hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
4947b3da895b151f21cf8008252be567e13c4b22 | diff --git a/openquake/engine/calculators/hazard/event_based/core.py b/openquake/engine/calculators/hazard/event_based/core.py
index <HASH>..<HASH> 100644
--- a/openquake/engine/calculators/hazard/event_based/core.py
+++ b/openquake/engine/calculators/hazard/event_based/core.py
@@ -85,7 +85,7 @@ def compute_ruptures(
ses_coll = models.SESCollection.objects.get(lt_model=trt_model.lt_model)
hc = models.HazardCalculation.objects.get(oqjob=job_id)
- all_ses = range(hc.ses_per_logic_tree_path)
+ all_ses = range(1, hc.ses_per_logic_tree_path + 1)
imts = map(from_string, hc.intensity_measure_types)
params = dict(
correl_model=general.get_correl_model(hc), | Fixed an off-by-one error | gem_oq-engine | train |
0d58da635e5443b63271455534d29031ab4b090b | diff --git a/tests/test-json-plugin.php b/tests/test-json-plugin.php
index <HASH>..<HASH> 100644
--- a/tests/test-json-plugin.php
+++ b/tests/test-json-plugin.php
@@ -19,7 +19,7 @@ class WP_Test_JSON_Plugin extends WP_UnitTestCase {
* The plugin should be installed and activated.
*/
function test_plugin_activated() {
- $this->assertTrue( class_exists( 'WP_JSON_Posts' ) );
+ $this->assertTrue( class_exists( 'WP_JSON_Posts_Controller' ) );
}
/** | Fix plugin activated test to use new controller class | WP-API_WP-API | train |
70a7a6e7fd04281809b946bb64fffe1f15f1201c | diff --git a/slick.grid.js b/slick.grid.js
index <HASH>..<HASH> 100644
--- a/slick.grid.js
+++ b/slick.grid.js
@@ -8,7 +8,7 @@
* (c) 2009-2010 Michael Leibman ([email protected])
* All rights reserved.
*
- * SlickGrid v1.0.0
+ * SlickGrid v1.1.0
*
* TODO:
* - frozen columns
@@ -16,25 +16,26 @@
*
*
* OPTIONS:
- * rowHeight - (default 25px) Row height in pixels.
- * enableAddRow - (default false) If true, a blank row will be displayed at the bottom - typing values in that row will add a new one.
- * leaveSpaceForNewRows - (default false)
- * editable - (default false) If false, no cells will be switched into edit mode.
- * editOnDoubleClick - (default false) Cell will not automatically go into edit mode without being double-clicked.
- * enableCellNavigation - (default true) If false, no cells will be selectable.
- * defaultColumnWidth - (default 80px) Default column width in pixels (if columns[cell].width is not specified).
- * enableColumnReorder - (default true) Allows the user to reorder columns.
- * asyncEditorLoading - (default false) Makes cell editors load asynchronously after a small delay.
- * This greatly increases keyboard navigation speed.
- * asyncEditorLoadDelay - (default 100msec) Delay after which cell editor is loaded. Ignored unless asyncEditorLoading is true.
- * forceFitColumns - (default false) Force column sizes to fit into the viewport (avoid horizontal scrolling).
- * enableAsyncPostRender - (default false) If true, async post rendering will occur and asyncPostRender delegates on columns will be called.
- * asyncPostRenderDelay - (default 60msec) Delay after which async post renderer delegate is called.
- * autoHeight - (default false) If true, vertically resizes to fit all rows.
- * editorLock - (default Slick.GlobalEditorLock) A Slick.EditorLock instance to use for controlling concurrent data edits.
+ * rowHeight - (default 25px) Row height in pixels.
+ * enableAddRow - (default false) If true, a blank row will be displayed at the bottom - typing values in that row will add a new one.
+ * leaveSpaceForNewRows - (default false)
+ * editable - (default false) If false, no cells will be switched into edit mode.
+ * editOnDoubleClick - (default false) Cell will not automatically go into edit mode without being double-clicked.
+ * enableCellNavigation - (default true) If false, no cells will be selectable.
+ * defaultColumnWidth - (default 80px) Default column width in pixels (if columns[cell].width is not specified).
+ * enableColumnReorder - (default true) Allows the user to reorder columns.
+ * asyncEditorLoading - (default false) Makes cell editors load asynchronously after a small delay.
+ * This greatly increases keyboard navigation speed.
+ * asyncEditorLoadDelay - (default 100msec) Delay after which cell editor is loaded. Ignored unless asyncEditorLoading is true.
+ * forceFitColumns - (default false) Force column sizes to fit into the viewport (avoid horizontal scrolling).
+ * enableAsyncPostRender - (default false) If true, async post rendering will occur and asyncPostRender delegates on columns will be called.
+ * asyncPostRenderDelay - (default 60msec) Delay after which async post renderer delegate is called.
+ * autoHeight - (default false) If true, vertically resizes to fit all rows.
+ * editorLock - (default Slick.GlobalEditorLock) A Slick.EditorLock instance to use for controlling concurrent data edits.
* showSecondaryHeaderRow - (default false) If true, an extra blank (to be populated externally) row will be displayed just below the header columns.
* secondaryHeaderRowHeight - (default 25px) The height of the secondary header row.
*
+ *
* COLUMN DEFINITION (columns) OPTIONS:
* id - Column ID.
* name - Column name to put in the header.
@@ -73,6 +74,7 @@
* onBeforeEditCell - Raised before a cell goes into edit mode. Return false to cancel. Args: row,cell,dataContext.
* onBeforeDestroy - Raised just before the grid control is destroyed (part of the destroy() method).
*
+ *
* NOTES:
* Cell/row DOM manipulations are done directly bypassing jQuery's DOM manipulation methods.
* This increases the speed dramatically, but can only be done safely because there are no event handlers
@@ -1751,7 +1753,7 @@ if (!jQuery.fn.drag) {
// Public API
$.extend(this, {
- "slickGridVersion": "1.0.0",
+ "slickGridVersion": "1.1.0",
// Events
"onSort": null, | Update documentation indentation and spacing + increment version to <I> (secondary header added) | coatue-oss_slickgrid2 | train |
1d774fd39782e585c0f9589276a127fe765deea6 | diff --git a/lib/einhorn/version.rb b/lib/einhorn/version.rb
index <HASH>..<HASH> 100644
--- a/lib/einhorn/version.rb
+++ b/lib/einhorn/version.rb
@@ -1,3 +1,3 @@
module Einhorn
- VERSION = '0.7.11'
+ VERSION = '0.7.12'
end | cut a new release of einhorn | stripe_einhorn | train |
b16f026deb9ba9b7323457b7a40df1cc966d7963 | diff --git a/scenarios/kubernetes_janitor.py b/scenarios/kubernetes_janitor.py
index <HASH>..<HASH> 100755
--- a/scenarios/kubernetes_janitor.py
+++ b/scenarios/kubernetes_janitor.py
@@ -134,8 +134,6 @@ def check_ci_jobs():
# Hard code node-ci project here
clean_project('k8s-jkns-ci-node-e2e')
- # gke internal project
- clean_project('gke-e2e-createdelete')
def main(mode, ratelimit, projects, age):
@@ -147,7 +145,7 @@ def main(mode, ratelimit, projects, age):
elif mode == 'custom':
projs = str.split(projects, ',')
for proj in projs:
- clean_project(proj, hours=age, ratelimit=ratelimit)
+ clean_project(proj.strip(), hours=age, ratelimit=ratelimit)
else:
check_ci_jobs() | strip spaces, also remove an internal project | kubernetes_test-infra | train |
6616e130239a818583f58dd038b7a80f2b4ff4d8 | diff --git a/lib/paper_trail/frameworks/rails/railtie.rb b/lib/paper_trail/frameworks/rails/railtie.rb
index <HASH>..<HASH> 100644
--- a/lib/paper_trail/frameworks/rails/railtie.rb
+++ b/lib/paper_trail/frameworks/rails/railtie.rb
@@ -2,13 +2,15 @@
module PaperTrail
# Represents code to load within Rails framework. See documentation in
- # `rails/railtie.rb`.
+ # `railties/lib/rails/railtie.rb`.
# @api private
class Railtie < ::Rails::Railtie
- # PaperTrail only has one initializer. The `initializer` method can take a
- # `before:` or `after:` argument, but that's only relevant for railties with
- # more than one initializer.
- initializer "paper_trail" do
+ # PaperTrail only has one initializer.
+ #
+ # We specify `before: "load_config_initializers"` to ensure that the PT
+ # initializer happens before "app initializers" (those defined in
+ # the app's `config/initalizers`).
+ initializer "paper_trail", before: "load_config_initializers" do
# `on_load` is a "lazy load hook". It "declares a block that will be
# executed when a Rails component is fully loaded". (See
# `active_support/lazy_load_hooks.rb`)
diff --git a/spec/dummy_app/config/application.rb b/spec/dummy_app/config/application.rb
index <HASH>..<HASH> 100644
--- a/spec/dummy_app/config/application.rb
+++ b/spec/dummy_app/config/application.rb
@@ -2,12 +2,14 @@
require File.expand_path("boot", __dir__)
-# Pick the frameworks you want:
-require "active_record/railtie"
-require "action_controller/railtie"
+# Here a conventional app would load the Rails components it needs, but we have
+# already loaded these in our spec_helper.
+# require "active_record/railtie"
+# require "action_controller/railtie"
-Bundler.require(:default, Rails.env)
-require "paper_trail"
+# Here a conventional app would require gems, but again, we have already loaded
+# these in our spec_helper.
+# Bundler.require(:default, Rails.env)
module Dummy
class Application < Rails::Application
diff --git a/spec/dummy_app/config/boot.rb b/spec/dummy_app/config/boot.rb
index <HASH>..<HASH> 100644
--- a/spec/dummy_app/config/boot.rb
+++ b/spec/dummy_app/config/boot.rb
@@ -1,18 +1,3 @@
# frozen_string_literal: true
-require "rubygems"
-
-# When you run rake locally (not on travis) in this dummy app, set the
-# BUNDLE_GEMFILE env. variable to ensure that the correct version of AR is used
-# for e.g. migrations. See examples in CONTRIBUTING.md.
-unless ENV.key?("BUNDLE_GEMFILE")
- gemfile = File.expand_path("../../../Gemfile", __dir__)
- if File.exist?(gemfile)
- puts "Booting PT test dummy app: Using gemfile: #{gemfile}"
- ENV["BUNDLE_GEMFILE"] = gemfile
- end
-end
-require "bundler"
-Bundler.setup
-
-$LOAD_PATH.unshift(File.expand_path("../../../lib", __dir__))
+# Unlike a conventional Rails app, our "dummy" app is booted by our spec_helper.
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -30,16 +30,45 @@ RSpec.configure do |config|
Kernel.srand config.seed
end
-require File.expand_path("dummy_app/config/environment", __dir__)
-require "rspec/rails"
-require "paper_trail/frameworks/rspec"
+# At this point, totally isolated unit tests could be run. But the PT test suite
+# also has "integration" tests, via a "dummy" Rails app. Here, we boot that
+# "dummy" app. The following process follows the same order, roughly, as a
+# conventional Rails app.
+#
+# In the past, this boot process was partially implemented here, and partially
+# in `dummy_app/config/*`. By consolidating it here,
+#
+# - It can better be understood, and documented in one place
+# - It can more closely resememble a conventional app boot. For example, loading
+# gems (like rspec-rails) _before_ loading the app.
+
+# First, `config/boot.rb` would add gems to $LOAD_PATH.
+Bundler.setup
+
+# Then, the chosen components of Rails would be loaded. In our case, we only
+# test with AR and AC.
+require "active_record/railtie"
+require "action_controller/railtie"
+
+# Then, gems are loaded. In a conventional Rails app, this would be done with
+# by the `Bundler.require` in `config/application.rb`.
+require "paper_trail"
require "ffaker"
+require "rspec/rails"
+require "rails-controller-testing"
-# Migrate
+# Now we can load our dummy app. Its boot process does not perfectly match a
+# conventional Rails app, but it's what we were able to fit in our test suite.
+require File.expand_path("dummy_app/config/environment", __dir__)
+
+# Now that AR has a connection pool, we can migrate the database.
require_relative "support/paper_trail_spec_migrator"
::PaperTrailSpecMigrator.new.migrate
+# This final section reselmbles what might be dummy_app's spec_helper, if it
+# had one.
+require "paper_trail/frameworks/rspec"
RSpec.configure do |config|
- config.fixture_path = "#{::Rails.root}/spec/fixtures"
+ config.fixture_path = nil # we use factories, not fixtures
config.use_transactional_fixtures = true
end | Document and make explicit certain "boot" order
- Ensure that the "paper_trail" initializer happens before the
end-user's initializers (in their app's config/initializers)
- Document the boot process of dummy_app and how it differs
from a conventional app.
This is a direct continuation of fc6c5f6, which was a collaboration
between Eric and myself, but I choose to make this a separate
commit, partly for vanity, and partly on the faint hope that it
might make review easier. | paper-trail-gem_paper_trail | train |
5fe82e7bbf6821a3d90fab98ad5e302a0976047d | diff --git a/xclim/indices/_agro.py b/xclim/indices/_agro.py
index <HASH>..<HASH> 100644
--- a/xclim/indices/_agro.py
+++ b/xclim/indices/_agro.py
@@ -395,8 +395,8 @@ def biologically_effective_degree_days(
else:
day_length = aggregate_between_dates(
day_lengths(dates=tasmin.time, lat=lat, method="simple"),
- start_date=start_date,
- end_date=end_date,
+ start=start_date,
+ end=end_date,
freq=freq,
)
k = 1
diff --git a/xclim/indices/_conversion.py b/xclim/indices/_conversion.py
index <HASH>..<HASH> 100644
--- a/xclim/indices/_conversion.py
+++ b/xclim/indices/_conversion.py
@@ -436,12 +436,12 @@ def saturation_vapor_pressure(
+ 2.7150305 * np.log(tas)
),
np.exp(
- +-5866.6426 / tas
+ -5866.6426 / tas
+ 22.32870244
+ 1.39387003e-2 * tas
+ -3.4262402e-5 * tas**2
+ 2.7040955e-8 * tas**3
- + 3.7063522e-1 * np.log(tas)
+ + 6.7063522e-1 * np.log(tas)
),
)
else:
diff --git a/xclim/testing/tests/test_atmos.py b/xclim/testing/tests/test_atmos.py
index <HASH>..<HASH> 100644
--- a/xclim/testing/tests/test_atmos.py
+++ b/xclim/testing/tests/test_atmos.py
@@ -280,9 +280,13 @@ class TestPotentialEvapotranspiration:
pet_tw48 = atmos.potential_evapotranspiration(tas=tm, method="TW48")
- np.testing.assert_allclose(pet_br65[0, 100:102], [np.nan, np.nan])
- np.testing.assert_allclose(pet_hg85[100:102, 0], [np.nan, np.nan])
- np.testing.assert_allclose(pet_tw48[0, 0], [np.nan])
+ np.testing.assert_allclose(
+ pet_br65.isel(location=0, time=slice(100, 102)), [np.nan, np.nan]
+ )
+ np.testing.assert_allclose(
+ pet_hg85.isel(location=0, time=slice(100, 102)), [np.nan, np.nan]
+ )
+ np.testing.assert_allclose(pet_tw48.isel(location=0, time=0), [np.nan])
class TestWaterBudget:
diff --git a/xclim/testing/tests/test_indices.py b/xclim/testing/tests/test_indices.py
index <HASH>..<HASH> 100644
--- a/xclim/testing/tests/test_indices.py
+++ b/xclim/testing/tests/test_indices.py
@@ -2458,10 +2458,10 @@ def test_water_budget_from_tas(pr_series, tasmin_series, tasmax_series, lat_seri
tx = tasmax_series(np.array([10, 15, 20]) + K2C).expand_dims(lat=lat)
out = xci.water_budget(pr, tasmin=tn, tasmax=tx, lat=lat, method="BR65")
- np.testing.assert_allclose(out[0, 2], [6.138921 / 86400], rtol=1e-3)
+ np.testing.assert_allclose(out[0, 2], 6.138921 / 86400, rtol=2e-3)
out = xci.water_budget(pr, tasmin=tn, tasmax=tx, lat=lat, method="HG85")
- np.testing.assert_allclose(out[0, 2], [6.037411 / 86400], rtol=1e-3)
+ np.testing.assert_allclose(out[0, 2], 6.037411 / 86400, rtol=2e-3)
time_std = date_range("1990-01-01", "1990-12-01", freq="MS", calendar="standard")
tm = xr.DataArray( | Fix tests and ITS-<I> | Ouranosinc_xclim | train |
63a00ebf4d8532a88d052d486a5750f678c84722 | diff --git a/CHANGES.md b/CHANGES.md
index <HASH>..<HASH> 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -2,6 +2,7 @@ Version 2.9.0.1
- Rename `redis.py` module as `client.py` to avoid naming conflicts from the nose plugin.
- Support contextmanager uses of `MockRedisLock`
+ - Support `string` operation: MSET
Version 2.9.0.0
diff --git a/mockredis/client.py b/mockredis/client.py
index <HASH>..<HASH> 100644
--- a/mockredis/client.py
+++ b/mockredis/client.py
@@ -332,6 +332,21 @@ class MockRedis(object):
"""Set the value of ``key`` to ``value`` if key doesn't exist"""
return self.set(key, value, nx=True)
+ def mset(self, *args, **kwargs):
+ """
+ Sets key/values based on a mapping. Mapping can be supplied as a single
+ dictionary argument or as kwargs.
+ """
+ if args:
+ if len(args) != 1 or not isinstance(args[0], dict):
+ raise RedisError('MSET requires **kwargs or a single dict arg')
+ mapping = args[0]
+ else:
+ mapping = kwargs
+ for key, value in mapping.items():
+ self.set(key, value)
+ return True
+
def msetnx(self, *args, **kwargs):
"""
Sets key/values based on a mapping if none of the keys are already set.
diff --git a/mockredis/tests/test_string.py b/mockredis/tests/test_string.py
index <HASH>..<HASH> 100644
--- a/mockredis/tests/test_string.py
+++ b/mockredis/tests/test_string.py
@@ -194,6 +194,11 @@ class TestRedisString(object):
def test_strict_setex_zero_expiration(self):
self.redis_strict.setex('key', 0, 'value')
+ def test_mset(self):
+ ok_(self.redis.mset({"key1": "hello", "key2": ""}))
+ ok_(self.redis.mset(**{"key3": "world", "key2": "there"}))
+ eq_(["hello", "there", "world"], self.redis.mget("key1", "key2", "key3"))
+
def test_msetnx(self):
ok_(self.redis.msetnx({"key1": "hello", "key2": "there"}))
ok_(not self.redis.msetnx(**{"key3": "world", "key2": "there"})) | Implement MSET
Issue #<I> | locationlabs_mockredis | train |
d08588230a82b7d1b6cc1164e950b819b40b9cd2 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -11,7 +11,7 @@ if __name__ == '__main__':
setup(
name='exactonline',
version='0.2.0',
- packages=['exactonline', 'exactonline.api'],
+ packages=['exactonline', 'exactonline.api', 'exactonline.elements'],
data_files=[('', ['LICENSE.txt', 'README.rst', 'CHANGES.rst'])],
description='Exact Online REST API Library in Python',
long_description=('\n\n\n'.join(long_descriptions)), | Add the missing 'exactonline.elements' to the dist package.
Reported by @hcwsegers. Closes #4. | ossobv_exactonline | train |
4c55b91b2b783bcf557614d2c8a0f4ba8d96a842 | diff --git a/superfly-wicket/src/main/java/com/payneteasy/superfly/wicket/PageInterceptingRequestMapper.java b/superfly-wicket/src/main/java/com/payneteasy/superfly/wicket/PageInterceptingRequestMapper.java
index <HASH>..<HASH> 100644
--- a/superfly-wicket/src/main/java/com/payneteasy/superfly/wicket/PageInterceptingRequestMapper.java
+++ b/superfly-wicket/src/main/java/com/payneteasy/superfly/wicket/PageInterceptingRequestMapper.java
@@ -24,8 +24,12 @@ public class PageInterceptingRequestMapper implements IRequestMapper {
@Override
public IRequestHandler mapRequest(Request request) {
IRequestHandler handler = delegate.mapRequest(request);
- return PageInterceptingRequestMapperLogic.resolve(request, handler,
- interceptionDecisions, interceptorPageClass);
+ if (handler == null) {
+ return handler;
+ } else {
+ return PageInterceptingRequestMapperLogic.resolve(request, handler,
+ interceptionDecisions, interceptorPageClass);
+ }
}
@Override
diff --git a/superfly-wicket/src/main/java/com/payneteasy/superfly/wicket/PageInterceptingRequestMapperLogic.java b/superfly-wicket/src/main/java/com/payneteasy/superfly/wicket/PageInterceptingRequestMapperLogic.java
index <HASH>..<HASH> 100644
--- a/superfly-wicket/src/main/java/com/payneteasy/superfly/wicket/PageInterceptingRequestMapperLogic.java
+++ b/superfly-wicket/src/main/java/com/payneteasy/superfly/wicket/PageInterceptingRequestMapperLogic.java
@@ -2,6 +2,7 @@ package com.payneteasy.superfly.wicket;
import org.apache.wicket.core.request.handler.*;
import org.apache.wicket.request.IRequestHandler;
+import org.apache.wicket.request.IRequestHandlerDelegate;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.component.IRequestablePage;
@@ -9,26 +10,35 @@ public class PageInterceptingRequestMapperLogic {
public static IRequestHandler resolve(Request request, IRequestHandler handler,
InterceptionDecisions interceptionDecisions,
Class<? extends IRequestablePage> interceptorPageClass) {
+ IRequestHandler result = handler;
if (interceptionDecisions.shouldIntercept(request)) {
boolean alreadyChanging = false;
- if (handler instanceof IPageRequestHandler) {
- IPageRequestHandler pageHandler = (IPageRequestHandler) handler;
+ IRequestHandler localHandler = unwrapDelegates(handler);
+ if (localHandler instanceof IPageRequestHandler) {
+ IPageRequestHandler pageHandler = (IPageRequestHandler) localHandler;
if (pageHandler.getPageClass() == interceptorPageClass) {
alreadyChanging = true;
}
}
if (!alreadyChanging) {
- if (handler instanceof IComponentRequestHandler) {
- IComponentRequestHandler iHandler = (IComponentRequestHandler) handler;
+ if (localHandler instanceof IComponentRequestHandler) {
+ IComponentRequestHandler iHandler = (IComponentRequestHandler) localHandler;
if (iHandler.getComponent().getPage().getClass() == interceptorPageClass) {
alreadyChanging = true;
}
}
}
if (!alreadyChanging) {
- handler = new RenderPageRequestHandler(new PageProvider(interceptorPageClass));
+ result = new RenderPageRequestHandler(new PageProvider(interceptorPageClass));
}
}
+ return result;
+ }
+
+ private static IRequestHandler unwrapDelegates(IRequestHandler handler) {
+ while (handler instanceof IRequestHandlerDelegate) {
+ handler = ((IRequestHandlerDelegate) handler).getDelegateHandler();
+ }
return handler;
} | Fixed a bug in PageInterceptingRequestMapperLogic: properly determining that we are on interceptor page
git-svn-id: <URL> | payneteasy_superfly | train |
f0d36493e69ac29ba0b201cae1dadfe6e7f8f44d | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -8,6 +8,7 @@ MAINTAINER_EMAIL = '[email protected]'
URL = 'http://github.com/blink1073/oct2py'
LICENSE = 'MIT'
REQUIRES = ["numpy (>= 1.7.1)", "scipy (>= 0.12)", "octave_kernel (>= 0.19)"]
+INSTALL_REQUIRES = ["octave_kernel >= 0.19"]
PACKAGES = [DISTNAME, '%s.tests' % DISTNAME, '%s/ipython' % DISTNAME,
'%s/ipython/tests' % DISTNAME]
PACKAGE_DATA = {DISTNAME: ['tests/*.m', '*.m']}
@@ -52,5 +53,6 @@ setup(
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
classifiers=list(filter(None, CLASSIFIERS.split('\n'))),
- requires=REQUIRES
+ requires=REQUIRES,
+ install_requires=INSTALL_REQUIRES
) | Add octave_kernel to install_requires | blink1073_oct2py | train |
d17b2c1a462273606438f3a42b16747d75e8d7f1 | diff --git a/src/Illuminate/Container/Container.php b/src/Illuminate/Container/Container.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/Container/Container.php
+++ b/src/Illuminate/Container/Container.php
@@ -81,6 +81,17 @@ class Container implements ArrayAccess {
}
/**
+ * Determine if the given abstract type has been resolved.
+ *
+ * @param string $abstract
+ * @return bool
+ */
+ public function resolved($abstract)
+ {
+ return isset($this->resolved[$abstract]) || isset($this->instances[$abstract]);
+ }
+
+ /**
* Determine if a given string is an alias.
*
* @param string $name
@@ -129,14 +140,12 @@ class Container implements ArrayAccess {
$concrete = $this->getClosure($abstract, $concrete);
}
- $bound = $this->bound($abstract);
-
$this->bindings[$abstract] = compact('concrete', 'shared');
- // If the abstract type was already bound in this container, we will fire the
+ // If the abstract type was already resolved in this container, we will fire the
// rebound listener so that any objects which have already gotten resolved
// can have their copy of the object updated via the listener callbacks.
- if ($bound)
+ if ($this->resolved($abstract))
{
$this->rebound($abstract);
}
@@ -405,8 +414,6 @@ class Container implements ArrayAccess {
{
$abstract = $this->getAlias($abstract);
- $this->resolved[$abstract] = true;
-
// If an instance of the type is currently being managed as a singleton we'll
// just return an existing instance instead of instantiating new instances
// so the developer can keep using the same objects instance every time.
@@ -439,6 +446,8 @@ class Container implements ArrayAccess {
$this->fireResolvingCallbacks($abstract, $object);
+ $this->resolved[$abstract] = true;
+
return $object;
}
diff --git a/src/Illuminate/Foundation/Application.php b/src/Illuminate/Foundation/Application.php
index <HASH>..<HASH> 100755
--- a/src/Illuminate/Foundation/Application.php
+++ b/src/Illuminate/Foundation/Application.php
@@ -464,6 +464,42 @@ class Application extends Container implements HttpKernelInterface, TerminableIn
}
/**
+ * Determine if the given abstract type has been bound.
+ *
+ * (Overriding Container::bound)
+ *
+ * @param string $abstract
+ * @return bool
+ */
+ public function bound($abstract)
+ {
+ return isset($this->deferredServices[$abstract]) || parent::bound($abstract);
+ }
+
+ /**
+ * "Extend" an abstract type in the container.
+ *
+ * (Overriding Container::extend)
+ *
+ * @param string $abstract
+ * @param Closure $closure
+ * @return void
+ *
+ * @throws \InvalidArgumentException
+ */
+ public function extend($abstract, Closure $closure)
+ {
+ $abstract = $this->getAlias($abstract);
+
+ if (isset($this->deferredServices[$abstract]))
+ {
+ $this->loadDeferredProvider($abstract);
+ }
+
+ return parent::extend($abstract, $closure);
+ }
+
+ /**
* Register a "before" application filter.
*
* @param Closure|string $callback | Fix logic around marking services resolved or not
If you app->extend an object after it's been bound but before it's
been resolved, it will be initialized right away. The solution is
to just check if an object has actually been resolved rather than
if it's bound.
A related issue that can also be solved as a part of this is that
you can't extend deferred services. This has also been fixed. | laravel_framework | train |
0ccbc450e8bd22200ee598726fe5cc7c2a5af2b1 | diff --git a/lib/Webforge/Common/DeprecatedException.php b/lib/Webforge/Common/DeprecatedException.php
index <HASH>..<HASH> 100644
--- a/lib/Webforge/Common/DeprecatedException.php
+++ b/lib/Webforge/Common/DeprecatedException.php
@@ -4,11 +4,11 @@ namespace Webforge\Common;
class DeprecatedException extends Exception {
- public static function fromClassMethod($class, $method) {
- return new static(sprintf('The classmethod %s::%s is deprecated', $class, $method));
+ public static function fromMethod($method) {
+ return new static(sprintf('The function %s is deprecated', $method));
}
- public static function fromClassMethodParam($class, $method, $paramNum, $msg) {
- return new static(sprintf('The parameter #%d from classmethod %s::%s is deprecated: %s', $paramNum, $class, $method, $msg));
+ public static function fromMethodParam($method, $paramNum, $msg) {
+ return new static(sprintf('The parameter #%d from function %s is deprecated: %s', $paramNum, $method, $msg));
}
} | change signature for deprecation for ability to use __FUNCTION__ | webforge-labs_webforge-common | train |
0bed6e537a7649f4025945b3285cbe1527b674d1 | diff --git a/selfupdate/selfupdate.go b/selfupdate/selfupdate.go
index <HASH>..<HASH> 100644
--- a/selfupdate/selfupdate.go
+++ b/selfupdate/selfupdate.go
@@ -87,7 +87,7 @@ func (u *Updater) BackgroundRun() {
//}
// TODO(bgentry): logger isn't on Windows. Replace w/ proper error reports.
if err := u.update(); err != nil {
- log.Fatal(err)
+ log.Println(err)
}
}
} | Removed log.Fatal as we dont want to stop the application if the update fails | sqs_go-selfupdate | train |
3212d2adc8882476f914800214542c1dd0b9a2fc | diff --git a/blocks_vertical/default_toolbox.js b/blocks_vertical/default_toolbox.js
index <HASH>..<HASH> 100644
--- a/blocks_vertical/default_toolbox.js
+++ b/blocks_vertical/default_toolbox.js
@@ -646,6 +646,7 @@ Blockly.Blocks.defaultToolbox = '<xml id="toolbox-categories" style="display: no
'<block type="extension_wedo_motor" id="extension_wedo_motor"></block>'+
'<block type="extension_wedo_hat" id="extension_wedo_hat"></block>'+
'<block type="extension_wedo_boolean" id="extension_wedo_boolean"></block>'+
+ '<block type="extension_wedo_reporter" id="extension_wedo_reporter"></block>'+
'<block type="extension_music_reporter" id="extension_music_reporter"></block>'+
'</category>'+
'</xml>';
diff --git a/blocks_vertical/extensions.js b/blocks_vertical/extensions.js
index <HASH>..<HASH> 100644
--- a/blocks_vertical/extensions.js
+++ b/blocks_vertical/extensions.js
@@ -133,6 +133,26 @@ Blockly.Blocks['extension_wedo_boolean'] = {
}
};
+Blockly.Blocks['extension_wedo_reporter'] = {
+ /**
+ * @this Blockly.Block
+ */
+ init: function() {
+ this.jsonInit({
+ "message0": "%1 width of this block",
+ "args0": [
+ {
+ "type": "field_image",
+ "src": Blockly.mainWorkspace.options.pathToMedia + "extensions/wedo2-block-icon.svg",
+ "width": 40,
+ "height": 40
+ }
+ ],
+ "category": Blockly.Categories.more,
+ "extensions": ["colours_more", "output_number"]
+ });
+ }
+};
Blockly.Blocks['extension_music_reporter'] = {
/** | Add another extension reporter block for test rendering | LLK_scratch-blocks | train |
b1fd8a2cfb4cb7a63cdd09e20066ff96b9a5cae4 | diff --git a/ext_emconf.php b/ext_emconf.php
index <HASH>..<HASH> 100644
--- a/ext_emconf.php
+++ b/ext_emconf.php
@@ -1,5 +1,5 @@
<?php
-$EM_CONF['replacecontent'] = [
+$EM_CONF[$_EXTKEY] = [
'title' => 'Replace Content',
'description' => 'Search and replace strings after page generation using regular expressions.',
'category' => 'fe', | Update ext_emconf.php
Replace extension name with $_EXTKEY | MaxServ_t3ext-replacecontent | train |
ab8ce62a8e702fafdb9a1a9a72321a3c6de8b3ee | diff --git a/BaragonData/src/main/java/com/hubspot/baragon/data/BaragonStateDatastore.java b/BaragonData/src/main/java/com/hubspot/baragon/data/BaragonStateDatastore.java
index <HASH>..<HASH> 100644
--- a/BaragonData/src/main/java/com/hubspot/baragon/data/BaragonStateDatastore.java
+++ b/BaragonData/src/main/java/com/hubspot/baragon/data/BaragonStateDatastore.java
@@ -144,12 +144,13 @@ public class BaragonStateDatastore extends AbstractDataStore {
List<String> matchingUpstreamPaths = matchingUpstreamPaths(currentUpstreams, upstreamInfo);
for (String matchingPath : matchingUpstreamPaths) {
String fullPath = String.format(UPSTREAM_FORMAT, serviceId, matchingPath);
- if (nodeExists(fullPath) && !pathsToDelete.contains(fullPath)) {
+ if (nodeExists(fullPath) && !pathsToDelete.contains(fullPath) && !fullPath.equals(addPath)) {
+ LOG.info(String.format("Deleting %s", fullPath));
pathsToDelete.add(fullPath);
transaction.delete().forPath(fullPath);
}
}
- if (!nodeExists(addPath)) {
+ if (!nodeExists(addPath) || pathsToDelete.contains(addPath)) {
transaction.create().forPath(addPath).and();
}
} | make sure a duplicate upstream with no rack is not deleted | HubSpot_Baragon | train |
cc2642b220958894c5a384530f32f622f76cd097 | diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/abstract_controller/rendering.rb
+++ b/actionpack/lib/abstract_controller/rendering.rb
@@ -160,11 +160,20 @@ module AbstractController
name = (options[:_template_name] || options[:action] || action_name).to_s
options[:_prefix] ||= _prefix if (options.keys & [:partial, :file, :template]).empty?
+ details = _normalize_details(options)
+
options[:_template] ||= with_template_cache(name) do
- find_template(name, { :formats => formats }, options)
+ find_template(name, details, options)
end
end
+ def _normalize_details(options)
+ details = { :formats => formats }
+ details[:formats] = Array(options[:format]) if options[:format]
+ details[:locale] = Array(options[:locale]) if options[:locale]
+ details
+ end
+
def find_template(name, details, options)
view_paths.find(name, details, options[:_prefix], options[:_partial])
end
diff --git a/actionpack/test/abstract/render_test.rb b/actionpack/test/abstract/render_test.rb
index <HASH>..<HASH> 100644
--- a/actionpack/test/abstract/render_test.rb
+++ b/actionpack/test/abstract/render_test.rb
@@ -17,7 +17,11 @@ module AbstractController
"renderer/symbol.erb" => "With Symbol",
"renderer/template_name.erb" => "With Template Name",
"string/with_path.erb" => "With String With Path",
- "some/file.erb" => "With File"
+ "some/file.erb" => "With File",
+ "with_format.html.erb" => "With html format",
+ "with_format.xml.erb" => "With xml format",
+ "with_locale.en.erb" => "With en locale",
+ "with_locale.pl.erb" => "With pl locale"
)]
def template
@@ -59,6 +63,22 @@ module AbstractController
def object
render :_template => ActionView::Template::Text.new("With Object")
end
+
+ def with_html_format
+ render :template => "with_format", :format => :html
+ end
+
+ def with_xml_format
+ render :template => "with_format", :format => :xml
+ end
+
+ def with_en_locale
+ render :template => "with_locale"
+ end
+
+ def with_pl_locale
+ render :template => "with_locale", :locale => :pl
+ end
end
class TestRenderer < ActiveSupport::TestCase
@@ -117,6 +137,25 @@ module AbstractController
assert_equal "With Object", @controller.response_body
end
+ def test_render_with_html_format
+ @controller.process(:with_html_format)
+ assert_equal "With html format", @controller.response_body
+ end
+
+ def test_render_with_xml_format
+ @controller.process(:with_xml_format)
+ assert_equal "With xml format", @controller.response_body
+ end
+
+ def test_render_with_en_locale
+ @controller.process(:with_en_locale)
+ assert_equal "With en locale", @controller.response_body
+ end
+
+ def test_render_with_pl_locale
+ @controller.process(:with_pl_locale)
+ assert_equal "With pl locale", @controller.response_body
+ end
end
end
end | Added :format and :locale options to render. | rails_rails | train |
c36de65ec59cb25ac19b435ed00d1a77261ac500 | diff --git a/js/trackView.js b/js/trackView.js
index <HASH>..<HASH> 100755
--- a/js/trackView.js
+++ b/js/trackView.js
@@ -293,6 +293,8 @@ var igv = (function (igv) {
*/
igv.TrackView.prototype.setContentHeight = function (newHeight) {
+ if (this.track.minHeight) newHeight = Math.max(this.track.minHeight, newHeight);
+
var contentHeightStr = newHeight + "px";
// Optionally adjust the trackDiv and viewport height to fit the content height, within min/max bounds | Constain content height to be >= viewport height | igvteam_igv.js | train |
2ff3f66dafcf7e742e6b60a30fc4573a6f6b1edd | diff --git a/src/sap.ui.fl/src/sap/ui/fl/LrepConnector.js b/src/sap.ui.fl/src/sap/ui/fl/LrepConnector.js
index <HASH>..<HASH> 100644
--- a/src/sap.ui.fl/src/sap/ui/fl/LrepConnector.js
+++ b/src/sap.ui.fl/src/sap/ui/fl/LrepConnector.js
@@ -339,7 +339,7 @@ sap.ui.define([
* - appDescriptor that belongs to actual component
* - siteId that belongs to actual component
* - layer up to which changes shall be read (excluding the specified layer)
- * @returns {Promise} Returns a Promise with the changes and componentClassName
+ * @returns {Promise} Returns a Promise with the changes (changes, contexts, optional messagebundle) and componentClassName
* @public
*/
Connector.prototype.loadChanges = function(sComponentClassName, mPropertyBag) {
@@ -360,7 +360,13 @@ sap.ui.define([
var sCacheKey = mPropertyBag.cacheKey;
// in case of no changes present according to async hints
if (sCacheKey === "<NO CHANGES>") {
- return Promise.resolve([]);
+ return Promise.resolve({
+ changes: {
+ changes : [],
+ contexts : []
+ },
+ componentClassName: sComponentClassName
+ });
}
if (sCacheKey) {
diff --git a/src/sap.ui.fl/test/sap/ui/fl/qunit/LrepConnector.qunit.js b/src/sap.ui.fl/test/sap/ui/fl/qunit/LrepConnector.qunit.js
index <HASH>..<HASH> 100644
--- a/src/sap.ui.fl/test/sap/ui/fl/qunit/LrepConnector.qunit.js
+++ b/src/sap.ui.fl/test/sap/ui/fl/qunit/LrepConnector.qunit.js
@@ -389,9 +389,12 @@
var oSendStub = this.stub(this.oLrepConnector, "send");
return this.oLrepConnector.loadChanges(sComponentClassName, mPropertyBag).then(function(oResult) {
- assert.ok(Array.isArray(oResult), "an array was returned");
- assert.equal(oResult.length, 0, "no changes are present");
- assert.equal(oSendStub.callCount, 0, "no backend request was triggered");
+ assert.ok(Array.isArray(oResult.changes.changes), "an array of changes was returned");
+ assert.ok(Array.isArray(oResult.changes.contexts), "an array of contexts was returned");
+ assert.equal(oResult.changes.changes.length, 0, "but no change is present");
+ assert.equal(oResult.changes.contexts.length, 0, "but no context is present");
+ assert.equal(oResult.componentClassName, sComponentClassName, "the component class name was returned correctly");
+ assert.equal(oSendStub.callCount, 0, "and no backend request was triggered");
});
}); | [INTERNAL][FIX] Correct cache entry format for component which has no
change yet.
Flex cache entry for a component which does not have any change need to
be in correct format so that first created changes can be added into
cache.
Change-Id: Ib<I>a<I>d<I>fac<I>d<I>bb<I>e<I>e<I>b0dad<I> | SAP_openui5 | train |
3fcfe1bb391a96a09910bd444252526d35604b19 | diff --git a/tests/Commands/CleanStatisticsTest.php b/tests/Commands/CleanStatisticsTest.php
index <HASH>..<HASH> 100644
--- a/tests/Commands/CleanStatisticsTest.php
+++ b/tests/Commands/CleanStatisticsTest.php
@@ -42,4 +42,34 @@ class CleanStatisticsTest extends TestCase
$this->assertCount(0, WebSocketsStatisticsEntry::where('created_at', '<', $cutOffDate)->get());
}
+
+ /** @test */
+ public function it_can_clean_the_statistics_for_app_id_only()
+ {
+ Collection::times(60)->each(function (int $index) {
+ WebSocketsStatisticsEntry::create([
+ 'app_id' => 'app_id',
+ 'peak_connection_count' => 1,
+ 'websocket_message_count' => 2,
+ 'api_message_count' => 3,
+ 'created_at' => Carbon::now()->subDays($index)->startOfDay(),
+ ]);
+ });
+
+ Collection::times(60)->each(function (int $index) {
+ WebSocketsStatisticsEntry::create([
+ 'app_id' => 'app_id2',
+ 'peak_connection_count' => 1,
+ 'websocket_message_count' => 2,
+ 'api_message_count' => 3,
+ 'created_at' => Carbon::now()->subDays($index)->startOfDay(),
+ ]);
+ });
+
+ $this->assertCount(120, WebSocketsStatisticsEntry::all());
+
+ Artisan::call('websockets:clean', ['appId' => 'app_id']);
+
+ $this->assertCount(91, WebSocketsStatisticsEntry::all());
+ }
} | Added test for app_id | beyondcode_laravel-websockets | train |
1fbd7538612ec611166a7ec22353867bdfc5ab3e | diff --git a/shovel/__init__.py b/shovel/__init__.py
index <HASH>..<HASH> 100755
--- a/shovel/__init__.py
+++ b/shovel/__init__.py
@@ -253,14 +253,37 @@ class Task(object):
print '=' * 30
print '%s%s' % (self.name, repr(args))
+def help_helper(tasks):
+ # This tries to print the reported tasks in a nice, heirarchical fashion
+ modules = []
+ for task in tasks:
+ # Get the module names for the task
+ m = task.fullname.split('.')
+ name = m.pop()
+ # If there are multiple layers here, then we should
+ # print a heirarchical structure.
+ unmatched = []
+ for i in range(len(m)):
+ if i >= len(modules):
+ unmatched = m[i:]
+ break
+ elif modules[i] != m[i]:
+ unmatched = m[i:]
+ modules = modules[:i]
+ break
+ for module in unmatched:
+ print '\t' * len(modules) + module + '/'
+ modules.append(module)
+
+ if len(task.doc) > 50:
+ print '%30s => %s...' % (task.fullname, task.doc[0:47])
+ else:
+ print '%30s => %s' % (task.fullname, task.doc)
+
def help(*names):
'''Display information about the provided task name, or available tasks'''
if not len(names):
- for task in Task.find():
- if len(task.doc) > 50:
- print '%30s => %s...' % (task.fullname, task.doc[0:47])
- else:
- print '%30s => %s' % (task.fullname, task.doc)
+ help_helper(Task.find())
else:
for name in names:
tasks = Task.find(name)
@@ -269,11 +292,7 @@ def help(*names):
elif len(tasks) == 1:
tasks[0].help()
else:
- for task in tasks:
- if len(task.doc) > 50:
- print '%30s => %s...' % (task.fullname, task.doc[0:47])
- else:
- print '%30s => %s' % (task.fullname, task.doc)
+ help_helper(tasks)
def load():
'''Load tasks from files''' | Cleaned up the help messaging information. | seomoz_shovel | train |
51a02ae616215d397cd6fa8d20e387ed9f441ec7 | diff --git a/sos/plugins/networking.py b/sos/plugins/networking.py
index <HASH>..<HASH> 100644
--- a/sos/plugins/networking.py
+++ b/sos/plugins/networking.py
@@ -121,47 +121,38 @@ class Networking(Plugin):
# "nmcli" objects.
# NetworkManager >= 0.9.9 (Use long names of objects for nmcli)
- nmcli_status_result = self.call_ext_prog("nmcli general status")
- if nmcli_status_result['status'] == 0:
+ nmcli_con_details_cmd = ""
+ nmcli_dev_details_cmd = ""
+ if self.call_ext_prog("nmcli general status")['status'] == 0:
self.add_cmd_output([
"nmcli general status",
- "nmcli connection show",
- "nmcli connection show --active",
- "nmcli device status",
- "nmcli device show"])
- nmcli_con_show_result = self.call_ext_prog(
- "nmcli --terse --fields NAME con show")
- if nmcli_con_show_result['status'] == 0:
- for con in nmcli_con_show_result['output'].splitlines():
- self.add_cmd_output("nmcli connection show id '%s'" % con)
-
- nmcli_dev_status_result = self.call_ext_prog(
- "nmcli --terse --fields DEVICE device status")
- if nmcli_dev_status_result['status'] == 0:
- for dev in nmcli_dev_status_result['output'].splitlines():
- self.add_cmd_output("nmcli device show '%s'" % dev)
-
+ "nmcli con",
+ "nmcli con show --active",
+ "nmcli dev"])
+ nmcli_con_details_cmd = "nmcli con show id"
+ nmcli_dev_details_cmd = "nmcli dev show"
# NetworkManager < 0.9.9 (Use short name of objects for nmcli)
- nmcli_status_result = self.call_ext_prog("nmcli nm status")
- if nmcli_status_result['status'] == 0:
+ elif self.call_ext_prog("nmcli nm status")['status'] == 0:
self.add_cmd_output([
"nmcli nm status",
"nmcli con",
"nmcli con status",
- "nmcli dev status",
"nmcli dev"])
+ nmcli_con_details_cmd = "nmcli con list id"
+ nmcli_dev_details_cmd = "nmcli dev list iface"
+ if len(nmcli_con_details_cmd) > 0:
nmcli_con_show_result = self.call_ext_prog(
"nmcli --terse --fields NAME con")
if nmcli_con_show_result['status'] == 0:
for con in nmcli_con_show_result['output'].splitlines():
- self.add_cmd_output("nmcli con list id '%s'" % con)
+ self.add_cmd_output("%s '%s'" % nmcli_con_details_cmd, con)
nmcli_dev_status_result = self.call_ext_prog(
- "nmcli --terse --fields DEVICE dev status")
+ "nmcli --terse --fields DEVICE dev")
if nmcli_dev_status_result['status'] == 0:
for dev in nmcli_dev_status_result['output'].splitlines():
- self.add_cmd_output("nmcli dev list iface '%s'" % dev)
+ self.add_cmd_output("%s '%s'" % nmcli_dev_details_cmd, dev)
ip_link_result = self.call_ext_prog("ip -o link")
if ip_link_result['status'] == 0: | [networking] Simplified the collecting of nmcli output
Simplified the collecting of nmcli output and used same
name for nmcli's objects when possible. | sosreport_sos | train |
509618259f9619c5ce77a384edf67c1c236bd7ed | diff --git a/src/main/java/mesosphere/marathon/client/utils/MarathonException.java b/src/main/java/mesosphere/marathon/client/utils/MarathonException.java
index <HASH>..<HASH> 100644
--- a/src/main/java/mesosphere/marathon/client/utils/MarathonException.java
+++ b/src/main/java/mesosphere/marathon/client/utils/MarathonException.java
@@ -9,8 +9,15 @@ public class MarathonException extends Exception {
this.status = status;
this.message = message;
}
-
- @Override
+
+ /**
+ * Gets the HTTP status code of the failure, such as 404.
+ */
+ public int getStatus() {
+ return status;
+ }
+
+ @Override
public String getMessage() {
return message + " (http status: " + status + ")";
} | Expose the HTTP status code of the failure.
... so that for example <I> (not found) cannot be processed differently
from <I> (server temporarily unavailable) | mohitsoni_marathon-client | train |
3c6f6c26c3df50db1491f88c4bcd84a5fd5d19d8 | diff --git a/Swat/SwatToolLink.php b/Swat/SwatToolLink.php
index <HASH>..<HASH> 100644
--- a/Swat/SwatToolLink.php
+++ b/Swat/SwatToolLink.php
@@ -53,7 +53,7 @@ class SwatToolLink extends SwatControl
/**
* The stock id of this tool link
*
- * Specifying a stock id initialized this tool link with a set of
+ * Specifying a stock id initializes this tool link with a set of
* stock values.
*
* @var string
@@ -90,7 +90,7 @@ class SwatToolLink extends SwatControl
else
$anchor_tag->href = sprintf($this->link, $this->value);
- if ($this->class !== null)
+ if ($this->class === null)
$anchor_tag->class = 'swat-tool-link';
else
$anchor_tag->class = 'swat-tool-link '.$this->class;
@@ -108,6 +108,7 @@ class SwatToolLink extends SwatControl
* - edit
* - delete
* - preview
+ * - change-order
*
* @param string $stock_id the identifier of the stock type to use.
* @param boolean $overwrite_properties whether to overwrite properties if
@@ -138,6 +139,11 @@ class SwatToolLink extends SwatControl
$class = 'swat-tool-link-preview';
break;
+ case 'change-order':
+ $title = Swat::_('Change Order');
+ $class = 'swat-tool-link-order';
+ break;
+
default:
throw new SwatException("Stock type with id of '{$stock_id}' not ".
'found.'); | - Fixed a couple of typos (one in a docblock and one baddy in ::display()).
- Added a change-order stock id.
svn commit r<I> | silverorange_swat | train |
f795301f9063557d4876e1fd4d4de70e4b7b31eb | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -58,8 +58,7 @@ tests_require = [
'pep8',
'flake8',
'flake8-quotes==0.8.1',
- 'hypothesis~=3.18.5',
- 'hypothesis-regex',
+ 'hypothesis>=5.3.0',
# Removed pylint because its GPL license isn't Apache2-compatible
'pytest>=3.0.0',
'pytest-cov>=2.2.1',
diff --git a/tests/common/test_schema.py b/tests/common/test_schema.py
index <HASH>..<HASH> 100644
--- a/tests/common/test_schema.py
+++ b/tests/common/test_schema.py
@@ -9,7 +9,7 @@ properties related to validation.
from unittest.mock import patch
from hypothesis import given
-from hypothesis_regex import regex
+from hypothesis.strategies import from_regex as regex
from pytest import raises
from bigchaindb.common.exceptions import SchemaValidationError | Update Hypothesis (#<I>)
Fixes #<I> | bigchaindb_bigchaindb | train |
7654e56bd7ca1d044fb592947108f0761c252994 | diff --git a/bundlewatch.config.js b/bundlewatch.config.js
index <HASH>..<HASH> 100644
--- a/bundlewatch.config.js
+++ b/bundlewatch.config.js
@@ -6,7 +6,7 @@ const bundlewatchConfig = {
},
{
path: './dist/cloudinary-core-shrinkwrap.min.js',
- maxSize: '31kb'
+ maxSize: '32kb'
},
{
path: './dist/cloudinary-jquery.min.js',
diff --git a/src/util/xhr/getBlobFromURL.js b/src/util/xhr/getBlobFromURL.js
index <HASH>..<HASH> 100644
--- a/src/util/xhr/getBlobFromURL.js
+++ b/src/util/xhr/getBlobFromURL.js
@@ -1,4 +1,19 @@
/**
+ * Reject on timeout
+ * @param maxTimeoutMS
+ * @param reject
+ * @returns {number} timerID
+ */
+function rejectOnTimeout(maxTimeoutMS, reject) {
+ return setTimeout(() => {
+ reject({
+ status: 'error',
+ message: 'Timeout loading Blob URL'
+ });
+ }, maxTimeoutMS);
+}
+
+/**
* @description Converts a URL to a BLOB URL
* @param {string} urlToLoad
* @param {number} max_timeout_ms - Time to elapse before promise is rejected
@@ -10,34 +25,67 @@
* }
* }>}
*/
-function getBlobFromURL(urlToLoad, max_timeout_ms) {
+function getBlobFromURL(urlToLoad, maxTimeoutMS) {
return new Promise((resolve, reject) => {
- let timerID = setTimeout(() => {
- reject({
- status: 'error',
- message: 'Timeout loading Blob URL'
- });
- }, max_timeout_ms);
+ const timerID = rejectOnTimeout(maxTimeoutMS, reject);
- let xhr = new XMLHttpRequest();
- xhr.responseType = 'blob';
- xhr.onload = function (response) {
- clearTimeout(timerID); // clear timeout reject error
+ // If fetch exists, use it to fetch blob, otherwise use XHR.
+ // XHR causes issues on safari 14.1 so we prefer fetch
+ const fetchBlob = (typeof fetch !== 'undefined' && fetch) ? loadUrlUsingFetch : loadUrlUsingXhr;
+
+ fetchBlob(urlToLoad).then((blob) => {
resolve({
status: 'success',
payload: {
- blobURL: URL.createObjectURL(xhr.response)
+ blobURL: URL.createObjectURL(blob)
}
});
- };
-
- xhr.onerror = function () {
- clearTimeout(timerID); // clear timeout reject error
+ }).catch(() => {
reject({
status: 'error',
message: 'Error loading Blob URL'
});
+ }).finally(() => {
+ // Clear the timeout timer on fail or success.
+ clearTimeout(timerID);
+ });
+ });
+}
+
+/**
+ * Use fetch function to fetch file
+ * @param urlToLoad
+ * @returns {Promise<unknown>}
+ */
+function loadUrlUsingFetch(urlToLoad) {
+ return new Promise((resolve, reject) => {
+ fetch(urlToLoad).then((response) => {
+ response.blob().then((blob) => {
+ resolve(blob);
+ });
+ }).catch(() => {
+ reject('error');
+ });
+ });
+}
+
+/**
+ * Use XHR to fetch file
+ * @param urlToLoad
+ * @returns {Promise<unknown>}
+ */
+function loadUrlUsingXhr(urlToLoad) {
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.responseType = 'blob';
+ xhr.onload = function (response) {
+ resolve(xhr.response);
};
+
+ xhr.onerror = function () {
+ reject('error');
+ };
+
xhr.open('GET', urlToLoad, true);
xhr.send();
}); | Fix transparent video on safari <I> by using fetch instead of XHR (#<I>) | cloudinary_cloudinary_js | train |
6278a86145ff1b152df0fef81296171ee9d462c6 | diff --git a/src/FeedIo/Adapter/Client.php b/src/FeedIo/Adapter/Client.php
index <HASH>..<HASH> 100644
--- a/src/FeedIo/Adapter/Client.php
+++ b/src/FeedIo/Adapter/Client.php
@@ -11,24 +11,11 @@ use Psr\Http\Client\ClientInterface as PsrClientInterface;
class Client implements ClientInterface
{
- public const DEFAULT_USER_AGENT = 'Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1';
-
- public function __construct(private PsrClientInterface $client, private string $userAgent = self::DEFAULT_USER_AGENT)
+ public function __construct(private PsrClientInterface $client)
{
}
/**
- * @param string $userAgent The new user-agent
- * @return self
- */
- public function setUserAgent(string $userAgent): Client
- {
- $this->userAgent = $userAgent;
-
- return $this;
- }
-
- /**
* @param string $url
* @param DateTime|null $modifiedSince
* @return ResponseInterface
@@ -81,7 +68,6 @@ class Client implements ClientInterface
{
$headers = [
'Accept-Encoding' => 'gzip, deflate',
- 'User-Agent' => $this->userAgent,
];
if ($modifiedSince) {
diff --git a/src/FeedIo/FeedIo.php b/src/FeedIo/FeedIo.php
index <HASH>..<HASH> 100644
--- a/src/FeedIo/FeedIo.php
+++ b/src/FeedIo/FeedIo.php
@@ -5,11 +5,11 @@ declare(strict_types=1);
namespace FeedIo;
use DateTime;
-use FeedIo\Adapter\ClientInterface;
-use FeedIo\Adapter\NullClient;
+use FeedIo\Adapter\Client;
use FeedIo\Http\ResponseBuilder;
use FeedIo\Reader\Result;
use FeedIo\Rule\DateTimeBuilderInterface;
+use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
@@ -67,10 +67,14 @@ class FeedIo
protected Reader $reader;
public function __construct(
- protected ClientInterface $client = new NullClient(),
+ ?ClientInterface $client = null,
protected LoggerInterface $logger = new NullLogger(),
protected ?SpecificationInterface $specification = null,
) {
+ if (is_null($client)) {
+ throw new \Exception('You must provide a PSR18-compliant HTTP client');
+ }
+ $this->client = new Client($client);
if (is_null($this->specification)) {
$this->specification = new Specification($this->logger);
} | Pass PSR-<I> compliant HTTP client to FeedIo facade | alexdebril_feed-io | train |
50bc85219a6a8f9e1654568920d94b172b8f3f8a | diff --git a/tests/mobanfile/test_targets.py b/tests/mobanfile/test_targets.py
index <HASH>..<HASH> 100644
--- a/tests/mobanfile/test_targets.py
+++ b/tests/mobanfile/test_targets.py
@@ -36,6 +36,7 @@ def test_handling_group_target():
def test_extract_group_targets():
test_targets = [
+ {"output": "a.output", "template": "a.template.jj2"},
{"copy": [{"output": "source"}], "copy1": [{"output1": "source1"}]}
]
actual = targets.extract_group_targets("copy1", test_targets) | :microscope: more test coverage | moremoban_moban | train |
5e6d2202f7639e09de46f900673acc3f35d66f4d | diff --git a/src/main/java/reactor/netty/resources/PooledConnectionProvider.java b/src/main/java/reactor/netty/resources/PooledConnectionProvider.java
index <HASH>..<HASH> 100644
--- a/src/main/java/reactor/netty/resources/PooledConnectionProvider.java
+++ b/src/main/java/reactor/netty/resources/PooledConnectionProvider.java
@@ -147,8 +147,9 @@ final class PooledConnectionProvider implements ConnectionProvider {
InstrumentedPool<PooledConnection> pool = channelPools.computeIfAbsent(holder, poolKey -> {
if (log.isDebugEnabled()) {
- log.debug("Creating new client pool [{}] for {}",
- name, bootstrap.config().remoteAddress());
+ String poolType = maxConnections == -1 ? "elastic" : "fixed";
+ log.debug("Creating a new {} client pool with name [{}] and max connections [{}] for [{}]",
+ poolType, name, maxConnections, bootstrap.config().remoteAddress());
}
InstrumentedPool<PooledConnection> newPool =
@@ -266,7 +267,7 @@ final class PooledConnectionProvider implements ConnectionProvider {
Channel ch = ctx.channel();
if (log.isDebugEnabled()) {
- log.debug(format(ch, "Created new pooled channel, now {} active connections and {} inactive connections"),
+ log.debug(format(ch, "Created a new pooled channel, now {} active connections and {} inactive connections"),
pool.metrics().acquiredSize(),
pool.metrics().idleSize());
} | fix #<I> Add more information in the logs for the connection pool that will be used | reactor_reactor-netty | train |
2e6b3747c9861f5ea7804111f1466e89ff1120e3 | diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -18,7 +18,7 @@
"supertest": "0.15.0",
"thehelp-project": "3.4.1",
"thehelp-test": "3.3.0",
- "winston": "0.8.3"
+ "winston": "0.9.0"
},
"scripts": {
diff --git a/src/server/graceful.js b/src/server/graceful.js
index <HASH>..<HASH> 100644
--- a/src/server/graceful.js
+++ b/src/server/graceful.js
@@ -223,26 +223,12 @@ Graceful.prototype._clearTimers = function _clearTimers() {
};
/*
-`_finalLog` makes a final log entry then takes down the process when that log call is
-complete.
-
-_Why so complex? To ensure that any `winston` file transports are properly flushed. You'll
-note without this, if `_die()` is called directly in `_exit()` above, the main integration
-tests will result in log files without the final 'about to exit with code X' entries._
+`_finalLog` makes a final log entry then waits until the next turn of the event loop to
+call process exit, attempting to give the filesystem enough time to flush to disk.
*/
Graceful.prototype._finalLog = function _finalLog(type, message) {
- var _this = this;
-
- var die = localUtil.once(function() {
- _this._die();
- });
-
- this.log[type](message, function(err, level, msg, meta) {
- /*jshint unused: false */
- die();
- });
-
- setTimeout(die, 250);
+ this.log[type](message);
+ setTimeout(this._die.bind(this), 0);
};
// `_die` calls `process._exit()` with the right error code based on `this.error` (set in
diff --git a/test/integration/server/test_logging.js b/test/integration/server/test_logging.js
index <HASH>..<HASH> 100644
--- a/test/integration/server/test_logging.js
+++ b/test/integration/server/test_logging.js
@@ -130,14 +130,4 @@ describe('winston creates expected log files', function() {
});
});
- it('waited until the final log entry made it into the file', function() {
- if (!winston) {
- return;
- }
-
- var contents = fs.readFileSync(path.join(util.logsDir, logFiles[1]));
- contents = contents.toString();
- expect(contents).to.match(/Worker #1 about to exit with code 1/);
- });
-
});
diff --git a/test/unit/server/test_graceful.js b/test/unit/server/test_graceful.js
index <HASH>..<HASH> 100644
--- a/test/unit/server/test_graceful.js
+++ b/test/unit/server/test_graceful.js
@@ -270,16 +270,7 @@ describe('Graceful', function() {
});
describe('#_finalLog', function() {
- it('calls _die when log calls callback', function(done) {
- graceful.log = {
- info: sinon.stub().yields()
- };
- graceful._die = done;
-
- graceful._finalLog('info', 'log string');
- });
-
- it('calls _die if log never calls callback', function(done) {
+ it('calls _die', function(done) {
graceful.log = {
info: sinon.stub()
}; | Remove fanciness in Graceful._finalLog
On today’s upgrade to winston, discovered that relying on winston’s callback didn’t always ensure that the final log message had flushed to disk. So now we just do a setTimeout(fn, 0) for the next turn of the event loop. | thehelp_cluster | train |
427183b6a6cd17bb7333e1ac1fb6a58601e9b359 | diff --git a/bosh-director-core/lib/bosh/director/core/templates/job_template_renderer.rb b/bosh-director-core/lib/bosh/director/core/templates/job_template_renderer.rb
index <HASH>..<HASH> 100644
--- a/bosh-director-core/lib/bosh/director/core/templates/job_template_renderer.rb
+++ b/bosh-director-core/lib/bosh/director/core/templates/job_template_renderer.rb
@@ -62,7 +62,9 @@ module Bosh::Director::Core::Templates
# Make a deep copy of the spec and replace the properties with
# the specific template properties.
altered_spec = Bosh::Common::DeepCopy.copy(spec)
- altered_spec['properties'] = current_template['template_scoped_properties']
+ altered_spec['properties'] = Bosh::Common::DeepCopy.copy(
+ current_template['template_scoped_properties']
+ )
result = altered_spec
end
end | allow specifying properties on a job in the deployment manifest
Make a deep copy of a variable to avoid weird errors
[#<I>]
<URL> | cloudfoundry_bosh | train |
ea5650252c603d034caa520647e6b86dbda9f939 | diff --git a/lib/httpimagestore/configuration/validate_hmac.rb b/lib/httpimagestore/configuration/validate_hmac.rb
index <HASH>..<HASH> 100644
--- a/lib/httpimagestore/configuration/validate_hmac.rb
+++ b/lib/httpimagestore/configuration/validate_hmac.rb
@@ -1,4 +1,5 @@
require 'httpimagestore/configuration/handler/statement'
+require 'securerandom'
module Configuration
class NoSecretKeySpecifiedError < ConfigurationError
@@ -123,6 +124,7 @@ module Configuration
actual_hmac = OpenSSL::HMAC.hexdigest(digest, @secret, uri)
if actual_hmac != expected_hmac
+ sleep SecureRandom.random_number/10 # sleep some random time to make timing attack harder
log.warn "invalid HMAC with digest '#{@digest}' for URI '#{uri}'; expected HMAC '#{expected_hmac}'"
ValidateHMAC.stats.incr_total_invalid_hmac
raise HMACMismatchError.new(expected_hmac, uri, @digest) | sleep some random time to make timing attack harder | jpastuszek_httpimagestore | train |
f4e1cb7448dfbee54770aa38fe8b933c7a6b6ac1 | diff --git a/test_pylast.py b/test_pylast.py
index <HASH>..<HASH> 100755
--- a/test_pylast.py
+++ b/test_pylast.py
@@ -344,13 +344,34 @@ class TestPyLast(unittest.TestCase):
self.assertTrue(type(tags[0]) == pylast.TopItem)
+ def test_track_is_hashable(self):
+ # TODO same for some other types
+ # https://github.com/hugovk/pylast/issues/82
+ # (passes in Python 2.7 but how about 3?)
+
+ # Arrange
+ lastfm_user = self.network.get_user(self.username)
+ track = lastfm_user.get_recent_tracks(limit = 1)[0]
+ tracks = set()
+
+ # Act
+ tracks.add(track)
+
+ # Assert
+ self.assertIsNotNone(track)
+ self.assertEqual(len(tracks), 1)
+
+
if __name__ == '__main__':
-# suite = unittest.TestSuite()
-# suite.addTest(TestPyLast('test_scrobble'))
-# suite.addTest(TestPyLast('test_unscrobble'))
-# unittest.TextTestRunner().run(suite)
+ # For quick testing of a single-case (eg. test = "test_track_is_hashable"
+ test = ""
- unittest.main()
+ if test is not None and len(test):
+ suite = unittest.TestSuite()
+ suite.addTest(TestPyLast(test))
+ unittest.TextTestRunner().run(suite)
+ else:
+ unittest.main()
# End of file | Add test case for #<I>. Passes as expected with Python <I>, but need to test in 3 | pylast_pylast | train |
69d0710481a8d5d475a812a956b8493db918404f | diff --git a/lib/chef/provider/zypper_repository.rb b/lib/chef/provider/zypper_repository.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/provider/zypper_repository.rb
+++ b/lib/chef/provider/zypper_repository.rb
@@ -123,7 +123,7 @@ class Chef
# matches 2.0 and 2.2 versions from SLES 12 and 15: https://rubular.com/r/e6D0WfGK6SXvUp
version = %r{gpg \(GnuPG\)\s*(.*)}.match(so.stdout)[1]
logger.trace("GPG package version is #{version}")
- version
+ Gem::Version.new(version)
end
# is the provided key already installed | Make sure gpg_version is actually a version object | chef_chef | train |
6d61d9cf6996b8e3a684292655d85ae02a3a0120 | diff --git a/composer.json b/composer.json
index <HASH>..<HASH> 100644
--- a/composer.json
+++ b/composer.json
@@ -23,10 +23,10 @@
"php-di/php-di": "~6.0"
},
"require-dev": {
- "phpunit/phpunit": "~8.2",
- "squizlabs/php_codesniffer": "~3.4",
+ "phpunit/phpunit": "~8.4",
+ "squizlabs/php_codesniffer": "~3.5",
"pdepend/pdepend": "~2.5",
- "phpmd/phpmd": "~2.6",
+ "phpmd/phpmd": "~2.7",
"sebastian/phpcpd": "~4.1",
"phploc/phploc": "~5.0",
"behat/behat": "~3.5",
diff --git a/src/symfony/Http/Client.php b/src/symfony/Http/Client.php
index <HASH>..<HASH> 100644
--- a/src/symfony/Http/Client.php
+++ b/src/symfony/Http/Client.php
@@ -56,7 +56,7 @@ class Client implements ClientWithResponseEventInterface
/**
* @var HttpFoundationFactory
*/
- private $httpFoundationFactory;
+ private $factory;
/**
* Client constructor.
@@ -66,7 +66,7 @@ class Client implements ClientWithResponseEventInterface
*/
public function __construct(HttpFoundationFactory $factory, GetResponseEvent $getResponseEvent = null)
{
- $this->httpFoundationFactory = $factory;
+ $this->factory = $factory;
if ($getResponseEvent instanceof GetResponseEvent) {
$this->setGetResponseEvent($getResponseEvent);
}
@@ -124,7 +124,7 @@ class Client implements ClientWithResponseEventInterface
}
$this->getResponseEvent->setResponse(
- $this->httpFoundationFactory->createResponse($this->response)
+ $this->factory->createResponse($this->response)
);
$this->response = null;
@@ -146,7 +146,7 @@ class Client implements ClientWithResponseEventInterface
*/
public function __clone()
{
- $this->httpFoundationFactory = clone $this->httpFoundationFactory;
+ $this->factory = clone $this->factory;
if (!empty($this->getResponseEvent)) {
$this->getResponseEvent = clone $this->getResponseEvent;
}
diff --git a/src/symfony/Listener/KernelListener.php b/src/symfony/Listener/KernelListener.php
index <HASH>..<HASH> 100644
--- a/src/symfony/Listener/KernelListener.php
+++ b/src/symfony/Listener/KernelListener.php
@@ -54,7 +54,7 @@ class KernelListener
/**
* @var ClientWithResponseEventInterface
*/
- private $clientWithResponseEvent;
+ private $client;
/**
* @var DiactorosFactory
@@ -74,7 +74,7 @@ class KernelListener
DiactorosFactory $diactorosFactory
) {
$this->manager = $manager;
- $this->clientWithResponseEvent = $event;
+ $this->client = $event;
$this->diactorosFactory = $diactorosFactory;
}
@@ -110,7 +110,7 @@ class KernelListener
return $this;
}
- $client = clone $this->clientWithResponseEvent;
+ $client = clone $this->client;
$client->setGetResponseEvent($event);
$psrRequest = $this->getPsrRequest($event->getRequest());
diff --git a/tests/symfony/Http/ClientTest.php b/tests/symfony/Http/ClientTest.php
index <HASH>..<HASH> 100644
--- a/tests/symfony/Http/ClientTest.php
+++ b/tests/symfony/Http/ClientTest.php
@@ -413,7 +413,7 @@ class ClientTest extends \PHPUnit\Framework\TestCase
self::assertInstanceOf(Client::class, $clonedClient);
- $reflectionProperty = new \ReflectionProperty($clonedClient, 'httpFoundationFactory');
+ $reflectionProperty = new \ReflectionProperty($clonedClient, 'factory');
$reflectionProperty->setAccessible(true);
self::assertNotSame($this->getHttpFoundationFactoryMock(), $reflectionProperty->getValue($clonedClient));
} | QA and update dev vendors requirements | TeknooSoftware_east-foundation | train |
82b5b0f57d7606e383f5089e15b055addfaffab3 | diff --git a/build/component-variables-transfer.js b/build/component-variables-transfer.js
index <HASH>..<HASH> 100644
--- a/build/component-variables-transfer.js
+++ b/build/component-variables-transfer.js
@@ -1,6 +1,8 @@
const path = require('path');
const fs = require('fs-extra');
const glob = require('glob');
+const cedarPackageJson = require('../package.json');
+const variablesPackageJson = require('../../rei-cedar-component-variables/package.json');
const DEST_REPO_NAME = 'rei-cedar-component-variables';
const DEST_PATH = 'dist/scss';
@@ -38,3 +40,14 @@ const singleFile = SUPPORTED_COMPONENTS.map(fname => fs.readFileSync(`${destMixi
fs.outputFileSync(`${destMixinsDir}/index.scss`, indexFile);
fs.outputFileSync(`${destMixinsDir}/cedar-component-variables.scss`, singleFile);
+
+// update cedar and cdr-tokens versions in component-variables
+
+const cedarVersion = cedarPackageJson.version;
+const tokenVersion = cedarPackageJson.devDependencies['@rei/cdr-tokens'];
+
+console.log('updating component-variables peerDependencies', { cedarVersion, tokenVersion, currentPeerDeps: variablesPackageJson.peerDependencies }, )
+variablesPackageJson.peerDependencies['@rei/cdr-tokens'] = tokenVersion;
+variablesPackageJson.peerDependencies['@rei/cedar'] = cedarVersion;
+fs.outputFileSync('../../rei-cedar-component-variables/package.json', JSON.stringify(variablesPackageJson));
+ | chore(variables): update component-variables peerDeps on transfer | rei_rei-cedar | train |
d3c364713eb2f65c1923b1a260664e7e4ae27950 | diff --git a/salt/output/highstate.py b/salt/output/highstate.py
index <HASH>..<HASH> 100644
--- a/salt/output/highstate.py
+++ b/salt/output/highstate.py
@@ -57,10 +57,12 @@ Example output:
------------
Total: 0
'''
-from __future__ import absolute_import
+
# Import python libs
+from __future__ import absolute_import
import pprint
+import textwrap
# Import salt libs
import salt.utils
@@ -249,9 +251,24 @@ def _format_host(host, data):
hstrs.append((u'{0}{1}{2[ENDC]}'
.format(tcolor, changes, colors)))
+ if 'warnings' in ret:
+ rcounts.setdefault('warnings', 0)
+ rcounts['warnings'] += 1
+ wrapper = textwrap.TextWrapper(
+ width=80,
+ initial_indent=u' ' * 14,
+ subsequent_indent=u' ' * 14
+ )
+ hstrs.append(
+ u' {colors[YELLOW]} Warnings: {0}{colors[ENDC]}'.format(
+ wrapper.fill('\n'.join(ret['warnings'])).lstrip(),
+ colors=colors
+ )
+ )
+
# Append result counts to end of output
colorfmt = u'{0}{1}{2[ENDC]}'
- rlabel = {True: u'Succeeded', False: u'Failed', None: u'Not Run'}
+ rlabel = {True: u'Succeeded', False: u'Failed', None: u'Not Run', 'warnings': u'Warnings'}
count_max_len = max([len(str(x)) for x in six.itervalues(rcounts)] or [0])
label_max_len = max([len(x) for x in six.itervalues(rlabel)] or [0])
line_max_len = label_max_len + count_max_len + 2 # +2 for ': '
@@ -314,8 +331,18 @@ def _format_host(host, data):
)
)
+ num_warnings = rcounts.get('warnings', 0)
+ if num_warnings:
+ hstrs.append(
+ colorfmt.format(
+ colors['YELLOW'],
+ _counts(rlabel['warnings'], num_warnings),
+ colors
+ )
+ )
+
totals = u'{0}\nTotal states run: {1:>{2}}'.format('-' * line_max_len,
- sum(six.itervalues(rcounts)),
+ sum(six.itervalues(rcounts)) - rcounts.get('warnings', 0),
line_max_len - 7)
hstrs.append(colorfmt.format(colors['CYAN'], totals, colors)) | Include the warnings in the `highstate` outputter | saltstack_salt | train |
bdc90dbfa22aa710808df07aeea57419fdf083e9 | diff --git a/Gruntfile.js b/Gruntfile.js
index <HASH>..<HASH> 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -95,18 +95,12 @@ module.exports = function(grunt) {
standalone: 'Raven' // umd
},
- transform: [versionify]
+ transform: [versionify],
+ plugin: [ derequire ]
},
core: {
src: 'src/singleton.js',
- dest: 'build/raven.js',
- options: {
- plugin: [ derequire ],
- transform: [
- [ versionify ],
- [ new AddPluginBrowserifyTransformer() ]
- ]
- }
+ dest: 'build/raven.js'
},
plugins: {
files: pluginConcatFiles, | Add builds should use dereq (incl plugin builds) | getsentry_sentry-javascript | train |
cea5a0d395770c8c9222ab3771eb16a36929bf40 | diff --git a/output/cloud/data_test.go b/output/cloud/data_test.go
index <HASH>..<HASH> 100644
--- a/output/cloud/data_test.go
+++ b/output/cloud/data_test.go
@@ -320,7 +320,6 @@ func TestQuickSelectAndBounds(t *testing.T) {
assert.Equal(t, dataForSort, dataForSelect)
t.Run(fmt.Sprintf("bounds-tc%d", tcNum), func(t *testing.T) {
- t.Parallel()
sortMin, sortMax := dataForSort.SortGetNormalBounds(tc.r, tc.l, tc.u, false)
selectMin, selectMax := dataForSelect.SelectGetNormalBounds(tc.r, tc.l, tc.u)
assert.Equal(t, sortMin, selectMin) | Fix a data race in cloud output test | loadimpact_k6 | train |
9791b8a8935adfd5c7e9ad3be6a80cad04390be6 | diff --git a/lib/worker.js b/lib/worker.js
index <HASH>..<HASH> 100644
--- a/lib/worker.js
+++ b/lib/worker.js
@@ -5,12 +5,17 @@ var cluster = require('cluster');
module.exports = function worker(workerFunction, options) {
var logger = require('./logger')(options.verbose, options.logStream);
- process.once('SIGINT', function onInt() {
+ process.once('SIGINT', onInt);
+ process.on('SIGTERM', onQuit);
+
+ workerFunction();
+
+ function onInt() {
logger.log({ event: 'received INT, immediately shutting down' });
process.kill(process.pid, 'SIGINT');
- });
+ }
- process.on('SIGTERM', function onQuit() {
+ function onQuit() {
logger.log({ event: 'received TERM, attempting graceful shutdown' });
setTimeout(function onTermTimeout() {
@@ -19,7 +24,5 @@ module.exports = function worker(workerFunction, options) {
}, options.timeout || 5000).unref();
cluster.worker.disconnect();
- });
-
- workerFunction();
+ }
}; | unnest signal handlers in worker | jclem_teamster | train |
81c39b45adea6f008681ffa7ecacd2ff2235eb20 | diff --git a/test/e2e/deployment.go b/test/e2e/deployment.go
index <HASH>..<HASH> 100644
--- a/test/e2e/deployment.go
+++ b/test/e2e/deployment.go
@@ -34,13 +34,13 @@ var _ = Describe("Deployment", func() {
It("deployment should create new pods", func() {
testNewDeployment(f)
})
- It("deployment should delete old pods and create new ones", func() {
+ It("deployment should delete old pods and create new ones [Flaky]", func() {
testRollingUpdateDeployment(f)
})
- It("deployment should scale up and down in the right order", func() {
+ It("deployment should scale up and down in the right order [Flaky]", func() {
testRollingUpdateDeploymentEvents(f)
})
- It("deployment should support rollover", func() {
+ It("deployment should support rollover [Flaky]", func() {
testRolloverDeployment(f)
})
}) | Label 3 flaky deployment e2e tests with [Flaky] | kubernetes_kubernetes | train |
c40f0ad158497eecd85aee77383b3d053b73417a | diff --git a/public/js/modules/wysiwyg.js b/public/js/modules/wysiwyg.js
index <HASH>..<HASH> 100644
--- a/public/js/modules/wysiwyg.js
+++ b/public/js/modules/wysiwyg.js
@@ -29,6 +29,47 @@ define(function(require) {
{ name: 'source', items : [ 'Source' ] }
]
};
+
+ // For uploaded images, don't specify the width and height as inline styles. Instead,
+ // make the attributes on the img tag.
+ // http://stackoverflow.com/a/6056896/59160
+ CKEDITOR.on('instanceReady', function (ev) {
+ ev.editor.dataProcessor.htmlFilter.addRules({
+ elements: {
+ $: function (element) {
+ // Output dimensions of images as width and height
+ if (element.name == 'img') {
+ var style = element.attributes.style;
+
+ if (style) {
+ // Get the width from the style.
+ var match = /(?:^|\s)width\s*:\s*(\d+)px/i.exec(style),
+ width = match && match[1];
+
+ // Get the height from the style.
+ match = /(?:^|\s)height\s*:\s*(\d+)px/i.exec(style);
+ var height = match && match[1];
+
+ if (width) {
+ element.attributes.style = element.attributes.style.replace(/(?:^|\s)width\s*:\s*(\d+)px;?/i, '');
+ element.attributes.width = width;
+ }
+
+ if (height) {
+ element.attributes.style = element.attributes.style.replace(/(?:^|\s)height\s*:\s*(\d+)px;?/i, '');
+ element.attributes.height = height;
+ }
+ }
+ }
+
+ if (!element.attributes.style)
+ delete element.attributes.style;
+
+ return element;
+ }
+ }
+ });
+ });
// Enable CKFinder
var allow_uploads = false; | Apply width and height on imgs in CKEditor as tag attributes instead of inline styles
Fixes #<I> | BKWLD_decoy | train |
f36ba98e93466411040d579d8913010f16973eb6 | diff --git a/resolve.js b/resolve.js
index <HASH>..<HASH> 100644
--- a/resolve.js
+++ b/resolve.js
@@ -39,8 +39,9 @@ function resolve(name, options, next) {
});
var shrinkwrap = new Shrinkwrap({
- githulk: options.githulk,
- registry: npm
+ githulk: options.githulk, // Custom GitHulk instance so it can be re-used.
+ production: true, // Don't include devDependencies.
+ registry: npm // Do use a custom Registry instance.
});
npm.packages.details(name, function details(err, data) { | [fix] Don't include devDependencies | nodejitsu_packages-pagelet | train |
8cd7e7a36fd4a6ef881f0cd88b528f84de4ea75c | diff --git a/tests/tests/kernel/private/rest/abstract_test.php b/tests/tests/kernel/private/rest/abstract_test.php
index <HASH>..<HASH> 100644
--- a/tests/tests/kernel/private/rest/abstract_test.php
+++ b/tests/tests/kernel/private/rest/abstract_test.php
@@ -16,28 +16,25 @@ abstract class ezpRestTestCase extends ezpTestCase
* @var eZINI
*/
protected $restINI;
-
+
/**
* @var ezpMvcConfiguration
*/
protected $mvcConfig;
-
+
public function __construct( $name = NULL, array $data = array(), $dataName = '' )
{
- ezpExtensionHelper::load( 'rest' );
- ezpExtensionHelper::load( 'oauth' );
-
$this->mvcConfig = new ezpMvcConfiguration();
-
+
// Load rest.ini and forces it to load its data
$this->restINI = eZINI::instance( 'rest.ini' );
$this->restINI->load( true );
-
+
$this->loadDummySettings();
-
+
parent::__construct( $name, $data, $dataName );
}
-
+
/**
* Method to initialize dummy settings, mostly in rest.ini
*/
@@ -45,7 +42,7 @@ abstract class ezpRestTestCase extends ezpTestCase
{
$this->restINI->setVariable( 'ApiProvider', 'ProviderClass', array( 'test' => 'ezpRestTestApiProvider' ));
}
-
+
/**
* Returns a valid test controller from URI
* @param $uri
@@ -59,7 +56,7 @@ abstract class ezpRestTestCase extends ezpTestCase
$r->contentVariables = array();
return $this->getTestControllerFromRequest( $r );
}
-
+
/**
* Returns a valid test controller from a request object
* @param ezpRestRequest $r
@@ -73,7 +70,7 @@ abstract class ezpRestTestCase extends ezpTestCase
$controllerClass = $routingInfos->controllerClass;
$controller = new $controllerClass( $routingInfos->action, $r );
$controller->setRouter( $router );
-
+
return $controller;
}
}
diff --git a/tests/tests/kernel/private/rest/suite.php b/tests/tests/kernel/private/rest/suite.php
index <HASH>..<HASH> 100644
--- a/tests/tests/kernel/private/rest/suite.php
+++ b/tests/tests/kernel/private/rest/suite.php
@@ -29,14 +29,10 @@ class ezpRestTestSuite extends ezpTestSuite
public function setUp()
{
parent::setUp();
-
- // make sure extension is enabled and settings are read
- ezpExtensionHelper::load( 'rest' );
}
public function tearDown()
{
- ezpExtensionHelper::unload( 'rest' );
parent::tearDown();
}
} | Removed traces of old rest extension in REST unit tests | ezsystems_ezpublish-legacy | train |
5ea8c0c5792afe2d5bf2cee312916666b878aa0a | diff --git a/go/teams/ftl.go b/go/teams/ftl.go
index <HASH>..<HASH> 100644
--- a/go/teams/ftl.go
+++ b/go/teams/ftl.go
@@ -109,7 +109,7 @@ func (f *FastTeamChainLoader) Load(m libkb.MetaContext, arg keybase1.FastTeamLoa
}
}
- if m.G().Env.GetFeatureFlags().HasFeature(libkb.FeatureBoxAuditor) {
+ if ShouldRunBoxAudit(m) {
newM, shouldReload := VerifyBoxAudit(m, res.Name.ToTeamID(arg.Public))
if shouldReload {
return f.Load(newM, originalArg)
diff --git a/go/teams/loader.go b/go/teams/loader.go
index <HASH>..<HASH> 100644
--- a/go/teams/loader.go
+++ b/go/teams/loader.go
@@ -311,8 +311,9 @@ func (l *TeamLoader) load1(ctx context.Context, me keybase1.UserVersion, lArg ke
}
}
- if l.G().Env.GetFeatureFlags().HasFeature(libkb.FeatureBoxAuditor) {
- newMctx, shouldReload := VerifyBoxAudit(libkb.NewMetaContext(ctx, l.G()), teamID)
+ mctx := libkb.NewMetaContext(ctx, l.G())
+ if ShouldRunBoxAudit(mctx) {
+ newMctx, shouldReload := VerifyBoxAudit(mctx, teamID)
if shouldReload {
return l.load1(newMctx.Ctx(), me, lArg)
} | turn on box auditor team jail checks (#<I>)
* turn on box auditor team jail checks | keybase_client | train |
bbf6d24b84040ab123187a39a8f4864046884eee | diff --git a/packages/canner-container/src/components/Navbar.js b/packages/canner-container/src/components/Navbar.js
index <HASH>..<HASH> 100644
--- a/packages/canner-container/src/components/Navbar.js
+++ b/packages/canner-container/src/components/Navbar.js
@@ -81,7 +81,7 @@ export default class Navbar extends React.Component<NavbarProps, State> {
}
render() {
- const {dataChanged, logo, renderMenu, showSaveButton, theme = "dark"} = this.props;
+ const {dataChanged, logo, renderMenu, showSaveButton, theme = "dark", style = {}, menuStyle = {}, drawerStyle = {}} = this.props;
const {drawerVisible} = this.state;
const {deploying} = this.state;
const hasChanged = dataChanged && Object.keys(dataChanged).length;
@@ -99,7 +99,7 @@ export default class Navbar extends React.Component<NavbarProps, State> {
theme={theme}
selectedKeys={[]}
onClick={this.headerMenuOnClick}
- style={{paddingBottom: 16}}
+ style={{paddingBottom: 16, ...menuStyle}}
>
<Menu.Item key="__logo">
{Logo}
@@ -111,7 +111,7 @@ export default class Navbar extends React.Component<NavbarProps, State> {
<Menu
mode={mode}
theme={theme}
- style={{ lineHeight: '64px', display: mode === 'horizontal' ? 'inline-block' : 'block' }}
+ style={{ lineHeight: '64px', display: mode === 'horizontal' ? 'inline-block' : 'block', ...menuStyle }}
selectedKeys={[]}
onClick={this.headerMenuOnClick}
>
@@ -143,7 +143,7 @@ export default class Navbar extends React.Component<NavbarProps, State> {
</React.Fragment>
);
return (
- <Header style={{padding: "0 20px", display: 'flex', justifyContent: 'space-between'}}>
+ <Header style={{padding: "0 20px", display: 'flex', justifyContent: 'space-between', ...style}}>
{Logo}
<HeaderMenu>
{renderNav({mode: 'horizontal', theme})}
@@ -152,7 +152,7 @@ export default class Navbar extends React.Component<NavbarProps, State> {
<Button icon="setting" shape="circle" ghost onClick={this.triggerDrawer} style={{border: 0}}/>
<Drawer
height="auto"
- style={{padding: 0, height: 'auto'}}
+ style={{padding: 0, height: 'auto', ...drawerStyle}}
placement={"top"}
closable={false}
visible={drawerVisible}
diff --git a/packages/canner-container/src/components/Sidebar.js b/packages/canner-container/src/components/Sidebar.js
index <HASH>..<HASH> 100644
--- a/packages/canner-container/src/components/Sidebar.js
+++ b/packages/canner-container/src/components/Sidebar.js
@@ -50,7 +50,7 @@ export default class Sidebar extends React.Component<SidebarProps, State> {
}
render() {
- const {menuConfig, routes, theme = 'dark', mode = 'inline'} = this.props;
+ const {menuConfig, routes, theme = 'dark', mode = 'inline', style = {}, menuStyle = {}} = this.props;
const {hasError} = this.state;
// if user's customize Menu is has error, display error messages
@@ -62,12 +62,13 @@ export default class Sidebar extends React.Component<SidebarProps, State> {
return null;
}
return (
- <Layout.Sider breakpoint="sm" collapsedWidth={0} style={{zIndex: 1}} theme={theme}>
+ <Layout.Sider breakpoint="sm" collapsedWidth={0} style={{zIndex: 1, ...style}} theme={theme}>
<Menu
onClick={this.siderMenuOnClick}
selectedKeys={[`/${routes[0]}`]}
mode={mode}
theme={theme}
+ style={menuStyle}
>
{
// $FlowIgnore
diff --git a/packages/canner-container/src/components/types.js b/packages/canner-container/src/components/types.js
index <HASH>..<HASH> 100644
--- a/packages/canner-container/src/components/types.js
+++ b/packages/canner-container/src/components/types.js
@@ -42,14 +42,19 @@ export type MenuConfig = Array<SubmenuConfig | MenuItemConfig>
export type SidebarConfig = {
menuConfig: MenuConfig | boolean,
theme?: 'light' | 'dark',
- mode?: 'vertical' | 'horizontal' | 'inline'
+ mode?: 'vertical' | 'horizontal' | 'inline',
+ style?: Object,
+ menuStyle?: Object
};
export type NavbarConfig = {
logo: string | {src: string, href: string} | React.Node, // img url
renderMenu: any => React.Node,
showSaveButton: boolean,
- theme?: 'light' | 'dark'
+ theme?: 'light' | 'dark',
+ style?: Object,
+ menuStyle?: Object,
+ drawerStyle?: Object
}
export type Router = { | style support in navbar and sidebar | Canner_canner | train |
d9c70dc93c27658c97a34e3abdd813e30999270c | diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/AuthzAuthenticationFilterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/AuthzAuthenticationFilterTests.java
index <HASH>..<HASH> 100644
--- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/AuthzAuthenticationFilterTests.java
+++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/AuthzAuthenticationFilterTests.java
@@ -1,12 +1,17 @@
package org.cloudfoundry.identity.uaa.authentication;
+import org.cloudfoundry.identity.uaa.security.PollutionPreventionExtension;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
@@ -21,44 +26,49 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+@ExtendWith(MockitoExtension.class)
+@ExtendWith(PollutionPreventionExtension.class)
class AuthzAuthenticationFilterTests {
+ @Mock
+ private AuthenticationManager mockAuthenticationManager;
+ private UaaAuthentication mockUaaAuthentication;
+ @InjectMocks
+ private AuthzAuthenticationFilter authzAuthenticationFilter;
+ private MockHttpServletRequest request;
+ private MockHttpServletResponse response;
+
+ @BeforeEach
+ void setUp() {
+ mockUaaAuthentication = mock(UaaAuthentication.class);
+
+ request = new MockHttpServletRequest("POST", "/oauth/authorize");
+ response = new MockHttpServletResponse();
+ }
+
@Test
void authenticatesValidUser() throws Exception {
String msg = "{ \"username\":\"marissa\", \"password\":\"koala\"}";
-
- AuthenticationManager am = mock(AuthenticationManager.class);
- Authentication result = mock(Authentication.class);
- when(am.authenticate(any(AuthzAuthenticationRequest.class))).thenReturn(result);
- AuthzAuthenticationFilter filter = new AuthzAuthenticationFilter(am);
-
- MockHttpServletRequest request = new MockHttpServletRequest("POST", "/oauth/authorize");
request.setParameter("credentials", msg);
- MockHttpServletResponse response = new MockHttpServletResponse();
- filter.doFilter(request, response, new MockFilterChain());
+ authzAuthenticationFilter.doFilter(request, response, new MockFilterChain());
}
@Test
void password_expired_fails_authentication() throws Exception {
- AuthenticationManager am = mock(AuthenticationManager.class);
- UaaAuthentication result = mock(UaaAuthentication.class);
- when(am.authenticate(any(AuthzAuthenticationRequest.class))).thenReturn(result);
+ when(mockUaaAuthentication.isAuthenticated()).thenReturn(true);
+ when(mockUaaAuthentication.isRequiresPasswordChange()).thenReturn(true);
- when(result.isAuthenticated()).thenReturn(true);
- when(result.isRequiresPasswordChange()).thenReturn(true);
-
- AuthzAuthenticationFilter filter = new AuthzAuthenticationFilter(am);
AuthenticationEntryPoint entryPoint = mock(AuthenticationEntryPoint.class);
- filter.setAuthenticationEntryPoint(entryPoint);
- filter.setParameterNames(Arrays.asList("username", "password"));
+ authzAuthenticationFilter.setAuthenticationEntryPoint(entryPoint);
+ authzAuthenticationFilter.setParameterNames(Arrays.asList("username", "password"));
- MockHttpServletRequest request = new MockHttpServletRequest("POST", "/oauth/authorize");
request.setParameter("username", "marissa");
request.setParameter("password", "anything");
- MockHttpServletResponse response = new MockHttpServletResponse();
- filter.doFilter(request, response, new MockFilterChain());
+ when(mockAuthenticationManager.authenticate(any(AuthzAuthenticationRequest.class))).thenReturn(mockUaaAuthentication);
+
+ authzAuthenticationFilter.doFilter(request, response, new MockFilterChain());
ArgumentCaptor<AuthenticationException> captor = ArgumentCaptor.forClass(AuthenticationException.class);
verify(entryPoint, times(1)).commence(same(request), same(response), captor.capture());
@@ -66,6 +76,6 @@ class AuthzAuthenticationFilterTests {
assertEquals(1, captor.getAllValues().size());
assertEquals(PasswordChangeRequiredException.class, captor.getValue().getClass());
assertEquals("password change required", captor.getValue().getMessage());
- assertSame(result, ((PasswordChangeRequiredException) captor.getValue()).getAuthentication());
+ assertSame(mockUaaAuthentication, ((PasswordChangeRequiredException) captor.getValue()).getAuthentication());
}
} | Test refactor - AuthzAuthenticationFilterTests
- Use Mockito mocks/inject mocks
[#<I>] | cloudfoundry_uaa | train |
18c24131be5119e9120f61e93577ed539ed82c02 | diff --git a/sortinghat/_version.py b/sortinghat/_version.py
index <HASH>..<HASH> 100644
--- a/sortinghat/_version.py
+++ b/sortinghat/_version.py
@@ -1,2 +1,2 @@
# Versions compliant with PEP 440 https://www.python.org/dev/peps/pep-0440
-__version__ = "0.6.3"
+__version__ = "0.6.4" | Update version number to <I> | chaoss_grimoirelab-sortinghat | train |
d6667018b27bded33af116f1905b1bd8eea61f56 | diff --git a/tests/TestCase/Model/Filter/CallbackTest.php b/tests/TestCase/Model/Filter/CallbackTest.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase/Model/Filter/CallbackTest.php
+++ b/tests/TestCase/Model/Filter/CallbackTest.php
@@ -6,6 +6,7 @@ use Cake\ORM\Entity;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;
+use Cake\Utility\Hash;
use Search\Manager;
use Search\Model\Filter\Base;
use Search\Model\Filter\Callback;
@@ -51,18 +52,22 @@ class CallbackTest extends TestCase
$articles = TableRegistry::get('Articles');
$manager = new Manager($articles);
- $callback = new Callback('title', $manager, [
+ $filter = new Callback('title', $manager, [
'callback' => function ($query, $args, $manager) {
$query->where(['title' => 'test']);
}
]);
- $callback->args(['title' => ['test']]);
- $callback->query($articles->find());
-
- $query = $callback->query();
- $this->assertEmpty($query->clause('where'));
+ $filter->args(['title' => ['test']]);
+ $filter->query($articles->find());
+ $filter->process();
- $callback->process();
- $this->assertNotEmpty($query->clause('where'));
+ $this->assertRegExp(
+ '/WHERE title = \:c0$/',
+ $filter->query()->sql()
+ );
+ $this->assertEquals(
+ ['test'],
+ Hash::extract($filter->query()->valueBinder()->bindings(), '{s}.value')
+ );
}
} | Make callback process test more specific. | FriendsOfCake_search | train |
49563a8b1676c13207b3c3bd516f1b7a8c343887 | diff --git a/Query/Builder.php b/Query/Builder.php
index <HASH>..<HASH> 100755
--- a/Query/Builder.php
+++ b/Query/Builder.php
@@ -698,7 +698,7 @@ class Builder
);
if (! $value instanceof Expression) {
- $this->addBinding($value, 'where');
+ $this->addBinding(is_array($value) ? head($value) : $value, 'where');
}
return $this;
@@ -1043,7 +1043,7 @@ class Builder
$this->wheres[] = compact('type', 'column', 'values', 'boolean', 'not');
- $this->addBinding($this->cleanBindings($values), 'where');
+ $this->addBinding(array_slice($this->cleanBindings($values), 0, 2), 'where');
return $this;
}
@@ -1111,6 +1111,8 @@ class Builder
$value, $operator, func_num_args() === 2
);
+ $value = is_array($value) ? head($value) : $value;
+
if ($value instanceof DateTimeInterface) {
$value = $value->format('Y-m-d');
}
@@ -1150,6 +1152,8 @@ class Builder
$value, $operator, func_num_args() === 2
);
+ $value = is_array($value) ? head($value) : $value;
+
if ($value instanceof DateTimeInterface) {
$value = $value->format('H:i:s');
}
@@ -1189,6 +1193,8 @@ class Builder
$value, $operator, func_num_args() === 2
);
+ $value = is_array($value) ? head($value) : $value;
+
if ($value instanceof DateTimeInterface) {
$value = $value->format('d');
}
@@ -1232,6 +1238,8 @@ class Builder
$value, $operator, func_num_args() === 2
);
+ $value = is_array($value) ? head($value) : $value;
+
if ($value instanceof DateTimeInterface) {
$value = $value->format('m');
}
@@ -1275,6 +1283,8 @@ class Builder
$value, $operator, func_num_args() === 2
);
+ $value = is_array($value) ? head($value) : $value;
+
if ($value instanceof DateTimeInterface) {
$value = $value->format('Y');
}
@@ -1583,7 +1593,7 @@ class Builder
$this->wheres[] = compact('type', 'column', 'operator', 'value', 'boolean');
if (! $value instanceof Expression) {
- $this->addBinding($value);
+ $this->addBinding((int) $value);
}
return $this;
@@ -1732,7 +1742,7 @@ class Builder
$this->havings[] = compact('type', 'column', 'operator', 'value', 'boolean');
if (! $value instanceof Expression) {
- $this->addBinding($value, 'having');
+ $this->addBinding(is_array($value) ? head($value) : $value, 'having');
}
return $this; | [6.x] Limit expected bindings (#<I>)
* limit expected bindings
* limit more bindings | illuminate_database | train |
01799871739631dfa47ec5d29fb5185a4ba59908 | diff --git a/pt/render.go b/pt/render.go
index <HASH>..<HASH> 100644
--- a/pt/render.go
+++ b/pt/render.go
@@ -28,7 +28,7 @@ func Render(scene *Scene, camera *Camera, w, h, cameraSamples, hitSamples, depth
ncpu := runtime.NumCPU()
runtime.GOMAXPROCS(ncpu)
scene.Compile()
- image := image.NewNRGBA(image.Rect(0, 0, w, h))
+ result := image.NewNRGBA(image.Rect(0, 0, w, h))
ch := make(chan int, h)
fmt.Printf("%d x %d pixels, %d x %d = %d samples, %d bounces, %d cores\n",
w, h, cameraSamples, hitSamples, cameraSamples*hitSamples, depth, ncpu)
@@ -48,11 +48,11 @@ func Render(scene *Scene, camera *Camera, w, h, cameraSamples, hitSamples, depth
c = c.Add(scene.Sample(ray, hitSamples, depth, rnd))
}
}
- c = c.Div(float64(n * n))
+ c = c.Div(float64(n * n)).Pow(1 / 2.2)
r := uint8(math.Min(255, c.R*255))
g := uint8(math.Min(255, c.G*255))
b := uint8(math.Min(255, c.B*255))
- image.SetNRGBA(x, y, color.NRGBA{r, g, b, 255})
+ result.SetNRGBA(x, y, color.NRGBA{r, g, b, 255})
}
ch <- 1
}
@@ -64,5 +64,34 @@ func Render(scene *Scene, camera *Camera, w, h, cameraSamples, hitSamples, depth
showProgress(start, i+1, h)
}
fmt.Println()
- return image
+ return result
+}
+
+func IterativeRender(pathTemplate string, iterations int, scene *Scene, camera *Camera, w, h, cameraSamples, hitSamples, depth int) error {
+ var frames []image.Image
+ result := image.NewNRGBA(image.Rect(0, 0, w, h))
+ for i := 0; i < iterations; i++ {
+ frame := Render(scene, camera, w, h, cameraSamples, hitSamples, depth)
+ frames = append(frames, frame)
+ for y := 0; y < h; y++ {
+ for x := 0; x < w; x++ {
+ c := Color{}
+ for _, frame := range frames {
+ r, g, b, _ := frame.At(x, y).RGBA()
+ color := Color{float64(r) / 65535, float64(g) / 65535, float64(b) / 65535}
+ c = c.Add(color)
+ }
+ c = c.Div(float64(len(frames)))
+ r := uint8(math.Min(255, c.R*255))
+ g := uint8(math.Min(255, c.G*255))
+ b := uint8(math.Min(255, c.B*255))
+ result.SetNRGBA(x, y, color.NRGBA{r, g, b, 255})
+ }
+ }
+ path := fmt.Sprintf(pathTemplate, i)
+ if err := SavePNG(path, result); err != nil {
+ return err
+ }
+ }
+ return nil
}
diff --git a/pt/scene.go b/pt/scene.go
index <HASH>..<HASH> 100644
--- a/pt/scene.go
+++ b/pt/scene.go
@@ -13,8 +13,12 @@ type Scene struct {
}
func (s *Scene) Compile() {
- s.shapeTree = NewTree(s.shapes)
- s.lightTree = NewTree(s.lights)
+ if s.shapeTree == nil {
+ s.shapeTree = NewTree(s.shapes)
+ }
+ if s.lightTree == nil {
+ s.lightTree = NewTree(s.lights)
+ }
}
func (s *Scene) AddShape(shape Shape) { | gamma correction; IterativeRender | fogleman_pt | train |
493486c43f95c259687acee5d28f8da553b0338f | diff --git a/course/lib.php b/course/lib.php
index <HASH>..<HASH> 100644
--- a/course/lib.php
+++ b/course/lib.php
@@ -1252,12 +1252,12 @@ function make_editing_buttons($moduleid, $absolute=false, $visible=true, $movese
static $str = '';
if (empty($str)) {
$str->delete = get_string("delete");
+ $str->move = get_string("move");
$str->moveup = get_string("moveup");
$str->movedown = get_string("movedown");
$str->update = get_string("update");
$str->hide = get_string("hide");
$str->show = get_string("show");
- $str->move = get_string("move");
}
if ($absolute) {
@@ -1283,14 +1283,15 @@ function make_editing_buttons($moduleid, $absolute=false, $visible=true, $movese
if ($moveselect) {
$move = "<a title=\"$str->move\" href=\"$path/mod.php?copy=$moduleid\"><img".
" src=\"$pixpath/t/move.gif\" height=\"11\" width=\"11\" border=\"0\"></a> ";
+ } else {
+ $move = "<a title=\"$str->moveup\" href=\"$path/mod.php?id=$moduleid&move=-1\"><img".
+ " src=\"$pixpath/t/up.gif\" height=11 width=11 border=0></a> ".
+ "<a title=\"$str->movedown\" href=\"$path/mod.php?id=$moduleid&move=1\"><img".
+ " src=\"$pixpath/t/down.gif\" height=11 width=11 border=0></a> ";
}
return "<a title=\"$str->delete\" href=\"$path/mod.php?delete=$moduleid\"><img".
- " src=\"$pixpath/t/delete.gif\" height=11 width=11 border=0></a> ".
- "<a title=\"$str->moveup\" href=\"$path/mod.php?id=$moduleid&move=-1\"><img".
- " src=\"$pixpath/t/up.gif\" height=11 width=11 border=0></a> ".
- "<a title=\"$str->movedown\" href=\"$path/mod.php?id=$moduleid&move=1\"><img".
- " src=\"$pixpath/t/down.gif\" height=11 width=11 border=0></a> $move".
+ " src=\"$pixpath/t/delete.gif\" height=11 width=11 border=0></a> $move".
"<a title=\"$str->update\" href=\"$path/mod.php?update=$moduleid\"><img".
" src=\"$pixpath/t/edit.gif\" height=11 width=11 border=0></a> $hideshow";
} | Removed redundant up/down arrows ... let's see how everyone feels about it | moodle_moodle | train |
866f465cc20bdab854ee8e0157215b291dc6020e | diff --git a/support-actionbarsherlock/src/org/droidparts/activity/TabbedFragmentActivity.java b/support-actionbarsherlock/src/org/droidparts/activity/TabbedFragmentActivity.java
index <HASH>..<HASH> 100644
--- a/support-actionbarsherlock/src/org/droidparts/activity/TabbedFragmentActivity.java
+++ b/support-actionbarsherlock/src/org/droidparts/activity/TabbedFragmentActivity.java
@@ -59,25 +59,29 @@ public abstract class TabbedFragmentActivity extends FragmentActivity {
getSupportActionBar().setNavigationMode(NAVIGATION_MODE_TABS);
}
- public int getSelectedTabPos() {
- return getSupportActionBar().getSelectedTab().getPosition();
+ protected final void addTab(ActionBar.Tab tab, int[] fragmentIds) {
+ tab.setTabListener(tabListener);
+ getSupportActionBar().addTab(tab);
+ tabSpecs.add(fragmentIds);
}
- protected void onTabSelected(int pos) {
+ public final void setCurrentTab(int position) {
+ getSupportActionBar().setSelectedNavigationItem(position);
+ }
+ public final int getCurrentTab() {
+ return getSupportActionBar().getSelectedTab().getPosition();
}
- protected final void addTab(ActionBar.Tab tab, int[] fragmentIds) {
- tab.setTabListener(tabListener);
- getSupportActionBar().addTab(tab);
- tabSpecs.add(fragmentIds);
+ protected void onTabChanged(int position) {
+
}
@Override
public void setFragmentVisible(int fragmentId, boolean visible) {
if (visible) {
hiddenFragments.remove(fragmentId);
- int[] currTab = tabSpecs.get(getSelectedTabPos());
+ int[] currTab = tabSpecs.get(getCurrentTab());
for (int fId : currTab) {
if (fId == fragmentId) {
super.setFragmentVisible(fragmentId, true);
@@ -114,6 +118,6 @@ public abstract class TabbedFragmentActivity extends FragmentActivity {
}
}
}
- onTabSelected(pos);
+ onTabChanged(pos);
}
} | Changed TabbedFragmentActivity API. | droidparts_droidparts | train |
88aa1bc2cfef4517fca9e467c86f70ae356be883 | diff --git a/test/language/snippets.rb b/test/language/snippets.rb
index <HASH>..<HASH> 100755
--- a/test/language/snippets.rb
+++ b/test/language/snippets.rb
@@ -358,7 +358,7 @@ class TestSnippets < Test::Unit::TestCase
}.each { |count, str|
path = "/tmp/singlequote%s" % count
assert_file(path)
- assert_equal(str, @catalog.resource(:file, path).should(:content))
+ assert_equal(str, @catalog.resource(:file, path).parameter(:content).actual_content)
}
end
@@ -403,7 +403,7 @@ class TestSnippets < Test::Unit::TestCase
path = "/tmp/multisubtest"
assert_file(path)
file = @catalog.resource(:file, path)
- assert_equal("sub2", file.should(:content), "sub2 did not override content")
+ assert_equal("{md5}5fbef65269a99bddc2106251dd89b1dc", file.should(:content), "sub2 did not override content")
assert_mode_equal(0755, path)
end
diff --git a/test/network/client/resource.rb b/test/network/client/resource.rb
index <HASH>..<HASH> 100755
--- a/test/network/client/resource.rb
+++ b/test/network/client/resource.rb
@@ -35,29 +35,20 @@ class TestResourceClient < Test::Unit::TestCase
client = mkclient()
# Test describing
- tresource = nil
- assert_nothing_raised {
- tresource = client.describe("file", file)
- }
+ tresource = client.describe("file", file)
assert(tresource, "Did not get response")
assert_instance_of(Puppet::TransObject, tresource)
- resource = nil
- assert_nothing_raised {
- resource = tresource.to_ral
- }
+ resource = tresource.to_ral
assert_events([], resource)
File.unlink(file)
assert_events([:file_created], resource)
File.unlink(file)
# Now test applying
- result = nil
- assert_nothing_raised {
- result = client.apply(tresource)
- }
+ result = client.apply(tresource)
assert(FileTest.exists?(file), "File was not created on apply")
end
end | Fixing tests broken in previous commits | puppetlabs_puppet | train |
a5e85c812d64d387dbdb778a3a704ca9763e6b0c | diff --git a/tests/phpunit/unit/Twig/Handler/WidgetHandlerTest.php b/tests/phpunit/unit/Twig/Handler/WidgetHandlerTest.php
index <HASH>..<HASH> 100644
--- a/tests/phpunit/unit/Twig/Handler/WidgetHandlerTest.php
+++ b/tests/phpunit/unit/Twig/Handler/WidgetHandlerTest.php
@@ -57,7 +57,7 @@ class WidgetHandlerTest extends BoltUnitTest
->setContent('<blink>Drop Bear Warning!</blink>')
;
- $this->setExpectedException('InvalidArgumentException', 'countwigets() requires a location, none given');
+ $this->setExpectedException('InvalidArgumentException', 'countwidgets() requires a location, none given');
$app['asset.queue.widget']->add($widget);
$handler->countWidgets();
} | Sneaky ninja typo-fix in tests. | bolt_bolt | train |
ba8d8997b0822f7ea4d8a7e0d25412593cd9da53 | diff --git a/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableSession.java b/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableSession.java
index <HASH>..<HASH> 100644
--- a/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableSession.java
+++ b/bigtable-client-core/src/main/java/com/google/cloud/bigtable/grpc/BigtableSession.java
@@ -274,8 +274,8 @@ public class BigtableSession implements AutoCloseable {
"Credentials must be an instance of OAuth2Credentials, but got %s.", credentials.getClass()
.getName()));
RefreshingOAuth2CredentialsInterceptor oauth2Interceptor =
- new RefreshingOAuth2CredentialsInterceptor(batchPool, (OAuth2Credentials) credentials,
- this.options.getRetryOptions());
+ new RefreshingOAuth2CredentialsInterceptor(this.batchPool,
+ (OAuth2Credentials) credentials, this.options.getRetryOptions());
oauth2Interceptor.asyncRefresh();
headerInterceptorBuilder.add(oauth2Interceptor);
} | Fixing the cluster api test. | googleapis_cloud-bigtable-client | train |
258b9a85d65c7cd80dcb604f3923976e8d36759b | diff --git a/clicktests/test.generic.js b/clicktests/test.generic.js
index <HASH>..<HASH> 100644
--- a/clicktests/test.generic.js
+++ b/clicktests/test.generic.js
@@ -13,7 +13,7 @@ var environment;
var testRepoPath;
suite.test('Init', function(done) {
- environment = new Environment(page);
+ environment = new Environment(page, { serverStartupOptions: ['--no-disableDiscardWarning'] });
environment.init(function(err) {
if (err) return done(err);
testRepoPath = environment.path + '/testrepo'; | Force disableDiscardWarning to be false for generic | FredrikNoren_ungit | train |
eb8343625f0afbd967f4c3684dede714abf6c57a | diff --git a/command/generate-root.go b/command/generate-root.go
index <HASH>..<HASH> 100644
--- a/command/generate-root.go
+++ b/command/generate-root.go
@@ -267,7 +267,7 @@ func (c *GenerateRootCommand) dumpStatus(status *api.GenerateRootStatusResponse)
statString := fmt.Sprintf(
"Nonce: %s\n"+
"Started: %v\n"+
- "Rekey Progress: %d\n"+
+ "Generate Root Progress: %d\n"+
"Required Keys: %d\n"+
"Complete: %t",
status.Nonce,
@@ -301,7 +301,7 @@ Usage: vault generate-root [options] [key]
One (and only one) of the following must be provided at attempt
initialization time:
-
+
1) A 16-byte, base64-encoded One Time Password (OTP) provided in the '-otp'
flag; the token is XOR'd with this value before it is returned once the final
unseal key has been provided. The '-decode' operation can be used with this
@@ -313,10 +313,10 @@ Usage: vault generate-root [options] [key]
2) A file containing a PGP key (binary or base64-encoded) or a Keybase.io
username in the format of "keybase:<username>" in the '-pgp-key' flag. The
final token value will be encrypted with this public key and base64-encoded.
-
+
General Options:
` + meta.GeneralOptionsUsage() + `
-Rekey Options:
+Generate Root Options:
-init Initialize the root generation attempt. This can only
be done if no generation is already initiated. | Fix generate-root help and progress output. | hashicorp_vault | train |
018248691eb5490d57d2e1731ea619b12a71a079 | diff --git a/harvestingkit/elsevier_package.py b/harvestingkit/elsevier_package.py
index <HASH>..<HASH> 100644
--- a/harvestingkit/elsevier_package.py
+++ b/harvestingkit/elsevier_package.py
@@ -295,7 +295,7 @@ class ElsevierPackage(object):
def _add_references(self, xml_doc, rec, refextract_callback=None):
for label, authors, doi, issue, page, title, volume, year,\
textref, ext_link, isjournal, comment, journal, publisher,\
- editors, book_title in self.get_references(xml_doc):
+ editors, book_title, links in self.get_references(xml_doc):
subfields = []
if textref and not authors:
textref = textref.replace('\"', '\'')
@@ -361,6 +361,9 @@ class ElsevierPackage(object):
subfields.append(('s', journal))
if textref:
subfields.append(('m', textref))
+ if links:
+ for link in links:
+ subfields.append(('u', link))
if subfields:
record_add_field(rec, '999', ind1='C', ind2='5',
subfields=subfields)
@@ -764,7 +767,7 @@ class ElsevierPackage(object):
year = re.sub(r'\D', '', year)
return (label, authors, doi, issue, page, title, volume,
year, textref, ext_link, isjournal, comment, journal,
- publisher, editors, book_title)
+ publisher, editors, book_title, links)
def get_references(self, xml_doc):
for ref in xml_doc.getElementsByTagName("ce:bib-reference"): | elsevier-package: propagate links in references to output
* Propagates URLs which were already extracted now also to
the final output. | inspirehep_harvesting-kit | train |
70a50ec4b45e76f73bad802d5aa60fa13cf94516 | diff --git a/core/src/main/java/net/time4j/format/ChronoFormatter.java b/core/src/main/java/net/time4j/format/ChronoFormatter.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/net/time4j/format/ChronoFormatter.java
+++ b/core/src/main/java/net/time4j/format/ChronoFormatter.java
@@ -210,14 +210,17 @@ public final class ChronoFormatter<T extends ChronoEntity<T>>
) {
super();
- if (element == null) {
- throw new NullPointerException("Missing element.");
- }
-
this.chronology = formatter.chronology;
this.defaultAttributes = formatter.defaultAttributes;
this.fracproc = formatter.fracproc;
+ if (element == null) {
+ throw new NullPointerException("Missing element.");
+ } else if (!this.chronology.isSupported(element)) {
+ throw new IllegalArgumentException(
+ "Not supported: " + element.name());
+ }
+
Map<ChronoElement<?>, Object> map =
new NonAmbivalentMap(formatter.defaults);
@@ -824,6 +827,8 @@ public final class ChronoFormatter<T extends ChronoEntity<T>>
* @param value replacement value or {@code null}
* if the default value shall be deregistered
* @return changed copy with new replacement value
+ * @throws IllegalArgumentException if given element is not supported
+ * by the underlying chronology
* @see Attributes#USE_DEFAULT_WHEN_ERROR
*/
/*[deutsch]
@@ -845,6 +850,8 @@ public final class ChronoFormatter<T extends ChronoEntity<T>>
* @param value replacement value or {@code null}
* if the default value shall be deregistered
* @return changed copy with new replacement value
+ * @throws IllegalArgumentException if given element is not supported
+ * by the underlying chronology
* @see Attributes#USE_DEFAULT_WHEN_ERROR
*/
public <V> ChronoFormatter<T> withDefault(
@@ -2360,6 +2367,8 @@ public final class ChronoFormatter<T extends ChronoEntity<T>>
*
* @param element chronological element
* @return this instance for method chaining
+ * @throws IllegalArgumentException if given element is not
+ * supported by the underlying chronology
* @throws IllegalStateException if a numerical element is added
* multiple times in a row
* @since 1.2
@@ -2377,6 +2386,8 @@ public final class ChronoFormatter<T extends ChronoEntity<T>>
*
* @param element chronological element
* @return this instance for method chaining
+ * @throws IllegalArgumentException if given element is not
+ * supported by the underlying chronology
* @throws IllegalStateException if a numerical element is added
* multiple times in a row
* @since 1.2
@@ -2426,7 +2437,8 @@ public final class ChronoFormatter<T extends ChronoEntity<T>>
* @param indicators ordinal indicators to be used as suffixes
* @return this instance for method chaining
* @throws IllegalArgumentException if there is no indicator at least
- * for the plural category OTHER
+ * for the plural category OTHER or if given element is not
+ * supported by the underlying chronology
* @throws IllegalStateException if a numerical element is added
* multiple times in a row
* @since 1.2
@@ -2472,7 +2484,8 @@ public final class ChronoFormatter<T extends ChronoEntity<T>>
* @param indicators ordinal indicators to be used as suffixes
* @return this instance for method chaining
* @throws IllegalArgumentException if there is no indicator at least
- * for the plural category OTHER
+ * for the plural category OTHER or if given element is not
+ * supported by the underlying chronology
* @throws IllegalStateException if a numerical element is added
* multiple times in a row
* @since 1.2
@@ -2952,6 +2965,8 @@ public final class ChronoFormatter<T extends ChronoEntity<T>>
* @param element year element (name must start with the
* prefix "YEAR")
* @return this instance for method chaining
+ * @throws IllegalArgumentException if given element is not
+ * supported by chronology
* @see Attributes#PIVOT_YEAR
*/
/*[deutsch]
@@ -2975,6 +2990,8 @@ public final class ChronoFormatter<T extends ChronoEntity<T>>
* @param element year element (name must start with the
* prefix "YEAR")
* @return this instance for method chaining
+ * @throws IllegalArgumentException if given element is not
+ * supported by chronology
* @see Attributes#PIVOT_YEAR
*/
public Builder<T> addTwoDigitYear(ChronoElement<Integer> element) { | added exta element check in ChronoFormatter
see issue #<I> | MenoData_Time4J | train |
3fd36631550a1e6c57b7ba59a796e9009b69711a | diff --git a/tests/JsonConfigTest.php b/tests/JsonConfigTest.php
index <HASH>..<HASH> 100644
--- a/tests/JsonConfigTest.php
+++ b/tests/JsonConfigTest.php
@@ -178,19 +178,4 @@ class JsonConfigTest extends TestCase
'userdefined3' => 'Berlioz3'],
$config->getVariables());
}
-
- /**
- * @throws \Berlioz\Config\Exception\ConfigException
- */
- public function testVarDump()
- {
- $config = new JsonConfig(sprintf('%s%s', __DIR__, '/files/config.json'), true);
-
- ob_start();
- var_dump($config);
- $varDump = ob_get_contents();
- ob_end_clean();
-
- $this->assertRegExp('/^(class Berlioz\\\\Config\\\\JsonConfig|object\(Berlioz\\\\Config\\\\JsonConfig\))\#\d+ \(0\) \{\s+\}$/mi', trim($varDump), 'Empty var_dump()');
- }
} | Remove test with xdebug conflict | BerliozFramework_Config | train |
70405f5eab516c9f7b626d803b043415809499a6 | diff --git a/schemes.go b/schemes.go
index <HASH>..<HASH> 100644
--- a/schemes.go
+++ b/schemes.go
@@ -24,6 +24,7 @@ var Schemes = []string{
`barion`,
`beshare`,
`bitcoin`,
+ `bitcoincash`,
`blob`,
`bolo`,
`browserext`,
@@ -47,6 +48,7 @@ var Schemes = []string{
`dav`,
`diaspora`,
`dict`,
+ `did`,
`dis`,
`dlna-playcontainer`,
`dlna-playsingle`,
@@ -55,6 +57,7 @@ var Schemes = []string{
`dtn`,
`dvb`,
`ed2k`,
+ `elsi`,
`example`,
`facetime`,
`fax`,
@@ -75,6 +78,7 @@ var Schemes = []string{
`gtalk`,
`h323`,
`ham`,
+ `hcap`,
`hcp`,
`http`,
`https`,
@@ -143,6 +147,8 @@ var Schemes = []string{
`ms-powerpoint`,
`ms-publisher`,
`ms-restoretabcompanion`,
+ `ms-screenclip`,
+ `ms-screensketch`,
`ms-search-repair`,
`ms-secondary-screen-controller`,
`ms-secondary-screen-setup`,
@@ -194,6 +200,7 @@ var Schemes = []string{
`onenote`,
`onenote-cmd`,
`opaquelocktoken`,
+ `openpgp4fpr`,
`pack`,
`palm`,
`paparazzi`,
@@ -226,6 +233,7 @@ var Schemes = []string{
`sgn`,
`shttp`,
`sieve`,
+ `simpleledger`,
`sip`,
`sips`,
`skype`,
diff --git a/tlds.go b/tlds.go
index <HASH>..<HASH> 100644
--- a/tlds.go
+++ b/tlds.go
@@ -174,7 +174,6 @@ var TLDs = []string{
`boo`,
`book`,
`booking`,
- `boots`,
`bosch`,
`bostik`,
`boston`,
@@ -249,6 +248,7 @@ var TLDs = []string{
`ch`,
`chanel`,
`channel`,
+ `charity`,
`chase`,
`chat`,
`cheap`,
@@ -623,6 +623,7 @@ var TLDs = []string{
`immo`,
`immobilien`,
`in`,
+ `inc`,
`industries`,
`infiniti`,
`info`,
@@ -650,7 +651,6 @@ var TLDs = []string{
`itau`,
`itv`,
`iveco`,
- `iwc`,
`jaguar`,
`java`,
`jcb`,
@@ -808,7 +808,6 @@ var TLDs = []string{
`memorial`,
`men`,
`menu`,
- `meo`,
`merckmsd`,
`metlife`,
`mg`,
@@ -854,7 +853,6 @@ var TLDs = []string{
`msd`,
`mt`,
`mtn`,
- `mtpc`,
`mtr`,
`mu`,
`museum`,
@@ -1085,7 +1083,6 @@ var TLDs = []string{
`sandvikcoromant`,
`sanofi`,
`sap`,
- `sapo`,
`sarl`,
`sas`,
`save`,
@@ -1380,7 +1377,6 @@ var TLDs = []string{
`xfinity`,
`xihuan`,
`xin`,
- `xperia`,
`xxx`,
`xyz`,
`yachts`,
@@ -1440,6 +1436,7 @@ var TLDs = []string{
`امارات`,
`ايران`,
`ایران`,
+ `بارت`,
`بازار`,
`بيتك`,
`بھارت`,
@@ -1525,6 +1522,7 @@ var TLDs = []string{
`我爱你`,
`手机`,
`手表`,
+ `招聘`,
`政务`,
`政府`,
`新加坡`, | update tlds and schemes | mvdan_xurls | train |
0f539c2544d6898154c364b512b989960086b548 | diff --git a/fireplace/enums.py b/fireplace/enums.py
index <HASH>..<HASH> 100644
--- a/fireplace/enums.py
+++ b/fireplace/enums.py
@@ -132,6 +132,9 @@ class GameTag(IntEnum):
HOW_TO_EARN = 364
HOW_TO_EARN_GOLDEN = 365
+ HEROPOWER_DAMAGE = 396
+ RECEIVES_DOUBLE_SPELLDAMAGE_BONUS = 404
+
# Renamed
DEATH_RATTLE = 217
OVERKILL = 380
@@ -264,7 +267,12 @@ class PlayReq(IntEnum):
REQ_TARGET_IF_AVAILABLE_AND_DRAGON_IN_HAND = 51
REQ_LEGENDARY_TARGET = 52
REQ_FRIENDLY_MINION_DIED_THIS_TURN = 53
- REQ_DRAG_TO_PLAY = 54
+ REQ_FRIENDLY_MINION_DIED_THIS_GAME = 54
+ REQ_ENEMY_WEAPON_EQUIPPED = 55
+ REQ_TARGET_IF_AVAILABLE_AND_MINIMUM_FRIENDLY_MINIONS = 56
+ REQ_TARGET_WITH_BATTLECRY = 57
+ REQ_TARGET_WITH_DEATHRATTLE = 58
+ REQ_DRAG_TO_PLAY = 59
class Race(IntEnum): | Add PlayRequirements and GameTags from <I> | jleclanche_fireplace | train |
6f8f84a05782b490bae034fc2b7d767c3a38bcd9 | diff --git a/src/System/StateChecker.php b/src/System/StateChecker.php
index <HASH>..<HASH> 100755
--- a/src/System/StateChecker.php
+++ b/src/System/StateChecker.php
@@ -55,7 +55,7 @@ class StateChecker {
}
/**
- * Check for entity existence if cache
+ * Check for entity existence in the EntityCache
*
* @return boolean
*/
@@ -86,6 +86,11 @@ class StateChecker {
return $this->exists;
}
+ /**
+ * Check if the primary key entity attribute is set
+ *
+ * @return boolean
+ */
protected function hasPrimaryKeyDefined()
{
$entityAttributes = $this->entity->getEntityAttributes();
@@ -97,7 +102,7 @@ class StateChecker {
* Chech relations for existence / dirtyness
*
* @param array $relations
- * @return
+ * @return array non-existing relationships
*/
public function checkExistingRelations($relations)
{
@@ -137,14 +142,25 @@ class StateChecker {
return $nonExisting;
}
- protected function checkEntityForExistence($entity)
+ /**
+ * Check if an entity exist in the Entity Cache
+ *
+ * @param Mappable $entity
+ * @return boolean
+ */
+ protected function checkEntityForExistence(Mappable $entity)
{
$checker = $this->newStateChecker($entity);
return $checker->exists();
}
-
+ /**
+ * Get the attributes that have been modified since
+ * the entity have been fetched from the database
+ *
+ * @return array
+ */
public function getDirtyAttributes()
{
$attributes = $this->flattenEmbeddables($this->entity->getEntityAttributes());
@@ -173,7 +189,13 @@ class StateChecker {
return $dirty;
}
- protected function flattenEmbeddables($attributes)
+ /**
+ * Merge any Value Object's attribute with entity's attribute
+ *
+ * @param array
+ * @return array
+ */
+ protected function flattenEmbeddables(array $attributes)
{
$embeddables = $this->entityMap->getEmbeddables();
@@ -192,7 +214,7 @@ class StateChecker {
/**
* Determine if the new and old values for a given key are numerically equivalent.
*
- * @return bool
+ * @return boolean
*/
protected function originalIsNumericallyEquivalent($current, $original)
{
@@ -200,6 +222,12 @@ class StateChecker {
}
+ /**
+ * Determine if an entity attribute is a relationship.
+ *
+ * @param strin $key
+ * @return boolean
+ */
protected function isRelation($key)
{
return in_array($key, $this->entityMap->getRelationships()); | Docblocks in StateChecker class | analogueorm_analogue | train |
545e40b874b3d22759e3c75f60cbd22458ab947f | diff --git a/src/main/java/biweekly/ICalendar.java b/src/main/java/biweekly/ICalendar.java
index <HASH>..<HASH> 100644
--- a/src/main/java/biweekly/ICalendar.java
+++ b/src/main/java/biweekly/ICalendar.java
@@ -6,8 +6,10 @@ import java.io.OutputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
+import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import javax.xml.transform.TransformerException;
@@ -1118,6 +1120,13 @@ public class ICalendar extends ICalComponent {
}
@Override
+ protected Map<String, Object> toStringValues() {
+ Map<String, Object> fields = new HashMap<String, Object>();
+ fields.put("version", version);
+ return fields;
+ }
+
+ @Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
diff --git a/src/main/java/biweekly/component/ICalComponent.java b/src/main/java/biweekly/component/ICalComponent.java
index <HASH>..<HASH> 100644
--- a/src/main/java/biweekly/component/ICalComponent.java
+++ b/src/main/java/biweekly/component/ICalComponent.java
@@ -539,9 +539,33 @@ public abstract class ICalComponent {
return sb.toString();
}
+ /**
+ * <p>
+ * Gets string representations of any additional fields the component has
+ * (other than sub-components and properties) for the {@link #toString}
+ * method.
+ * </p>
+ * <p>
+ * Meant to be overridden by child classes. The default implementation
+ * returns an empty map.
+ * </p>
+ * @return the values of the component's fields (key = field name, value =
+ * field value)
+ */
+ protected Map<String, Object> toStringValues() {
+ return Collections.emptyMap();
+ }
+
private void toString(int depth, StringBuilder sb) {
StringUtils.repeat(' ', depth * 2, sb);
- sb.append(getClass().getName()).append(StringUtils.NEWLINE);
+ sb.append(getClass().getName());
+
+ Map<String, Object> fields = toStringValues();
+ if (!fields.isEmpty()) {
+ sb.append(' ').append(fields.toString());
+ }
+
+ sb.append(StringUtils.NEWLINE);
depth++;
for (ICalProperty property : properties.values()) { | ICalendar.toString() was not including the value of the "version" field. | mangstadt_biweekly | train |
aa0d4db05dd1c62fe9351c969dc9e4ec4c863311 | diff --git a/features/issue147.feature b/features/issue147.feature
index <HASH>..<HASH> 100644
--- a/features/issue147.feature
+++ b/features/issue147.feature
@@ -11,4 +11,4 @@ Feature: Issue 147
And I create a request object
And load the resource
And execute the resource
- Then response should be "1"
+ Then response should be "1bar"
diff --git a/issues/Issue147.php b/issues/Issue147.php
index <HASH>..<HASH> 100644
--- a/issues/Issue147.php
+++ b/issues/Issue147.php
@@ -21,7 +21,7 @@ class Issue147Foundation extends Resource {
* @otherthing foo
*/
public function tother() {
- return (string)$this->thing;
+ return (string)$this->thing.$this->otherthing;
}
}
diff --git a/src/Tonic/Application.php b/src/Tonic/Application.php
index <HASH>..<HASH> 100644
--- a/src/Tonic/Application.php
+++ b/src/Tonic/Application.php
@@ -325,11 +325,11 @@ class Application
$classReflector = new \ReflectionClass($className);
$parentReflector = $classReflector->getParentClass();
if ($parentReflector) {
- $metadata = $this->mergeMetadata($metadata, $this->readMethodAnnotations($parentReflector->name, $targetClass));
+ $metadata = $this->mergeMetadata($this->readMethodAnnotations($parentReflector->name, $targetClass), $metadata);
}
$interfaces = $classReflector->getInterfaceNames();
foreach ($interfaces as $interface) {
- $metadata = $this->mergeMetadata($metadata, $this->readMethodAnnotations($interface, $targetClass));
+ $metadata = $this->mergeMetadata($this->readMethodAnnotations($interface, $targetClass), $metadata);
}
return $metadata; | Changed order of annotation merge so as to not overwrite child annotations (issue #<I>) | peej_tonic | train |
1a1d284aa13ac84b3a954c557bce3af1f627baac | diff --git a/classes/PodsMeta.php b/classes/PodsMeta.php
index <HASH>..<HASH> 100644
--- a/classes/PodsMeta.php
+++ b/classes/PodsMeta.php
@@ -448,6 +448,11 @@ class PodsMeta {
if ( !empty( $pod ) )
$pod->save( $data );
+ elseif ( !empty( $id ) ) {
+ foreach ( $data as $field => $value ) {
+ update_post_meta( $id, $field, $value );
+ }
+ }
pods_no_conflict_off( 'post' );
@@ -538,6 +543,11 @@ class PodsMeta {
if ( !empty( $pod ) )
$pod->save( $data );
+ elseif ( !empty( $id ) ) {
+ foreach ( $data as $field => $value ) {
+ update_post_meta( $id, $field, $value );
+ }
+ }
return $post;
}
@@ -730,6 +740,11 @@ class PodsMeta {
if ( !empty( $pod ) )
$pod->save( $data );
+ elseif ( !empty( $id ) ) {
+ foreach ( $data as $field => $value ) {
+ update_user_meta( $id, $field, $value );
+ }
+ }
}
/**
@@ -912,6 +927,11 @@ class PodsMeta {
if ( !empty( $pod ) )
$pod->save( $data );
+ elseif ( !empty( $id ) ) {
+ foreach ( $data as $field => $value ) {
+ update_comment_meta( $id, $field, $value );
+ }
+ }
}
/* | Save meta data even if current object isn't a Pod | pods-framework_pods | train |
1569e296aba00fa97ddbbb19877faf84c71bf348 | diff --git a/swagger_parser/swagger_parser.py b/swagger_parser/swagger_parser.py
index <HASH>..<HASH> 100755
--- a/swagger_parser/swagger_parser.py
+++ b/swagger_parser/swagger_parser.py
@@ -361,8 +361,11 @@ class SwaggerParser(object):
Returns:
An example array.
"""
+ # if items is a list, then each item has its own spec
+ if isinstance(prop_spec['items'], list):
+ return [self.get_example_from_prop_spec(item_prop_spec) for item_prop_spec in prop_spec['items']]
# Standard types in array
- if 'type' in prop_spec['items'].keys():
+ elif 'type' in prop_spec['items'].keys():
if 'format' in prop_spec['items'].keys() and prop_spec['items']['format'] == 'date-time':
return self._get_example_from_basic_type('datetime')
else: | fix issue where array items is a list of types | Trax-air_swagger-parser | train |
621793da857fe00622115f3de0f9ab7b0fd00461 | diff --git a/src/main/java/net/dv8tion/jda/api/entities/GuildChannel.java b/src/main/java/net/dv8tion/jda/api/entities/GuildChannel.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/dv8tion/jda/api/entities/GuildChannel.java
+++ b/src/main/java/net/dv8tion/jda/api/entities/GuildChannel.java
@@ -37,7 +37,7 @@ import java.util.List;
* @see JDA#getGuildChannelById(long)
* @see JDA#getGuildChannelById(ChannelType, long)
*/
-public interface GuildChannel extends ISnowflake, Comparable<GuildChannel>
+public interface GuildChannel extends ISnowflake, IMentionable, Comparable<GuildChannel>
{
/**
* The {@link net.dv8tion.jda.api.entities.ChannelType ChannelType} for this GuildChannel
diff --git a/src/main/java/net/dv8tion/jda/api/entities/StoreChannel.java b/src/main/java/net/dv8tion/jda/api/entities/StoreChannel.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/dv8tion/jda/api/entities/StoreChannel.java
+++ b/src/main/java/net/dv8tion/jda/api/entities/StoreChannel.java
@@ -33,4 +33,4 @@ import net.dv8tion.jda.api.JDA;
* @see JDA#getStoreChannelsByName(String, boolean)
* @see JDA#getStoreChannelById(long)
*/
-public interface StoreChannel extends GuildChannel, IMentionable {}
+public interface StoreChannel extends GuildChannel {}
diff --git a/src/main/java/net/dv8tion/jda/api/entities/TextChannel.java b/src/main/java/net/dv8tion/jda/api/entities/TextChannel.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/dv8tion/jda/api/entities/TextChannel.java
+++ b/src/main/java/net/dv8tion/jda/api/entities/TextChannel.java
@@ -57,7 +57,7 @@ import java.util.List;
* @see JDA#getTextChannelsByName(String, boolean)
* @see JDA#getTextChannelById(long)
*/
-public interface TextChannel extends GuildChannel, MessageChannel, IMentionable
+public interface TextChannel extends GuildChannel, MessageChannel
{
/**
* The maximum duration of slowmode in seconds
diff --git a/src/main/java/net/dv8tion/jda/internal/entities/AbstractChannelImpl.java b/src/main/java/net/dv8tion/jda/internal/entities/AbstractChannelImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/dv8tion/jda/internal/entities/AbstractChannelImpl.java
+++ b/src/main/java/net/dv8tion/jda/internal/entities/AbstractChannelImpl.java
@@ -80,6 +80,13 @@ public abstract class AbstractChannelImpl<T extends GuildChannel, M extends Abst
@Nonnull
@Override
+ public String getAsMention()
+ {
+ return "<#" + id + '>';
+ }
+
+ @Nonnull
+ @Override
public abstract ChannelAction<T> createCopy(@Nonnull Guild guild);
@Nonnull
diff --git a/src/main/java/net/dv8tion/jda/internal/entities/StoreChannelImpl.java b/src/main/java/net/dv8tion/jda/internal/entities/StoreChannelImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/dv8tion/jda/internal/entities/StoreChannelImpl.java
+++ b/src/main/java/net/dv8tion/jda/internal/entities/StoreChannelImpl.java
@@ -40,13 +40,6 @@ public class StoreChannelImpl extends AbstractChannelImpl<StoreChannel, StoreCha
@Nonnull
@Override
- public String getAsMention()
- {
- return "<#" + id + '>';
- }
-
- @Nonnull
- @Override
public ChannelType getType()
{
return ChannelType.STORE;
diff --git a/src/main/java/net/dv8tion/jda/internal/entities/TextChannelImpl.java b/src/main/java/net/dv8tion/jda/internal/entities/TextChannelImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/dv8tion/jda/internal/entities/TextChannelImpl.java
+++ b/src/main/java/net/dv8tion/jda/internal/entities/TextChannelImpl.java
@@ -70,13 +70,6 @@ public class TextChannelImpl extends AbstractChannelImpl<TextChannel, TextChanne
@Nonnull
@Override
- public String getAsMention()
- {
- return "<#" + id + '>';
- }
-
- @Nonnull
- @Override
public RestAction<List<Webhook>> retrieveWebhooks()
{
checkPermission(Permission.MANAGE_WEBHOOKS); | Allow all guild channels to be mentioned (#<I>) | DV8FromTheWorld_JDA | train |
8778cd7f98dab8ba96409c3caae9dc107025b821 | diff --git a/packages/mip/src/components/mip-fixed.js b/packages/mip/src/components/mip-fixed.js
index <HASH>..<HASH> 100644
--- a/packages/mip/src/components/mip-fixed.js
+++ b/packages/mip/src/components/mip-fixed.js
@@ -14,11 +14,9 @@ class MipFixed extends CustomElement {
return
}
- // only in iOS + iframe
- if (platform.isIos() && viewer.isIframed) {
- // move element to fixedlayer
- viewer.fixedElement.setFixedElement([this.element], true)
- }
+ // only in iOS + iframe need moving element to fixedlayer
+ let shouldMoveToFixedLayer = platform.isIos() && viewer.isIframed
+ viewer.fixedElement.setFixedElement([this.element], shouldMoveToFixedLayer)
}
} | fix: move <mip-fixed> to <body> in iOS | mipengine_mip2 | train |
365738ff446009a72fcbbea76dcb0093a89e9b40 | diff --git a/tracking/middleware.py b/tracking/middleware.py
index <HASH>..<HASH> 100644
--- a/tracking/middleware.py
+++ b/tracking/middleware.py
@@ -1,16 +1,23 @@
import re
import logging
-from datetime import datetime
from django.utils import timezone
from tracking.models import Visitor, Pageview
from tracking.utils import get_ip_address
-from tracking.settings import (TRACK_AJAX_REQUESTS,
- TRACK_ANONYMOUS_USERS, TRACK_PAGEVIEWS, TRACK_IGNORE_URLS, TRACK_IGNORE_STATUS_CODES, TRACK_REFERER, TRACK_QUERY_STRING)
-
-TRACK_IGNORE_URLS = [re.compile(x) for x in TRACK_IGNORE_URLS]
+from tracking.settings import (
+ TRACK_AJAX_REQUESTS,
+ TRACK_ANONYMOUS_USERS,
+ TRACK_IGNORE_STATUS_CODES,
+ TRACK_IGNORE_URLS,
+ TRACK_PAGEVIEWS,
+ TRACK_QUERY_STRING,
+ TRACK_REFERER,
+)
+
+track_ignore_urls = [re.compile(x) for x in TRACK_IGNORE_URLS]
log = logging.getLogger(__file__)
+
class VisitorTrackingMiddleware(object):
def process_response(self, request, response):
# Session framework not installed, nothing to see here..
@@ -48,10 +55,12 @@ class VisitorTrackingMiddleware(object):
except Visitor.DoesNotExist:
visitor_user_agent = request.META.get('HTTP_USER_AGENT', None)
if visitor_user_agent is not None:
- visitor_user_agent = visitor_user_agent.decode('latin-1', errors='ignore')
+ visitor_user_agent = visitor_user_agent.decode(
+ 'latin-1', errors='ignore')
# Log the ip address. Start time is managed via the
# field `default` value
- visitor = Visitor(pk=session_key, ip_address=get_ip_address(request),
+ visitor = Visitor(
+ pk=session_key, ip_address=get_ip_address(request),
user_agent=visitor_user_agent)
# Update the user field if the visitor user is not set. This
@@ -78,7 +87,7 @@ class VisitorTrackingMiddleware(object):
if TRACK_PAGEVIEWS:
# Match against `path_info` to not include the SCRIPT_NAME..
path = request.path_info.lstrip('/')
- for url in TRACK_IGNORE_URLS:
+ for url in track_ignore_urls:
if url.match(path):
break
else:
@@ -91,8 +100,10 @@ class VisitorTrackingMiddleware(object):
if TRACK_QUERY_STRING:
query_string = request.META.get('QUERY_STRING')
- pageview = Pageview(visitor=visitor, url=request.path,
- view_time=now, method=request.method, referer=referer, query_string=query_string)
+ pageview = Pageview(
+ visitor=visitor, url=request.path, view_time=now,
+ method=request.method, referer=referer,
+ query_string=query_string)
pageview.save()
return response | PEP8 on middleware and a few tweaks for testing | bruth_django-tracking2 | train |
e1459f7a513d0e771a95048fc73437a12436cb5c | diff --git a/lib/mwlib/tests/MW/Setup/Manager/DefaultTest.php b/lib/mwlib/tests/MW/Setup/Manager/DefaultTest.php
index <HASH>..<HASH> 100644
--- a/lib/mwlib/tests/MW/Setup/Manager/DefaultTest.php
+++ b/lib/mwlib/tests/MW/Setup/Manager/DefaultTest.php
@@ -6,7 +6,7 @@
* @copyright Copyright (c) Metaways Infosystems GmbH, 2011
* @license LGPLv3, http://www.gnu.org/licenses/lgpl.html
*/
-class MW_Setup_Manager_DefaultTest extends PHPUnit_Extensions_OutputTestCase
+class MW_Setup_Manager_DefaultTest extends MW_Unittest_Testcase
{
protected $_config;
protected $_dbm;
@@ -41,10 +41,10 @@ class MW_Setup_Manager_DefaultTest extends PHPUnit_Extensions_OutputTestCase
public function testRun()
{
- $this->expectOutputString('
+ $expected = '
Executing OneTask OK
Executing TwoTask OK
-');
+';
$conn = $this->_dbm->acquire();
@@ -53,16 +53,23 @@ Executing TwoTask OK
$this->_dbm->release( $conn );
+ ob_start();
+
$object->run( 'mysql' );
+
+ $result = ob_get_contents();
+ ob_end_clean();
+
+ $this->assertEquals( $expected, $result );
}
public function testRun2()
{
- $this->expectOutputString('
+ $expected = '
Executing OneTask OK
Executing TwoTask OK
Executing ThreeTask OK
-');
+';
$conn = $this->_dbm->acquire();
@@ -75,6 +82,13 @@ Executing ThreeTask OK
$this->_dbm->release( $conn );
+ ob_start();
+
$object->run( 'mysql' );
+
+ $result = ob_get_contents();
+ ob_end_clean();
+
+ $this->assertEquals( $expected, $result );
}
} | Replaces phpunit output test case by manual check because it's not available on travis-ci | Arcavias_arcavias-core | train |
6be757fab01dc67ee48c2603f3ee0f4cc1cb0512 | diff --git a/src/main/java/hudson/plugins/emailext/ExtendedEmailPublisherDescriptor.java b/src/main/java/hudson/plugins/emailext/ExtendedEmailPublisherDescriptor.java
index <HASH>..<HASH> 100644
--- a/src/main/java/hudson/plugins/emailext/ExtendedEmailPublisherDescriptor.java
+++ b/src/main/java/hudson/plugins/emailext/ExtendedEmailPublisherDescriptor.java
@@ -2,6 +2,8 @@ package hudson.plugins.emailext;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
+import hudson.init.InitMilestone;
+import hudson.init.Initializer;
import hudson.matrix.MatrixProject;
import hudson.model.AbstractProject;
import hudson.plugins.emailext.plugins.EmailTriggerDescriptor;
@@ -25,6 +27,7 @@ import org.jenkinsci.plugins.scriptsecurity.scripts.languages.GroovyLanguage;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
+
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
@@ -185,22 +188,27 @@ public final class ExtendedEmailPublisherDescriptor extends BuildStepDescriptor<
public ExtendedEmailPublisherDescriptor() {
super(ExtendedEmailPublisher.class);
load();
+
if (defaultBody == null && defaultSubject == null && emergencyReroute == null) {
defaultBody = ExtendedEmailPublisher.DEFAULT_BODY_TEXT;
defaultSubject = ExtendedEmailPublisher.DEFAULT_SUBJECT_TEXT;
emergencyReroute = ExtendedEmailPublisher.DEFAULT_EMERGENCY_REROUTE_TEXT;
}
+ }
+ @Initializer(after = InitMilestone.EXTENSIONS_AUGMENTED, before = InitMilestone.JOB_LOADED)
+ public static void autoConfigure() {
+ ExtendedEmailPublisherDescriptor descriptor = ExtendedEmailPublisher.descriptor();
if (Jenkins.get().isUseSecurity()
- && (!StringUtils.isBlank(this.defaultPostsendScript)) || !StringUtils.isBlank(this.defaultPresendScript)) {
- setDefaultPostsendScript(this.defaultPostsendScript);
- setDefaultPresendScript(this.defaultPresendScript);
+ && (!StringUtils.isBlank(descriptor.getDefaultPostsendScript())) || !StringUtils.isBlank(descriptor.getDefaultPresendScript())) {
+ descriptor.setDefaultPostsendScript(descriptor.getDefaultPostsendScript());
+ descriptor.setDefaultPresendScript(descriptor.getDefaultPresendScript());
try {
- setDefaultClasspath(this.defaultClasspath);
+ descriptor.setDefaultClasspath(descriptor.getDefaultClasspath());
} catch (FormException e) {
//Some of the old configured classpaths probably used some environment variable, let's clean those out
List<GroovyScriptPath> newList = new ArrayList<>();
- for (GroovyScriptPath path : defaultClasspath) {
+ for (GroovyScriptPath path : descriptor.getDefaultClasspath()) {
URL u = path.asURL();
if (u != null) {
try {
@@ -212,7 +220,7 @@ public final class ExtendedEmailPublisherDescriptor extends BuildStepDescriptor<
}
}
try {
- setDefaultClasspath(newList);
+ descriptor.setDefaultClasspath(newList);
} catch (FormException e1) {
assert false : e1;
} | Fix JENKINS-<I>
Move to an initializer after extensions have been augmented | jenkinsci_email-ext-plugin | train |
d5bea2e19d9f8885d8d5257a28bf8603fa313a8f | diff --git a/modules/citrus-core/src/main/java/com/consol/citrus/validation/xml/DomXmlMessageValidator.java b/modules/citrus-core/src/main/java/com/consol/citrus/validation/xml/DomXmlMessageValidator.java
index <HASH>..<HASH> 100644
--- a/modules/citrus-core/src/main/java/com/consol/citrus/validation/xml/DomXmlMessageValidator.java
+++ b/modules/citrus-core/src/main/java/com/consol/citrus/validation/xml/DomXmlMessageValidator.java
@@ -288,11 +288,14 @@ public class DomXmlMessageValidator extends AbstractMessageValidator<XmlMessageV
XMLUtils.prettyPrint(receivedMessage.getPayload().toString()));
// Report all parsing errors
- String validationErrors = "Found " + results.length + " XML validation errors: ";
- for(SAXParseException e : results)
- validationErrors = validationErrors + "\n" + e.toString();
- log.debug(validationErrors);
-
+ log.debug("Found " + results.length + " schema validation errors");
+ StringBuilder errors = new StringBuilder();
+ for(SAXParseException e : results) {
+ errors.append(e.toString());
+ errors.append("\n");
+ }
+ log.debug(errors.toString());
+
throw new ValidationException("Schema validation failed:", results[0]);
}
} catch (IOException e) { | Use StringBuilder and minor cosmetic changes | citrusframework_citrus | train |
725979f0276aa88082696e0b4801d0227cd885bc | diff --git a/GaReport.php b/GaReport.php
index <HASH>..<HASH> 100644
--- a/GaReport.php
+++ b/GaReport.php
@@ -82,11 +82,11 @@ class GaReport extends Module
}
/**
- * Implements hook "template.dashboard"
+ * Implements hook "dashboard.panels"
* @param array $panels
* @param \gplcart\core\controllers\backend\Controller $controller
*/
- public function hookTemplateDashboard(array &$panels, $controller)
+ public function hookDashboardPanels(array &$panels, $controller)
{
/* @var $model \gplcart\modules\ga_report\models\Report */
$model = $this->getInstance('gplcart\\modules\\ga_report\\models\\Report'); | Rename hook (API changes) | gplcart_ga_report | train |
310c0ebcf910beb0944b214d46ea4c8ae8ec54dc | diff --git a/mindmaps-graql-shell/src/main/java/io/mindmaps/graql/GraqlShell.java b/mindmaps-graql-shell/src/main/java/io/mindmaps/graql/GraqlShell.java
index <HASH>..<HASH> 100644
--- a/mindmaps-graql-shell/src/main/java/io/mindmaps/graql/GraqlShell.java
+++ b/mindmaps-graql-shell/src/main/java/io/mindmaps/graql/GraqlShell.java
@@ -192,7 +192,7 @@ public class GraqlShell {
try {
sendBatchRequest(uriString, cmd.getOptionValue("b"));
} catch (IOException e) {
- System.err.println(e.toString());
+ throw new RuntimeException(e);
}
return;
}
@@ -245,9 +245,17 @@ public class GraqlShell {
os.write(out);
}
- try (InputStream is = http.getInputStream()) {
- String response = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
- System.out.println(response);
+ int statusCode = http.getResponseCode();
+ if (statusCode >= 200 && statusCode < 400) {
+ try (InputStream is = http.getInputStream()) {
+ String response = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
+ System.out.println(response);
+ }
+ } else {
+ try (InputStream is = http.getErrorStream()) {
+ String response = CharStreams.toString(new InputStreamReader(is, Charsets.UTF_8));
+ System.out.println(response);
+ }
}
} | Handle batch load when engine returns an error response code (#<I>) | graknlabs_grakn | train |
24f48dbaf284ab9acf440c961ccbba234b7247df | diff --git a/lib/foreman_tasks/version.rb b/lib/foreman_tasks/version.rb
index <HASH>..<HASH> 100644
--- a/lib/foreman_tasks/version.rb
+++ b/lib/foreman_tasks/version.rb
@@ -1,3 +1,3 @@
module ForemanTasks
- VERSION = "0.7.0"
+ VERSION = "0.7.1"
end | Update foreman-tasks to <I> | theforeman_foreman-tasks | train |
8535310a022291d209ebd5bf62a8735f71261b4b | diff --git a/lib/athena.js b/lib/athena.js
index <HASH>..<HASH> 100644
--- a/lib/athena.js
+++ b/lib/athena.js
@@ -58,7 +58,7 @@ async.map = function (/* hlog, */ arr, method, resultsHandler)
{
if (finished && Object.keys(waiting).length === 0 && typeof args.resultsHandler === 'function')
{
- args.resultsHandler(context.__hlog, results);
+ args.resultsHandler.call(context, context.__hlog, results);
args.resultsHandler = null; // prevent from being called multiple times
}
}
@@ -105,7 +105,7 @@ async.parallel = function (/* hlog, */ methods, resultsHandler)
{
if (finished && Object.keys(waiting).length === 0 && typeof args.resultsHandler === 'function')
{
- args.resultsHandler(context.__hlog, results);
+ args.resultsHandler.call(context, context.__hlog, results);
args.resultsHandler = null; // prevent from being called multiple times
}
} | Send this context for all result handlers. | bretcope_odyssey | train |
067328a467c54464e3c86006ac177141ba89522c | diff --git a/openquake/commonlib/readinput.py b/openquake/commonlib/readinput.py
index <HASH>..<HASH> 100644
--- a/openquake/commonlib/readinput.py
+++ b/openquake/commonlib/readinput.py
@@ -429,10 +429,10 @@ def get_site_collection(oqparam):
grid_spacing).discretize(grid_spacing)
grid_sites = site.SiteCollection.from_points(
grid.lons, grid.lats, req_site_params=req_site_params)
+ logging.info('Associating %d site model sites to %d grid sites',
+ len(sm), len(grid_sites))
sitecol, params, _ = geo.utils.assoc(
sm, grid_sites, oqparam.region_grid_spacing * 1.414, 'warn')
- logging.info('Associating %d site model sites to %d grid sites',
- len(sm), len(sitecol))
sitecol.make_complete()
else:
sitecol = site.SiteCollection.from_points( | More logging [skip CI] | gem_oq-engine | train |
2b0540172c1dce021cac7f324dc4fce8ceb50011 | diff --git a/src/Illuminate/Foundation/helpers.php b/src/Illuminate/Foundation/helpers.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Foundation/helpers.php
+++ b/src/Illuminate/Foundation/helpers.php
@@ -10,6 +10,7 @@ use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Contracts\View\Factory as ViewFactory;
use Illuminate\Contracts\Cookie\Factory as CookieFactory;
use Illuminate\Database\Eloquent\Factory as EloquentFactory;
+use Illuminate\Contracts\Validation\Factory as ValidationFactory;
if (! function_exists('abort')) {
/**
@@ -662,6 +663,28 @@ if (! function_exists('url')) {
}
}
+if (! function_exists('validator')) {
+ /**
+ * Create a new Validator instance.
+ *
+ * @param array $data
+ * @param array $rules
+ * @param array $messages
+ * @param array $customAttributes
+ * @return \Illuminate\Contracts\Validation\Validator
+ */
+ function validator(array $data, array $rules, array $messages = [], array $customAttributes = [])
+ {
+ $factory = app(ValidationFactory::class);
+
+ if (func_num_args() === 0) {
+ return $factory;
+ }
+
+ return $factory->make($data, $rules, $messages, $customAttributes);
+ }
+}
+
if (! function_exists('view')) {
/**
* Get the evaluated view contents for the given view. | Add a validator() helper as a shorthand for Validate::make()
and use ::class notation. Order new helper alphabetically :) | laravel_framework | train |
1462d2897281d09abb11cb8778c789c909648f34 | diff --git a/note.py b/note.py
index <HASH>..<HASH> 100755
--- a/note.py
+++ b/note.py
@@ -897,7 +897,7 @@ class Runner(object):
def __init__(self):
self.dbName = 'note'
- self.db = mongoDB(self.dbName, self.config['database']['uri'])
+ self.db = mongoDB(self.dbName)
note = Note(self.db)
todo = ToDo(self.db) | remove database uri reference before config is loaded | dwwkelly_note | train |
5e038e41060e28bab484cd24babf7484ff66f29f | diff --git a/api/jobs.go b/api/jobs.go
index <HASH>..<HASH> 100644
--- a/api/jobs.go
+++ b/api/jobs.go
@@ -648,6 +648,16 @@ func (j *Job) Canonicalize() {
}
}
+// LookupTaskGroup finds a task group by name
+func (j *Job) LookupTaskGroup(name string) *TaskGroup {
+ for _, tg := range j.TaskGroups {
+ if *tg.Name == name {
+ return tg
+ }
+ }
+ return nil
+}
+
// JobSummary summarizes the state of the allocations of a job
type JobSummary struct {
JobID string
diff --git a/api/tasks.go b/api/tasks.go
index <HASH>..<HASH> 100644
--- a/api/tasks.go
+++ b/api/tasks.go
@@ -132,6 +132,17 @@ func (r *ReschedulePolicy) Copy() *ReschedulePolicy {
return nrp
}
+func (p *ReschedulePolicy) String() string {
+ if p == nil {
+ return ""
+ }
+ if *p.Unlimited {
+ return fmt.Sprintf("unlimited with %v delay, max_delay = %v", *p.DelayFunction, *p.MaxDelay)
+ } else {
+ return fmt.Sprintf("%v in %v with %v delay, max_delay = %v", *p.Attempts, *p.Interval, *p.DelayFunction, *p.MaxDelay)
+ }
+}
+
// CheckRestart describes if and when a task should be restarted based on
// failing health checks.
type CheckRestart struct {
diff --git a/command/job_status.go b/command/job_status.go
index <HASH>..<HASH> 100644
--- a/command/job_status.go
+++ b/command/job_status.go
@@ -371,7 +371,7 @@ func (c *JobStatusCommand) outputJobInfo(client *api.Client, job *api.Job) error
c.outputFailedPlacements(latestFailedPlacement)
}
- c.outputReschedulingEvals(client, jobAllocs)
+ c.outputReschedulingEvals(client, job, jobAllocs, c.length)
if latestDeployment != nil {
c.Ui.Output(c.Colorize().Color("\n[bold]Latest Deployment[reset]"))
@@ -540,7 +540,7 @@ func (c *JobStatusCommand) outputJobSummary(client *api.Client, job *api.Job) er
// outputReschedulingEvals displays eval IDs and time for any
// delayed evaluations by task group
-func (c *JobStatusCommand) outputReschedulingEvals(client *api.Client, allocListStubs []*api.AllocationListStub) error {
+func (c *JobStatusCommand) outputReschedulingEvals(client *api.Client, job *api.Job, allocListStubs []*api.AllocationListStub, uuidLength int) error {
// Get the most recent alloc ID by task group
mostRecentAllocs := make(map[string]*api.AllocationListStub)
@@ -579,11 +579,12 @@ func (c *JobStatusCommand) outputReschedulingEvals(client *api.Client, allocList
if err != nil || evaluation.WaitUntil.IsZero() || time.Now().After(evaluation.WaitUntil) {
continue
}
+ rp := job.LookupTaskGroup(taskGroup).ReschedulePolicy
evalTime := prettyTimeDiff(evaluation.WaitUntil, time.Now())
- evalDetails = append(evalDetails, fmt.Sprintf("%s|%s|%s", taskGroup, evalID, evalTime))
+ evalDetails = append(evalDetails, fmt.Sprintf("%s|%s|%s|%s", taskGroup, rp.String(), limit(evalID, uuidLength), evalTime))
}
if len(evalDetails) > 0 { // Only show this section if there is pending evals
- delayedEvalInfos = append(delayedEvalInfos, "Task Group|Eval ID|Eval Time")
+ delayedEvalInfos = append(delayedEvalInfos, "Task Group|Reschedule Policy|Eval ID|Eval Time")
delayedEvalInfos = append(delayedEvalInfos, evalDetails...)
c.Ui.Output(c.Colorize().Color("\n[bold]Upcoming Evaluations[reset]"))
c.Ui.Output(formatList(delayedEvalInfos))
diff --git a/command/job_status_test.go b/command/job_status_test.go
index <HASH>..<HASH> 100644
--- a/command/job_status_test.go
+++ b/command/job_status_test.go
@@ -331,7 +331,7 @@ func TestJobStatusCommand_RescheduleEvals(t *testing.T) {
}
out := ui.OutputWriter.String()
require.Contains(out, "Upcoming Evaluations")
- require.Contains(out, e.ID)
+ require.Contains(out, e.ID[:8])
}
func waitForSuccess(ui cli.Ui, client *api.Client, length int, t *testing.T, evalId string) int { | Show reschedule policy in addition to when the eval will get rescheduled | hashicorp_nomad | train |
8b03cd8d2e6d00ec2521480efa7a2c0361294fb7 | diff --git a/tests/integration/cloud/providers/digital_ocean.py b/tests/integration/cloud/providers/digital_ocean.py
index <HASH>..<HASH> 100644
--- a/tests/integration/cloud/providers/digital_ocean.py
+++ b/tests/integration/cloud/providers/digital_ocean.py
@@ -12,7 +12,7 @@ from salt.config import cloud_providers_config
# Import Salt Testing Libs
from salttesting import skipIf
-from salttesting.helpers import ensure_in_syspath
+from salttesting.helpers import ensure_in_syspath, expensiveTest
ensure_in_syspath('../../../')
@@ -72,6 +72,7 @@ class DigitalOceanTest(integration.ShellCase):
.format(provider)
)
+ @expensiveTest
def test_instance(self):
'''
Test creating an instance on Digital Ocean
diff --git a/tests/integration/cloud/providers/linode.py b/tests/integration/cloud/providers/linode.py
index <HASH>..<HASH> 100644
--- a/tests/integration/cloud/providers/linode.py
+++ b/tests/integration/cloud/providers/linode.py
@@ -12,7 +12,7 @@ from salt.config import cloud_providers_config
# Import Salt Testing Libs
from salttesting import skipIf
-from salttesting.helpers import ensure_in_syspath
+from salttesting.helpers import ensure_in_syspath, expensiveTest
ensure_in_syspath('../../../')
@@ -63,6 +63,7 @@ class LinodeTest(integration.ShellCase):
)
)
+ @expensiveTest
def test_instance(self):
'''
Test creating an instance on Linode
diff --git a/tests/runtests.py b/tests/runtests.py
index <HASH>..<HASH> 100755
--- a/tests/runtests.py
+++ b/tests/runtests.py
@@ -148,6 +148,10 @@ class SaltTestsuiteParser(SaltCoverageTestingParser):
)
def validate_options(self):
+ if self.options.cloud_provider_tests:
+ # Turn on expensive tests execution
+ os.environ['EXPENSIVE_TESTS'] = 'True'
+
if self.options.coverage and any((
self.options.module, self.options.client, self.options.shell,
self.options.unit, self.options.state, self.options.runner, | Decorate tests as expensive
Less trouble for the new runtests script | saltstack_salt | train |
eab74abe64b9d0a8a93a522fa849e3a0e0910ffb | diff --git a/src/Kernel.php b/src/Kernel.php
index <HASH>..<HASH> 100644
--- a/src/Kernel.php
+++ b/src/Kernel.php
@@ -40,7 +40,7 @@ class Kernel
private $config = [];
/**
- * @param array $modules The name of the modules to load.
+ * @param array $modules The name of the modules to load.
* @param string $environment Environment of the application (prod, dev, test, ...).
*/
public function __construct(array $modules = [], $environment = 'prod')
@@ -136,7 +136,7 @@ class Kernel
}
// Load the environment-specific config if it exists
- $envConfig = '/' . $module . '/config/env/' . $this->environment . '.php';
+ $envConfig = '/'.$module.'/config/env/'.$this->environment.'.php';
if ($resources->contains($envConfig)) {
$resource = $resources->get($envConfig);
if ($resource instanceof FilesystemResource) {
diff --git a/tests/KernelTest.php b/tests/KernelTest.php
index <HASH>..<HASH> 100644
--- a/tests/KernelTest.php
+++ b/tests/KernelTest.php
@@ -90,7 +90,7 @@ class KernelTest extends \PHPUnit_Framework_TestCase
*/
public function uses_provided_config()
{
- $this->kernel = new Kernel;
+ $this->kernel = new Kernel();
$this->kernel->addConfig([
'foo' => 'bar',
'bar' => 'bar', | Applied fixes from StyleCI (#4) | PHP-DI_Kernel | train |
f56777b489c668549045c8a7a52570070e51dc83 | diff --git a/neo4j-gremlin/src/test/java/com/tinkerpop/gremlin/neo4j/structure/Neo4jGraphTest.java b/neo4j-gremlin/src/test/java/com/tinkerpop/gremlin/neo4j/structure/Neo4jGraphTest.java
index <HASH>..<HASH> 100644
--- a/neo4j-gremlin/src/test/java/com/tinkerpop/gremlin/neo4j/structure/Neo4jGraphTest.java
+++ b/neo4j-gremlin/src/test/java/com/tinkerpop/gremlin/neo4j/structure/Neo4jGraphTest.java
@@ -5,7 +5,9 @@ import com.tinkerpop.gremlin.neo4j.BaseNeo4jGraphTest;
import com.tinkerpop.gremlin.process.graph.GraphTraversal;
import com.tinkerpop.gremlin.structure.Element;
import com.tinkerpop.gremlin.structure.Vertex;
+import com.tinkerpop.gremlin.util.StreamFactory;
import org.junit.Test;
+import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.graphdb.ConstraintViolationException;
import org.neo4j.graphdb.DynamicLabel;
import org.neo4j.graphdb.Node;
@@ -348,4 +350,21 @@ public class Neo4jGraphTest extends BaseNeo4jGraphTest {
assertEquals(0, this.g.V().has(Element.LABEL, "Product").has("name", "marko").has(Element.LABEL, "Person").count().next(), 0);
assertEquals(0, this.g.V().has(Element.LABEL, "Corporate").has("name", "marko").has(Element.LABEL, "Person").count().next(), 0);
}
+
+ @Test
+ public void shouldGenerateNodesAndRelationshipsCorrectlyForMetaProperties() {
+ g.tx().readWrite();
+ ExecutionEngine cypher = g.getCypher();
+ Vertex a = g.addVertex("name","marko","name","okram");
+ Vertex b = g.addVertex("name","stephen","location","virginia");
+ assertEquals(2, g.V().count().next().intValue());
+ assertEquals(0, g.E().count().next().intValue());
+
+ //cypher.execute("MATCH ()-[r]-() RETURN COUNT(DISTINCT r)").forEach(System.out::println);
+
+ assertEquals(4l, cypher.execute("MATCH n RETURN COUNT(n)").iterator().next().get("COUNT(n)"));
+ assertEquals(2l, cypher.execute("MATCH (n)-[r]->(m) RETURN COUNT(r)").iterator().next().get("COUNT(r)"));
+
+
+ }
} | the start of Neo4jGraph structure testing with Cypher. | apache_tinkerpop | train |
e1ca976192f9a9e02e55edbde6d291ad995bf8d8 | diff --git a/ModelBundle/DataFixtures/MongoDB/LoadDemoSiteData.php b/ModelBundle/DataFixtures/MongoDB/LoadDemoSiteData.php
index <HASH>..<HASH> 100644
--- a/ModelBundle/DataFixtures/MongoDB/LoadDemoSiteData.php
+++ b/ModelBundle/DataFixtures/MongoDB/LoadDemoSiteData.php
@@ -41,6 +41,7 @@ class LoadDemoSiteData extends AbstractLoadSiteData implements OrchestraProducti
);
$site2->setSitemapPriority(0.5);
$site2->setDeleted(false);
+ $site2->setContentTypes(array('news', 'customer', 'car'));
$site2->setTemplateSet('default');
$site2->setTemplateNodeRoot('home');
$site2->addBlock('slideshow');
diff --git a/ModelBundle/Document/Site.php b/ModelBundle/Document/Site.php
index <HASH>..<HASH> 100644
--- a/ModelBundle/Document/Site.php
+++ b/ModelBundle/Document/Site.php
@@ -46,13 +46,20 @@ class Site implements SiteInterface
protected $siteId;
/**
- * @var ArrayCollection
+ * @var array
*
- * @ODM\Field(type="hash")
+ * @ODM\Field(type="collection")
*/
protected $blocks = array();
/**
+ * @var array
+ *
+ * @ODM\Field(type="collection")
+ */
+ protected $contentTypes = array();
+
+ /**
* @var string $metaAuthor
*
* @ODM\Field(type="string")
@@ -158,6 +165,22 @@ class Site implements SiteInterface
}
/**
+ * @param array $contentTypes
+ */
+ public function setContentTypes($contentTypes)
+ {
+ $this->contentTypes = $contentTypes;
+ }
+
+ /**
+ * @return array
+ */
+ public function getContentTypes()
+ {
+ return $this->contentTypes;
+ }
+
+ /**
* @return string
*/
public function getId()
diff --git a/ModelBundle/Repository/ContentRepository.php b/ModelBundle/Repository/ContentRepository.php
index <HASH>..<HASH> 100644
--- a/ModelBundle/Repository/ContentRepository.php
+++ b/ModelBundle/Repository/ContentRepository.php
@@ -295,11 +295,19 @@ class ContentRepository extends AbstractAggregateRepository implements FieldAuto
* @param boolean|null $published
* @param int|null $limit
* @param array|null $sort
+ * @param array $contentTypes
*
* @return array
*/
- public function findByHistoryAndSiteId($id, $siteId, array $eventTypes = null, $published = null, $limit = null, array $sort = null)
- {
+ public function findByHistoryAndSiteId(
+ $id,
+ $siteId,
+ array $eventTypes = null,
+ $published = null,
+ $limit = null,
+ array $sort = null,
+ array $contentTypes = array()
+ ) {
$qa = $this->createAggregationQuery();
$filter = array(
'histories.user.$id' => new \MongoId($id),
@@ -312,6 +320,9 @@ class ContentRepository extends AbstractAggregateRepository implements FieldAuto
if (null !== $published) {
$filter['status.published'] = $published;
}
+ if (!empty($contentTypes)) {
+ $filter['contentType'] = array('$in' => $contentTypes);
+ }
$qa->match($filter);
diff --git a/ModelBundle/Repository/ContentTypeRepository.php b/ModelBundle/Repository/ContentTypeRepository.php
index <HASH>..<HASH> 100644
--- a/ModelBundle/Repository/ContentTypeRepository.php
+++ b/ModelBundle/Repository/ContentTypeRepository.php
@@ -14,11 +14,11 @@ use Solution\MongoAggregation\Pipeline\Stage;
class ContentTypeRepository extends AbstractAggregateRepository implements ContentTypeRepositoryInterface
{
/**
- * @param $language
+ * @param array $contentTypes
*
* @return array
*/
- public function findAllNotDeletedInLastVersion($language = null)
+ public function findAllNotDeletedInLastVersion(array $contentTypes = array())
{
$qa = $this->createAggregationQuery();
$qa->match(
@@ -26,16 +26,13 @@ class ContentTypeRepository extends AbstractAggregateRepository implements Conte
'deleted' => false
)
);
- $elementName = 'contentType';
- $this->generateLastVersionFilter($qa, $elementName);
-
- if ($language) {
- $qa->sort(
- array(
- $elementName . '.names.' . $language. '.value' => 1
- )
+ if (!empty($contentTypes)) {
+ $qa->match(
+ array('contentTypeId' => array('$in' => $contentTypes))
);
}
+ $elementName = 'contentType';
+ $this->generateLastVersionFilter($qa, $elementName);
return $this->hydrateAggregateQuery($qa, $elementName, 'getContentTypeId');
} | add content type choice on site form (#<I>)
* add content type choice on site form
* fix functional tests
* PhpDoc | open-orchestra_open-orchestra-model-bundle | train |
2b986bc5265ab921f149047738999826ac4a7e06 | diff --git a/cli_ui/__init__.py b/cli_ui/__init__.py
index <HASH>..<HASH> 100644
--- a/cli_ui/__init__.py
+++ b/cli_ui/__init__.py
@@ -634,39 +634,36 @@ def main_test_colors() -> None:
def main_demo() -> None:
+ info_section(bold, "python-cli demo")
+ info("This is", red, "red")
+ info("this is", bold, "bold")
info("OK", check)
up = Symbol("👍", "+1")
info("I like it", blue, up)
- info_section(bold, "python-cli demo")
- # Monkey-patch message() so that we sleep after
- # each call
- global message
- old_message = message
-
- def new_message(*args: Any, **kwargs: Any) -> None:
- old_message(*args, **kwargs)
- time.sleep(0.5)
-
- message = new_message
+ info()
+ info_section(bold, "various levels of messages")
info_1("Important info")
info_2("Secondary info")
- info("This is", red, "red")
- info("this is", bold, "bold")
+ info_3("More detailed info")
+
+ info()
+ info_section(bold, "progress info")
+
list_of_things = ["foo", "bar", "baz"]
for i, thing in enumerate(list_of_things):
info_count(i, len(list_of_things), thing)
- info_progress("Done", 5, 20)
- info_progress("Done", 10, 20)
- info_progress("Done", 20, 20)
+ info()
+
+ time.sleep(0.5)
+ info_progress("Doing something", 5, 20)
+ time.sleep(0.5)
+ info_progress("Doing something", 10, 20)
+ time.sleep(0.5)
+ info_progress("Doing something", 20, 20)
+ time.sleep(0.5)
info("\n", check, "all done")
- # stop monkey patching
- message = old_message
- fruits = ["apple", "orange", "banana"]
- answer = ask_choice("Choose a fruit", choices=fruits)
- info("You chose:", answer)
-
def main() -> None:
parser = argparse.ArgumentParser() | Rewrite main demo
* Don't monkey patch
* Sleep only when using info_progress()
* Avoid prompting the user
* Better use of sections | TankerHQ_python-cli-ui | train |
02465f8f93b13b5cc52c2f4585ca9afcd2cb6383 | diff --git a/src/nonvisual/filemanager.js b/src/nonvisual/filemanager.js
index <HASH>..<HASH> 100644
--- a/src/nonvisual/filemanager.js
+++ b/src/nonvisual/filemanager.js
@@ -264,7 +264,7 @@ var FileManager = Base.$extend({
}
}
- if (match) {
+ if (match || this.acceptedMimes.length === 0 && this.acceptedExts.length === 0) {
this._callCallbacks("file-open", [file, x, y]);
}
}, | Allows to set no mime/ext filter on FileManager | wanadev_PhotonUI | train |
911779b9bd3de24efffd64af4c60a0e68e579ded | diff --git a/src/ui_components/jf_tree/jf_tree_api.js b/src/ui_components/jf_tree/jf_tree_api.js
index <HASH>..<HASH> 100644
--- a/src/ui_components/jf_tree/jf_tree_api.js
+++ b/src/ui_components/jf_tree/jf_tree_api.js
@@ -8,7 +8,7 @@ export function JFTreeApi($q, $timeout, AdvancedStringMatch) {
this.$flatItems = [];
this.actions = [];
this.listeners = {};
- this.supportedEvents = ['pagination.change', 'item.clicked', 'keydown'];
+ this.supportedEvents = ['ready', 'pagination.change', 'item.clicked', 'item.selected', 'keydown'];
this.appScope = appScope;
this._setDefaults();
}
@@ -21,6 +21,11 @@ export function JFTreeApi($q, $timeout, AdvancedStringMatch) {
setTreeData(rootData) {
this.$root = rootData;
this._buildFlatItems();
+ this.fire('ready');
+ }
+
+ selectFirst() {
+ if (this.$flatItems.length) this._setSelected(this.$flatItems[0])
}
setSortingFunction(sortingFunction) {
@@ -41,6 +46,11 @@ export function JFTreeApi($q, $timeout, AdvancedStringMatch) {
return this;
}
+ setUniqueIdGetter(uniqueIdGetter) {
+ this.uniqueIdGetter = uniqueIdGetter;
+ return this;
+ }
+
setChildrenChecker(childrenChecker) {
this.childrenChecker = childrenChecker;
return this;
@@ -95,6 +105,21 @@ export function JFTreeApi($q, $timeout, AdvancedStringMatch) {
}
}
+ findNode(findFunction) {
+ let item = _.find(this.$flatItems, fi => {
+ return findFunction(fi.data);
+ })
+ if (item) return item.data;
+ }
+
+ selectNode(node) {
+ this._setSelected(this._flatFromNode(node));
+ }
+
+ centerOnNode(node) {
+ this.centerOnItem(this._flatFromNode(node));
+ }
+
centerOnItem(item) {
let index = this.$flatItems.indexOf(item);
let halfPage = Math.floor(this.itemsPerPage / 2);
@@ -228,6 +253,9 @@ export function JFTreeApi($q, $timeout, AdvancedStringMatch) {
flat.$pending = false;
})
}
+ else {
+ defer.resolve();
+ }
}
else defer.resolve();
@@ -352,6 +380,7 @@ export function JFTreeApi($q, $timeout, AdvancedStringMatch) {
_setSelected(item) {
this.$selectedNode = item.data;
+ this.fire('item.selected', item.data);
}
_isSelected(item) { | jf-tree: Api improvements | jfrog_jfrog-ui-essentials | train |
389d7c1214b03e9b2fa9f797d48627b6350522ec | diff --git a/channels/pkg/channels/apply.go b/channels/pkg/channels/apply.go
index <HASH>..<HASH> 100644
--- a/channels/pkg/channels/apply.go
+++ b/channels/pkg/channels/apply.go
@@ -20,6 +20,7 @@ import (
"context"
"fmt"
+ "go.uber.org/multierr"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
@@ -95,6 +96,8 @@ func (p *Applier) applyObjects(ctx context.Context, gvr schema.GroupVersionResou
actualMap[key] = actualObject
}
+ var merr error
+
for _, expectedObjects := range expectedObjects {
name := expectedObjects.GetName()
namespace := expectedObjects.GetNamespace()
@@ -114,17 +117,17 @@ func (p *Applier) applyObjects(ctx context.Context, gvr schema.GroupVersionResou
var opts v1.UpdateOptions
obj.SetResourceVersion(actual.GetResourceVersion())
if _, err := resource.Update(ctx, obj, opts); err != nil {
- return fmt.Errorf("failed to create %s: %w", key, err)
+ merr = multierr.Append(merr, fmt.Errorf("failed to create %s: %w", key, err))
}
} else {
klog.V(2).Infof("creating %s %s", gvr, key)
var opts v1.CreateOptions
if _, err := resource.Create(ctx, obj, opts); err != nil {
- return fmt.Errorf("failed to create %s: %w", key, err)
+ merr = multierr.Append(merr, fmt.Errorf("failed to create %s: %w", key, err))
}
}
}
- return nil
+ return merr
}
diff --git a/channels/pkg/cmd/factory.go b/channels/pkg/cmd/factory.go
index <HASH>..<HASH> 100644
--- a/channels/pkg/cmd/factory.go
+++ b/channels/pkg/cmd/factory.go
@@ -56,6 +56,7 @@ func (f *DefaultFactory) restConfig() (*rest.Config, error) {
if err != nil {
return nil, fmt.Errorf("cannot load kubecfg settings: %w", err)
}
+ restConfig.UserAgent = "kops"
f.cachedRESTConfig = restConfig
}
return f.cachedRESTConfig, nil | Set UserAgent to kops on the REST config | kubernetes_kops | train |
0cc11dfb7ff669a3a76867c6f1e66d4441ea259f | diff --git a/spec/models/analysis_case_spec.rb b/spec/models/analysis_case_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/analysis_case_spec.rb
+++ b/spec/models/analysis_case_spec.rb
@@ -4,10 +4,6 @@ require 'spec_helper'
describe "Analysis Case" do
- puts "Analysis Case Benchmark"
- puts Benchmark.measure { let (:analysis_case) { Fabricate(:analysis_case) } }
-
-
let(:analysis_case) { Fabricate(:analysis_case) }
it "should be created/fabricated" do
diff --git a/spec/models/case_test_spec.rb b/spec/models/case_test_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/case_test_spec.rb
+++ b/spec/models/case_test_spec.rb
@@ -4,9 +4,6 @@ require 'spec_helper'
describe "Case Test" do
- puts "Case Test Benchmark"
- puts Benchmark.measure { let (:case_test) { Fabricate(:case_test) } }
-
let(:case_test) { Fabricate(:case_test) }
it "should be created/fabricated" do
diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/user_spec.rb
+++ b/spec/models/user_spec.rb
@@ -1,13 +1,9 @@
# -*- coding: UTF-8 -*-
require 'spec_helper'
-require 'benchmark'
describe "User" do
- puts "User Benchmark"
- puts Benchmark.measure { let (:user) { Fabricate(:user) } }
-
let (:user) { Fabricate(:user) }
it "should be created/fabricated" do
diff --git a/spec/models/verification_suite_spec.rb b/spec/models/verification_suite_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/verification_suite_spec.rb
+++ b/spec/models/verification_suite_spec.rb
@@ -1,13 +1,9 @@
# -*- coding: UTF-8 -*-
require 'spec_helper'
-require 'benchmark'
describe "Verification Suite" do
- puts "Verification Suite Benchmark"
- puts Benchmark.measure { let (:verification_suite) { Fabricate(:verification_suite) } }
-
let(:verification_suite) { Fabricate(:verification_suite) }
it "should be created/fabricated" do | Removed Benchmarking of model fabrications | dtf-gems_dtf | train |
f858398cda2b2d0bd55d1202b9b8275a4c7e4560 | diff --git a/gulpfile.babel.js b/gulpfile.babel.js
index <HASH>..<HASH> 100644
--- a/gulpfile.babel.js
+++ b/gulpfile.babel.js
@@ -3,7 +3,6 @@ import gulp from 'gulp';
import sourcemaps from 'gulp-sourcemaps';
import babel from 'gulp-babel';
import changed from 'gulp-changed';
-import replace from 'gulp-replace';
gulp.task('compile:src', () => {
return gulp.src('src/**/*.js')
@@ -30,4 +29,5 @@ gulp.task('watch', function() {
);
});
-gulp.task('test', ['watch', 'compile:src', 'compile:test']);
+gulp.task('compile', ['compile:src', 'compile:test']);
+gulp.task('compile-watch', ['compile:src', 'compile:test', 'watch']); | gulpfile: refactor for "npm publish" | SerkanSipahi_app-decorators | train |
9f4ae715414499e5193923e4cda07174c395087e | diff --git a/src/Http/Request.php b/src/Http/Request.php
index <HASH>..<HASH> 100644
--- a/src/Http/Request.php
+++ b/src/Http/Request.php
@@ -111,7 +111,7 @@ class Request
$requestHeaders,
['Content-Type' => 'application/x-www-form-urlencoded']
),
- \http_build_query($postData, '&')
+ \http_build_query($postData, '', '&')
);
} | Use correct separation character for POST body
The second parameter is numeric prefix. The third is separator, it comes from php.ini but typically it's & so this still works fine. But it's better to be explicit. | fkooman_php-oauth2-client | train |
26fd472af472dabe5105005fbebc1ce7029502f4 | diff --git a/datastore/setup.py b/datastore/setup.py
index <HASH>..<HASH> 100644
--- a/datastore/setup.py
+++ b/datastore/setup.py
@@ -30,7 +30,7 @@ version = '1.7.1'
release_status = 'Development Status :: 5 - Production/Stable'
dependencies = [
'google-api-core[grpc] >= 1.6.0, < 2.0.0dev',
- 'google-cloud-core >=0.28.0, <0.29dev',
+ 'google-cloud-core >=0.29.0, <0.30dev',
]
extras = {
}
diff --git a/trace/setup.py b/trace/setup.py
index <HASH>..<HASH> 100644
--- a/trace/setup.py
+++ b/trace/setup.py
@@ -30,7 +30,7 @@ version = '0.20.0'
release_status = 'Development Status :: 3 - Alpha'
dependencies = [
'google-api-core[grpc] >= 1.6.0, < 2.0.0dev',
- 'google-cloud-core >=0.28.0, <0.29dev',
+ 'google-cloud-core >=0.29.0, <0.30dev',
]
extras = {
} | Update version of google-cloud-core (#<I>) | googleapis_google-cloud-python | train |
15ca3e460496c35e032713b2d5e63ef975160466 | diff --git a/views/js/controller/creator/encoders/dom2qti.js b/views/js/controller/creator/encoders/dom2qti.js
index <HASH>..<HASH> 100644
--- a/views/js/controller/creator/encoders/dom2qti.js
+++ b/views/js/controller/creator/encoders/dom2qti.js
@@ -42,7 +42,7 @@ define([
* Some Nodes have attributes that needs typing during decoding.
* @type {Object}
*/
- var typedNodes = {
+ var typedAttributes = {
printedVariable: {
identifier: baseType.getConstantByName('identifier'),
powerForm: baseType.getConstantByName('boolean'),
@@ -163,8 +163,8 @@ define([
var attrName = normalizeNodeName(value.nodeName);
//todo: cover with unit tests
if (attrName) {
- if (typedNodes[nodeName] && typedNodes[nodeName][attrName]) {
- acc[attrName] = baseType.getValue(typedNodes[nodeName][attrName], value.nodeValue);
+ if (typedAttributes[nodeName] && typedAttributes[nodeName][attrName]) {
+ acc[attrName] = baseType.getValue(typedAttributes[nodeName][attrName], value.nodeValue);
} else {
acc[attrName] = value.nodeValue;
} | renamed typedNodes => typedAttributes | oat-sa_extension-tao-testqti | train |
8a8a720d069037a10053354b2760e8c936d34b3f | diff --git a/ChernoffFaces.js b/ChernoffFaces.js
index <HASH>..<HASH> 100644
--- a/ChernoffFaces.js
+++ b/ChernoffFaces.js
@@ -145,16 +145,20 @@
ChernoffFaces.prototype.listeners = function () {
var that = this;
-
node.on(that.change, function(msg) {
- var fv = new FaceVector(that.sc.getAllValues());
- that.fp.redraw(fv);
+ that.draw(that.sc.getAllValues());
});
};
+ ChernoffFaces.prototype.draw = function (features) {
+ if (!features) return;
+ var fv = new FaceVector(features);
+ this.fp.redraw(fv);
+ };
ChernoffFaces.prototype.getAllValues = function() {
- return this.sc.getAllValues();
+ //if (this.sc) return this.sc.getAllValues();
+ return this.fp.face;
};
ChernoffFaces.prototype.randomize = function() {
@@ -187,7 +191,7 @@
//Draws a Chernoff face.
FacePainter.prototype.draw = function (face, x, y) {
if (!face) return;
-
+ this.face = face;
this.fit2Canvas(face);
this.canvas.scale(face.scaleX, face.scaleY); | HTMLRenderer render Table and List | nodeGame_nodegame-widgets | train |
767a4f6a532e9eb897694777b52e4fbdf5d65394 | diff --git a/contrib/dox/doc_builder.js b/contrib/dox/doc_builder.js
index <HASH>..<HASH> 100644
--- a/contrib/dox/doc_builder.js
+++ b/contrib/dox/doc_builder.js
@@ -277,7 +277,9 @@
var newMethods = getParentMethods(module);
// If we have a parent, add those methods in
- if (module.is_extends) {
+ // but only if it isn't StormService, which we special case for now
+ var isStormService = module.name === "splunkjs.StormService";
+ if (module.is_extends && !isStormService) {
module.inherited = newMethods.filter(function(method) {
return (module.methods.indexOf(method) < 0);
});
@@ -292,11 +294,13 @@
}
var outputs = {};
- modules.forEach(function(module) {
+ modules.sort(function(a,b) {
+ return (a.name < b.name ? -1 : (a.name === b.name ? 0 : 1));
+ }).forEach(function(module) {
var moduleList = [];
for(var i = 0; i < modules.length; i++) {
if (modules[i] === module) {
- moduleList.unshift(module);
+ moduleList.push(module);
}
else {
moduleList.push({name: modules[i].name}); | Change documentation generator to sort modules alphabetically
Also, don't put inherited docs for StormService. | splunk_splunk-sdk-javascript | train |
c05c64d8cfab1c679157f49abbc5ba11f5891534 | diff --git a/src/transforms.js b/src/transforms.js
index <HASH>..<HASH> 100644
--- a/src/transforms.js
+++ b/src/transforms.js
@@ -46,10 +46,10 @@ const sort = ({
const Sort = () => {
const columns = getSortingColumns();
const index = columns.map(c => c.property).indexOf(property);
- let headerClass = 'sort-none';
+ let headerClass = 'sort sort-none';
if (index >= 0) {
- headerClass = `sort-${columns[index].sort}`;
+ headerClass = `sort sort-${columns[index].sort}`;
}
return {
diff --git a/tests/transforms_test.js b/tests/transforms_test.js
index <HASH>..<HASH> 100644
--- a/tests/transforms_test.js
+++ b/tests/transforms_test.js
@@ -107,7 +107,7 @@ describe('sort', function () {
const sorter = sort();
const result = sorter('test')();
- expect(result.className).to.equal('sort-none');
+ expect(result.className).to.equal('sort sort-none');
});
it('sets sorting class', function () {
@@ -125,7 +125,7 @@ describe('sort', function () {
});
const result = sorter(testProperty)();
- expect(result.className).to.equal(`sort-${sortDirection}`);
+ expect(result.className).to.equal(`sort sort-${sortDirection}`);
});
it('triggers sorting on click', function () { | transforms - Attach `sort` class to sort for easier styling | reactabular_reactabular | train |
91db94b278b12a6de7afe69805d3678bb670fd46 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -265,15 +265,8 @@ def cython_extensions_and_necessity():
for name in CYTHON_EXTENSION_MODULE_NAMES]
config = os.environ.get('CONFIG', 'opt')
prefix = 'libs/' + config + '/'
- if "darwin" in sys.platform or USE_PREBUILT_GRPC_CORE:
- extra_objects = [prefix + 'libares.a',
- prefix + 'libboringssl.a',
- prefix + 'libgpr.a',
- prefix + 'libgrpc.a']
- core_c_files = []
- else:
- core_c_files = list(CORE_C_FILES)
- extra_objects = []
+ core_c_files = list(CORE_C_FILES)
+ extra_objects = []
extensions = [
_extension.Extension(
name=module_name, | build grpc libraries now that submake for macOS is removed | grpc_grpc | train |
Subsets and Splits