hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
24ee82e9fd476a1c651051d29384612fda0a52c4
|
diff --git a/rows/fields.py b/rows/fields.py
index <HASH>..<HASH> 100644
--- a/rows/fields.py
+++ b/rows/fields.py
@@ -15,7 +15,8 @@ REGEXP_ONLY_NUMBERS = re.compile('[^0-9]')
# TODO: all fields must accept `consider_locale=False` parameter so we can set
# it fo True if want to use locale but if not it won't slow down the
# process of serializing/deserializing data
-
+# TODO: should test 'None' directly on Field.deserialize and create a test for
+# it
class Field(object):
TYPE = type(None)
@@ -42,6 +43,8 @@ class BoolField(Field):
def deserialize(cls, value, *args, **kwargs):
if isinstance(value, cls.TYPE) or value is None:
return value
+ elif not value.strip():
+ return None
if value in ('true', '1', 'yes'):
return True
@@ -65,6 +68,8 @@ class IntegerField(Field):
def deserialize(cls, value, *args, **kwargs):
if isinstance(value, cls.TYPE) or value is None:
return value
+ elif not value.strip():
+ return None
return locale.atoi(value)
@@ -84,6 +89,8 @@ class FloatField(Field):
def deserialize(cls, value, *args, **kwargs):
if isinstance(value, cls.TYPE) or value is None:
return value
+ elif not value.strip():
+ return None
return locale.atof(value)
@@ -111,6 +118,8 @@ class DecimalField(Field):
def deserialize(cls, value, *args, **kwargs):
if isinstance(value, cls.TYPE) or value is None:
return value
+ elif not value.strip():
+ return None
locale_vars = locale.localeconv()
decimal_separator = locale_vars['decimal_point']
@@ -154,6 +163,8 @@ class PercentField(DecimalField):
# TODO: do it in all classes (and maybe use on serialize)
if isinstance(value, cls.TYPE) or value is None:
return value
+ elif not value.strip():
+ return None
if '%' not in value:
raise ValueError("Can't be {}".format(cls.__name__))
@@ -177,6 +188,8 @@ class DateField(Field):
def deserialize(cls, value, *args, **kwargs):
if isinstance(value, cls.TYPE) or value is None:
return value
+ elif not value.strip():
+ return None
dt_object = datetime.datetime.strptime(value, cls.INPUT_FORMAT)
return datetime.date(dt_object.year, dt_object.month, dt_object.day)
@@ -198,6 +211,8 @@ class DatetimeField(Field):
def deserialize(cls, value, *args, **kwargs):
if isinstance(value, cls.TYPE) or value is None:
return value
+ elif not value.strip():
+ return None
# TODO: may use iso8601
groups = cls.DATETIME_REGEXP.findall(value)
@@ -224,6 +239,8 @@ class UnicodeField(Field):
def deserialize(cls, value, *args, **kwargs):
if isinstance(value, cls.TYPE) or value is None:
return value
+ elif not value.strip():
+ return None
if type(value) is unicode:
return value
@@ -247,5 +264,7 @@ class StringField(Field):
def deserialize(cls, value, *args, **kwargs):
if isinstance(value, cls.TYPE) or value is None:
return value
+ elif not value.strip():
+ return None
return value
|
Fix fields' deserialize method (deal with None)
|
turicas_rows
|
train
|
2fe785ed350f65cef85edc68035e169e8ddad52d
|
diff --git a/common/config.go b/common/config.go
index <HASH>..<HASH> 100644
--- a/common/config.go
+++ b/common/config.go
@@ -161,14 +161,6 @@ func DownloadableURL(original string) (string, error) {
// Make sure it is lowercased
url.Scheme = strings.ToLower(url.Scheme)
- // This is to work around issue #5927. This can safely be removed once
- // we distribute with a version of Go that fixes that bug.
- //
- // See: https://code.google.com/p/go/issues/detail?id=5927
- if url.Path != "" && url.Path[0] != '/' {
- url.Path = "/" + url.Path
- }
-
// Verify that the scheme is something we support in our common downloader.
supported := []string{"file", "http", "https"}
found := false
|
common: remove dead code
The referenced bug was fixed in Go <I>,
and Packer requires Go <I>+.
|
hashicorp_packer
|
train
|
e16f7c01fcc3a807d56662dd81360f8fc097bc59
|
diff --git a/client/jetpack-connect/authorize.js b/client/jetpack-connect/authorize.js
index <HASH>..<HASH> 100644
--- a/client/jetpack-connect/authorize.js
+++ b/client/jetpack-connect/authorize.js
@@ -224,7 +224,8 @@ export class JetpackAuthorize extends Component {
this.isFromJpo() ||
this.isFromBlockEditor() ||
this.shouldRedirectJetpackStart() ||
- getRoleFromScope( scope ) === 'subscriber'
+ getRoleFromScope( scope ) === 'subscriber' ||
+ this.isJetpackUpgradeFlow()
) {
debug(
'Going back to WP Admin.',
@@ -283,6 +284,18 @@ export class JetpackAuthorize extends Component {
return 'sso' === from && isSsoApproved( clientId );
}
+ /**
+ * Check if the user is coming from the Jetpack upgrade flow.
+ *
+ * @param {object} props Props to test
+ * @param {?string} props.authQuery.redirectAfterAuth Where were we redirected after auth.
+ * @returns {boolean} True if the user is coming from the Jetpack upgrade flow, false otherwise.
+ */
+ isJetpackUpgradeFlow( props = this.props ) {
+ const { redirectAfterAuth } = props.authQuery;
+ return redirectAfterAuth.includes( 'page=jetpack&action=authorize_redirect' );
+ }
+
isWooRedirect = ( props = this.props ) => {
const { from } = props.authQuery;
return (
diff --git a/client/jetpack-connect/test/authorize.js b/client/jetpack-connect/test/authorize.js
index <HASH>..<HASH> 100644
--- a/client/jetpack-connect/test/authorize.js
+++ b/client/jetpack-connect/test/authorize.js
@@ -202,4 +202,28 @@ describe( 'JetpackAuthorize', () => {
expect( result ).toBe( true );
} );
} );
+
+ describe( 'shouldSeePlans', () => {
+ const isJetpackUpgradeFlow = new JetpackAuthorize().isJetpackUpgradeFlow;
+
+ test( 'should see plans', () => {
+ const props = {
+ authQuery: {
+ redirectAfterAuth: 'page=jetpack&action=something_else',
+ },
+ };
+
+ expect( isJetpackUpgradeFlow( props ) ).toBe( false );
+ } );
+
+ test( 'should be sent back', () => {
+ const props = {
+ authQuery: {
+ redirectAfterAuth: 'page=jetpack&action=authorize_redirect',
+ },
+ };
+
+ expect( isJetpackUpgradeFlow( props ) ).toBe( true );
+ } );
+ } );
} );
|
Jetpack Upgrade Flow: Connecting Users (#<I>)
If a Jetpack user is not connected to WP.com, the upgrade flow will lead them nowhere.
It is part of the solution that fixes the flow, which also includes Jetpack and WP.com changes.
This commit makes the authentication upgrade flow will be exempt from redirecting users to the Jetpack "Plans" page.
The flow is already a purchase process, so there's no need for the "Plans" page to show up.
|
Automattic_wp-calypso
|
train
|
076fe6aab6edc3afc52eda9427c0a3fc60ccd18a
|
diff --git a/java/jeeintegration/src/main/java/io/joynr/jeeintegration/JoynrIntegrationBean.java b/java/jeeintegration/src/main/java/io/joynr/jeeintegration/JoynrIntegrationBean.java
index <HASH>..<HASH> 100644
--- a/java/jeeintegration/src/main/java/io/joynr/jeeintegration/JoynrIntegrationBean.java
+++ b/java/jeeintegration/src/main/java/io/joynr/jeeintegration/JoynrIntegrationBean.java
@@ -140,17 +140,17 @@ public class JoynrIntegrationBean {
}
if (gbids == null) {
- // default registration (in default backend)
- runtime.registerProvider(getDomainForProvider(beanClass),
- provider,
- providerQos,
- false,
- providesJoynrTypesInfoAnnotation.interfaceClass());
-
- } else {
- // TODO register with GBIDs
+ // empty array for default registration (i.e. in default backend)
+ gbids = new String[0];
}
+ runtime.registerProvider(getDomainForProvider(beanClass),
+ provider,
+ providerQos,
+ gbids,
+ false,
+ providesJoynrTypesInfoAnnotation.interfaceClass());
+
registeredProviders.add(provider);
}
}
|
[JEE] Use the adapted register method from JoynrRuntime
|
bmwcarit_joynr
|
train
|
abc98709a3be05f5d0e8a111585107eeb9d474de
|
diff --git a/cdm/src/main/java/ucar/nc2/dt/StationaryRadarCollection.java b/cdm/src/main/java/ucar/nc2/dt/StationaryRadarCollection.java
index <HASH>..<HASH> 100644
--- a/cdm/src/main/java/ucar/nc2/dt/StationaryRadarCollection.java
+++ b/cdm/src/main/java/ucar/nc2/dt/StationaryRadarCollection.java
@@ -5,6 +5,7 @@ import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Iterator;
+import java.util.ArrayList;
/** A collection of data at unconnected radar station.
* User can subset by stations, bounding box and by date range.
@@ -84,7 +85,7 @@ public interface StationaryRadarCollection {
* @param preInt the time range before interval
* @param postInt the time range after interval
* @return List of getDataClass() */
- public List getData( String sName, Date start, Date end, int interval, int roundTo, int preInt,
+ public ArrayList getData( String sName, Date start, Date end, int interval, int roundTo, int preInt,
int postInt) throws IOException;
/** Get data for this Station within the specified date range.
@@ -95,7 +96,7 @@ public interface StationaryRadarCollection {
* @param preInt the time range before interval
* @param postInt the time range after interval
* @return List of getDataClass() */
- public List getDataURIs( String sName, Date start, Date end, int interval, int roundTo, int preInt,
+ public ArrayList getDataURIs( String sName, Date start, Date end, int interval, int roundTo, int preInt,
int postInt) throws IOException;
/** Get data for this Station within the specified date range, allow user to cancel.
@@ -108,7 +109,7 @@ public interface StationaryRadarCollection {
* @param postInt the time range after interval
* @return List of RadialDatasetSweep data
*/
- public List getData( String sName, Date start, Date end, int interval, int roundTo, int preInt,
+ public ArrayList getData( String sName, Date start, Date end, int interval, int roundTo, int preInt,
int postInt, ucar.nc2.util.CancelTask cancel) throws IOException;
/** Get data for this Station within the specified date range.
@@ -120,7 +121,7 @@ public interface StationaryRadarCollection {
* @param postInt the time range after interval
* @param cancel allow user to cancel. Implementors should return ASAP.
* @return List of getDataClass() */
- public List getDataURIs( String sName, Date start, Date end, int interval, int roundTo, int preInt,
+ public ArrayList getDataURIs( String sName, Date start, Date end, int interval, int roundTo, int preInt,
int postInt, ucar.nc2.util.CancelTask cancel) throws IOException;
/** Get all data for a list of Stations.
* @return List of RadialDatasetSweep data
|
change output getData to ArrayList
|
Unidata_thredds
|
train
|
92e8d88cf52bcdcea6cc7cc08c50f5199d80e225
|
diff --git a/src/sap.m/src/sap/m/DateTimePickerRenderer.js b/src/sap.m/src/sap/m/DateTimePickerRenderer.js
index <HASH>..<HASH> 100644
--- a/src/sap.m/src/sap/m/DateTimePickerRenderer.js
+++ b/src/sap.m/src/sap/m/DateTimePickerRenderer.js
@@ -37,10 +37,9 @@ sap.ui.define(['sap/ui/core/Renderer', './DatePickerRenderer', './InputBaseRende
oRm.openStart("div", oControl.getId() + "-timezoneLabel");
oRm.class("sapMDTPTimezoneLabel");
- oRm.attr("title", sTimezone);
oRm.openEnd();
- oRm.openStart("span");
+ oRm.openStart("span", oControl.getId() + "-timezoneID");
oRm.openEnd();
oRm.text(sTimezone);
oRm.close("span");
@@ -68,6 +67,16 @@ sap.ui.define(['sap/ui/core/Renderer', './DatePickerRenderer', './InputBaseRende
}
};
+ DateTimePickerRenderer.getAriaDescribedBy = function(oControl) {
+ var sDescribedBy = InputBaseRenderer.getAriaDescribedBy.apply(this, arguments);
+
+ if (oControl._getShowTimezone()) {
+ sDescribedBy += " " + oControl.getId() + "-timezoneID";
+ }
+
+ return sDescribedBy;
+ };
+
return DateTimePickerRenderer;
}, /* bExport= */ true);
diff --git a/src/sap.m/test/sap/m/qunit/DateTimePicker.qunit.js b/src/sap.m/test/sap/m/qunit/DateTimePicker.qunit.js
index <HASH>..<HASH> 100755
--- a/src/sap.m/test/sap/m/qunit/DateTimePicker.qunit.js
+++ b/src/sap.m/test/sap/m/qunit/DateTimePicker.qunit.js
@@ -625,6 +625,33 @@ sap.ui.define([
}, 400);
});
+ QUnit.test("showTimezone and aria-describedBy", function(assert) {
+ // arrange
+ var oDTP = new DateTimePicker("DTPACC")
+ .placeAt("qunit-fixture"),
+ oInputRef;
+ oCore.applyChanges();
+
+ oInputRef = oDTP.$("inner");
+
+ // assert
+ assert.ok(oInputRef.attr("aria-describedby").indexOf("DTPACC-timezoneID") === -1,
+ "the timezone id is not included in the aria-describedby DOM references");
+
+ // act
+ oDTP.setShowTimezone(true);
+ oCore.applyChanges();
+
+ oInputRef = oDTP.$("inner");
+
+ // assert
+ assert.ok(oInputRef.attr("aria-describedby").indexOf("DTPACC-timezoneID") > -1,
+ "the timezone id is included in the aria-describedby DOM references");
+
+ // clean
+ oDTP.destroy();
+ });
+
QUnit.module("Calendar and TimePicker");
QUnit.test("Open picker on small screen", function(assert) {
|
[INTERNAL] sap.m.DateTimePicker: Improve accessibility
With the ability to display the timezone, its name should be announced by the
screen readers.
JIRA: BGSOFUIBALKAN-<I>
Change-Id: I4be<I>f<I>c2decb<I>f<I>f<I>f
|
SAP_openui5
|
train
|
3c0195d00e59f8c76446dad727761a021892ae24
|
diff --git a/common/vr/common/utils.py b/common/vr/common/utils.py
index <HASH>..<HASH> 100644
--- a/common/vr/common/utils.py
+++ b/common/vr/common/utils.py
@@ -223,13 +223,15 @@ def get_lxc_version():
""" Asks the current host what version of LXC it has. Returns it as a
string. If LXC is not installed, raises subprocess.CalledProcessError"""
- # Old LXC had an lxc-version executable, and prefixed its result with
+ # Old LXC had an lxc-version executable, and prefixed its result with
# "lxc version: "
try:
- result = subprocess.check_output(['lxc-version']).rstrip()
+ result = subprocess.check_output(['lxc-version'],
+ stderr=subprocess.STDOUT).rstrip()
return result.replace("lxc version: ", "")
except (OSError, subprocess.CalledProcessError):
pass
# New LXC instead has a --version option on most installed executables.
- return subprocess.check_output(['lxc-start', '--version']).rstrip()
+ return subprocess.check_output(['lxc-start', '--version'],
+ stderr=subprocess.STDOUT).rstrip()
|
Redirecting all command errors to stdout
|
yougov_vr.common
|
train
|
f86a6f627e8b2ec1ab6f0dba460eb890be9c604f
|
diff --git a/spyder_kernels/comms/commbase.py b/spyder_kernels/comms/commbase.py
index <HASH>..<HASH> 100644
--- a/spyder_kernels/comms/commbase.py
+++ b/spyder_kernels/comms/commbase.py
@@ -455,7 +455,7 @@ class CommBase(object):
"""
Handle an error that was raised on the other side asyncronously.
"""
- error_wrapper.raise_error()
+ error_wrapper.print_error()
def _sync_error(self, error_wrapper):
"""
|
Print async error instead of raising it
|
spyder-ide_spyder-kernels
|
train
|
cc370c24368a578032f305910b4b87f017803729
|
diff --git a/GPy/models/Bayesian_GPLVM.py b/GPy/models/Bayesian_GPLVM.py
index <HASH>..<HASH> 100644
--- a/GPy/models/Bayesian_GPLVM.py
+++ b/GPy/models/Bayesian_GPLVM.py
@@ -180,7 +180,7 @@ class Bayesian_GPLVM(sparse_GP, GPLVM):
return np.hstack((self.dbound_dmuS.flatten(), self.dbound_dZtheta))
def plot_latent(self, *args, **kwargs):
- util.plot_latent_indices(self, *args, **kwargs)
+ plot_latent.plot_latent_indices(self, *args, **kwargs)
def do_test_latents(self, Y):
"""
|
Fixed bug in BGPLVM plot
|
SheffieldML_GPy
|
train
|
498e8742dc61fc8c4733ce17e8e427b0df86f4d7
|
diff --git a/buildbucket/appengine/internal/metrics/builder.go b/buildbucket/appengine/internal/metrics/builder.go
index <HASH>..<HASH> 100644
--- a/buildbucket/appengine/internal/metrics/builder.go
+++ b/buildbucket/appengine/internal/metrics/builder.go
@@ -220,6 +220,27 @@ func reportMaxAge(ctx context.Context, project, bucket, legacyBucket, builder st
// reportBuildCount computes and reports # of builds with SCHEDULED and STARTED.
func reportBuildCount(ctx context.Context, project, bucket, legacyBucket, builder string) error {
- // TODO(ddoman): implement me
+ var nScheduled, nStarted int64
+ q := datastore.NewQuery(model.BuildKind).
+ Eq("bucket_id", protoutil.FormatBucketID(project, bucket)).
+ Eq("experimental", false).
+ Eq("tags", "builder:"+builder)
+ eg, ctx := errgroup.WithContext(ctx)
+ eg.Go(func() (err error) {
+ nScheduled, err = datastore.Count(ctx, q.Eq("status_v2", pb.Status_SCHEDULED))
+ return
+ })
+ eg.Go(func() (err error) {
+ nStarted, err = datastore.Count(ctx, q.Eq("status_v2", pb.Status_STARTED))
+ return
+ })
+ if err := eg.Wait(); err != nil {
+ return err
+ }
+
+ V1.BuildCount.Set(ctx, nScheduled, legacyBucket, builder, pb.Status_name[int32(pb.Status_SCHEDULED)])
+ V1.BuildCount.Set(ctx, nStarted, legacyBucket, builder, pb.Status_name[int32(pb.Status_STARTED)])
+ V2.BuildCount.Set(ctx, nScheduled, pb.Status_name[int32(pb.Status_SCHEDULED)])
+ V2.BuildCount.Set(ctx, nStarted, pb.Status_name[int32(pb.Status_STARTED)])
return nil
}
diff --git a/buildbucket/appengine/internal/metrics/builder_test.go b/buildbucket/appengine/internal/metrics/builder_test.go
index <HASH>..<HASH> 100644
--- a/buildbucket/appengine/internal/metrics/builder_test.go
+++ b/buildbucket/appengine/internal/metrics/builder_test.go
@@ -51,9 +51,9 @@ func TestReportBuilderMetrics(t *testing.T) {
store := tsmon.Store(ctx)
prj, bkt := "infra", "ci"
task := &target.Task{
- ServiceName: "service",
+ ServiceName: "svc",
JobName: "job",
- HostName: "ins-0",
+ HostName: "ins",
TaskNum: 0,
}
store.SetDefaultTarget(task)
diff --git a/buildbucket/appengine/internal/metrics/v1.go b/buildbucket/appengine/internal/metrics/v1.go
index <HASH>..<HASH> 100644
--- a/buildbucket/appengine/internal/metrics/v1.go
+++ b/buildbucket/appengine/internal/metrics/v1.go
@@ -36,11 +36,13 @@ var (
"failure_reason": field.String("failure_reason"),
"must_be_never_leased": field.Bool("must_be_never_leased"),
"result": field.String("result"),
+ "status": field.String("status"),
"user_agent": field.String("user_agent"),
}
// V1 is a collection of metric objects for V1 metrics.
V1 = struct {
+ BuildCount metric.Int
BuildCountCreated metric.Counter
BuildCountStarted metric.Counter
BuildCountCompleted metric.Counter
@@ -49,6 +51,11 @@ var (
BuildDurationScheduling metric.CumulativeDistribution
MaxAgeScheduled metric.Float
}{
+ BuildCount: metric.NewInt(
+ "buildbucket/builds/count",
+ "Number of pending/running prod builds", nil,
+ bFields("status")...,
+ ),
BuildCountCreated: metric.NewCounter(
"buildbucket/builds/created",
"Build creation", nil,
diff --git a/buildbucket/appengine/internal/metrics/v2.go b/buildbucket/appengine/internal/metrics/v2.go
index <HASH>..<HASH> 100644
--- a/buildbucket/appengine/internal/metrics/v2.go
+++ b/buildbucket/appengine/internal/metrics/v2.go
@@ -15,6 +15,7 @@
package metrics
import (
+ "go.chromium.org/luci/common/tsmon/field"
"go.chromium.org/luci/common/tsmon/metric"
"go.chromium.org/luci/common/tsmon/types"
)
@@ -22,9 +23,17 @@ import (
var (
// V2 is a collection of metric objects for V2 metrics.
V2 = struct {
+ BuildCount metric.Int
BuilderPresence metric.Bool
MaxAgeScheduled metric.Float
}{
+ BuildCount: metric.NewIntWithTargetType(
+ "buildbucket/v2/builds/count",
+ (&Builder{}).Type(),
+ "Number of pending/running prod builds",
+ nil,
+ field.String("status"),
+ ),
BuilderPresence: metric.NewBoolWithTargetType(
"buildbucket/v2/builder/presence",
(&Builder{}).Type(),
|
[buildbucket] report build count metrics
Before this CL is rolled out, PyBB needs to be updated to
stop reporting global metrics.
Change-Id: Iea<I>ebfc2ce4f8cf<I>e2f<I>cc1b<I>bc4c5c9e8
Bug: <I>
Reviewed-on: <URL>
|
luci_luci-go
|
train
|
a45007fcf6e5dca092a3d7b325a77a39e85ce251
|
diff --git a/databind/src/main/java/com/nextfaze/databind/IncrementalArrayData.java b/databind/src/main/java/com/nextfaze/databind/IncrementalArrayData.java
index <HASH>..<HASH> 100644
--- a/databind/src/main/java/com/nextfaze/databind/IncrementalArrayData.java
+++ b/databind/src/main/java/com/nextfaze/databind/IncrementalArrayData.java
@@ -298,9 +298,9 @@ public abstract class IncrementalArrayData<T> extends AbstractData<T> implements
private void clearDataAndNotify() {
if (size() > 0) {
mData.clear();
- onInvalidate();
notifyDataChanged();
}
+ onInvalidate();
}
private void startThreadIfNeeded() {
|
Ensure IncrementalArrayData.onInvalidate() is called regardless of whether the data is empty
|
NextFaze_power-adapters
|
train
|
6601749898ce5440d4c96a1897806507dd467b37
|
diff --git a/src/Leevel/Router/Matching/Annotation.php b/src/Leevel/Router/Matching/Annotation.php
index <HASH>..<HASH> 100644
--- a/src/Leevel/Router/Matching/Annotation.php
+++ b/src/Leevel/Router/Matching/Annotation.php
@@ -181,8 +181,8 @@ class Annotation extends BaseMatching implements IMatching
}
// 额外参数 ['extend1' => 'foo']
- if (isset($router[$attributesKey]) && is_array($router[$attributesKey])) {
- $result[$attributesKey] = array_merge($result[$attributesKey], $router[$attributesKey]);
+ if (isset($router['attributes']) && is_array($router['attributes'])) {
+ $result[$attributesKey] = array_merge($result[$attributesKey], $router['attributes']);
}
// 中间件
@@ -192,7 +192,7 @@ class Annotation extends BaseMatching implements IMatching
// 匹配的变量
$result[IRouter::VARS] = $this->matchedVars;
-
+
return $result;
}
|
fix(router): Fix extend attributes of router
|
hunzhiwange_framework
|
train
|
f667f71304a988829a5d91ffbecc54413688fa9e
|
diff --git a/src/Response.php b/src/Response.php
index <HASH>..<HASH> 100644
--- a/src/Response.php
+++ b/src/Response.php
@@ -106,7 +106,7 @@ class Response implements ResponseInterface
$this->statusCode = $code;
$this->headers = $headers;
- $this->reasonPhrase = $this->status[$this->code];
+ $this->reasonPhrase = $this->status[$this->statusCode];
}
/**
|
Changing code into statusCode..
|
plvhx_psr7-http-message
|
train
|
78fcba8c58e52adb049892dc9d70e9e7a62f8f4f
|
diff --git a/lib/npolar/api/client/json_api_client.rb b/lib/npolar/api/client/json_api_client.rb
index <HASH>..<HASH> 100644
--- a/lib/npolar/api/client/json_api_client.rb
+++ b/lib/npolar/api/client/json_api_client.rb
@@ -153,7 +153,7 @@ module Npolar::Api::Client
def get_body(uri, param={})
@param = param
response = get(uri)
- unless response.success?
+ unless (200.299).include? response.code
raise "Could not GET #{uri} status: #{response.code}"
end
@@ -575,7 +575,7 @@ module Npolar::Api::Client
else
response = r
- "#{response.code} #{response.request.http_method} #{response.request.url} [#{self.class.name}] #{response.total_time} #{response.body.bytesize} #{response.body[0..255]}"
+ "#{response.code} #{response.request.http_method} #{response.request.url} [#{self.class.name}] #{response.total_time} #{response.body.bytesize} #{response.body[0..1024]}"
end
end
|
No more #success? [!?]
|
npolar_npolar-api-client-ruby
|
train
|
8ffd01b917931c2be3fdb95363e0fd382e79c8b8
|
diff --git a/core/class.mysqldbi.php b/core/class.mysqldbi.php
index <HASH>..<HASH> 100644
--- a/core/class.mysqldbi.php
+++ b/core/class.mysqldbi.php
@@ -6,7 +6,7 @@
*
* @extends mysqli
*
- * @version 4.7.2 2012-03-24
+ * @version 4.7.3 2012-11-03
* @author Gregor Kofler
*
* @todo execute is "ambiguous" as deprecated alias for mysqli_stmt_execute
@@ -771,56 +771,7 @@ class Mysqldbi extends mysqli {
}
/**
- * Administration and handling of a nested set
- */
- public function getParentNodes($tbl, $id, $fields = null) {
- if(is_array($fields)) {
- for($i = 0; $i < count($fields); $i++) {
- $fields[$i] = 'a.'.$fields[$i];
- }
- $fields = implode(',', $fields);
- }
- else {
- $fields = 'a.*';
- }
- $pk = $this->getPrimaryKey($tbl);
- $sql = "
- select
- $fields
- from
- $tbl a, $tbl b
- WHERE a.l <= b.l AND a.r >= b.r and b.$pk = $id and a.parent is not null";
-
- return($this->doQuery($sql));
- }
-
- public function getSubTree($tbl, $id = null, $fields = null) {
- if(is_array($fields)) {
- for($i = 0; $i < count($fields); $i++) {
- $fields[$i] = 'a.'.$fields[$i];
- }
- $fields = implode(',', $fields);
- }
- else {
- $fields = 'a.*';
- }
-
- $where = empty($id) ? 'a.level > 0' : "b.$pk = $id";
- $pk = $this->getPrimaryKey($tbl);
- $sql = "
- select distinct
- $fields
- from
- $tbl a, $tbl b
- where
- a.l BETWEEN b.l AND b.r and $where
- order by a.l";
-
- return($this->doQuery($sql));
- }
-
- /**
- * overloads native prepare method
+ * overwrites native prepare method
*
* @param string $query
*/
|
Removed unused code for handling nested sets.
Change-Id: I0cdf<I>aa9d3c2d<I>a<I>e<I>e5a6d<I>ad<I>
|
Vectrex_vxPHP
|
train
|
497a84be55ba3ef02540f58a9105a2a92388d96f
|
diff --git a/languagetool-language-modules/pt/src/test/java/org/languagetool/rules/pt/PortugueseWordRepeatBeginningRuleTest.java b/languagetool-language-modules/pt/src/test/java/org/languagetool/rules/pt/PortugueseWordRepeatBeginningRuleTest.java
index <HASH>..<HASH> 100644
--- a/languagetool-language-modules/pt/src/test/java/org/languagetool/rules/pt/PortugueseWordRepeatBeginningRuleTest.java
+++ b/languagetool-language-modules/pt/src/test/java/org/languagetool/rules/pt/PortugueseWordRepeatBeginningRuleTest.java
@@ -38,7 +38,7 @@ public class PortugueseWordRepeatBeginningRuleTest {
// correct sentences:
assertEquals(0, langTool.check("Este exemplo está correto. Este exemplo também está.").size());
assertEquals(0, langTool.check("Certo, isto está bem. Este exemplo está correto. Certo que este também.").size());
- assertEquals(0, langTool.check("2011: Setembro já passou. 2011: Outubro também. 2011: Novembro já se foi.").size());
+ assertEquals(0, langTool.check("2011: Setembro já passou. 2011: Outubro também já passou. 2011: Novembro já se foi.").size());
// errors:
assertEquals(1, langTool.check("Este exemplo está correto. Este segundo também. Este terceiro exemplo não.").size());
assertEquals(1, langTool.check("Então, este está correto. Então, este está errado, por causa da repetição.").size());
|
[pt] make another test conform with NO_VERB rule
|
languagetool-org_languagetool
|
train
|
bec9c06889b20dd06a8d67372bf3c57c012d38fd
|
diff --git a/tests/League/StatsD/Test/LaravelTestCase.php b/tests/League/StatsD/Test/LaravelTestCase.php
index <HASH>..<HASH> 100644
--- a/tests/League/StatsD/Test/LaravelTestCase.php
+++ b/tests/League/StatsD/Test/LaravelTestCase.php
@@ -33,6 +33,8 @@ class LaravelTestCase extends TestCase
$provider = new StatsdServiceProvider($app);
$app->register($provider);
+ $provider->boot();
+
return $provider;
}
}
\ No newline at end of file
|
Added boot function too Laravel Service Provider Test Case
|
thephpleague_statsd
|
train
|
897ccd9a68ebb58af93ca137e6f14343a9b6de05
|
diff --git a/resources/views/layouts/jqm.php b/resources/views/layouts/jqm.php
index <HASH>..<HASH> 100644
--- a/resources/views/layouts/jqm.php
+++ b/resources/views/layouts/jqm.php
@@ -5,11 +5,11 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta name="format-detection" content="telephone=no">
<title><?= $e($wei->page->getTitle()) ?></title>
- <link rel="stylesheet" href="//cdn.bootcss.com/jquery-mobile/1.4.0/jquery.mobile.min.css">
+ <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jquery-mobile/1.4.0/jquery.mobile.min.css">
<link rel="stylesheet" href="<?= $asset('plugins/app/css/jqm.css') ?>">
<?= $wei->page->renderHead() ?>
- <script src="//cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
- <script src="//cdn.bootcss.com/jquery-mobile/1.4.0/jquery.mobile.min.js"></script>
+ <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
+ <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mobile/1.4.0/jquery.mobile.min.js"></script>
<script src="<?= $asset([
'comps/requirejs/require.min.js',
'plugins/app/js/require-config.js',
diff --git a/resources/views/layouts/pc.php b/resources/views/layouts/pc.php
index <HASH>..<HASH> 100644
--- a/resources/views/layouts/pc.php
+++ b/resources/views/layouts/pc.php
@@ -12,7 +12,7 @@
'plugins/app/css/app.css',
]) ?>">
<?= $block->get('css') ?>
- <script src="//cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
+ <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="<?= $asset([
'comps/requirejs/require.js',
'comps/bootstrap/dist/js/bootstrap.min.js',
|
fix: bootcdn更换为cf
|
miaoxing_plugin
|
train
|
57ef7dd58ab64d6114a9c520cd885e47ffb6d7d1
|
diff --git a/file/file.go b/file/file.go
index <HASH>..<HASH> 100644
--- a/file/file.go
+++ b/file/file.go
@@ -39,7 +39,7 @@ func Open(name string, growth uint64) (file *File, err error) {
return file, file.Ensure(file.Growth)
}
- if file.Buf, err = gommap.Map(file.Fh.Fd(), gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED); err != nil {
+ if file.Buf, err = gommap.Map(file.Fh, gommap.RDWR, 0); err != nil {
return
}
// find append position
@@ -73,7 +73,7 @@ func (file *File) Ensure(more uint64) (err error) {
return
}
if file.Buf != nil {
- if err = file.Buf.UnsafeUnmap(); err != nil {
+ if err = file.Buf.Unmap(); err != nil {
return
}
}
@@ -88,7 +88,7 @@ func (file *File) Ensure(more uint64) (err error) {
}
if newSize := int(file.Size + file.Growth); newSize < 0 {
log.Panicf("File %s is getting too large", file.Name)
- } else if file.Buf, err = gommap.Map(file.Fh.Fd(), gommap.PROT_READ|gommap.PROT_WRITE, gommap.MAP_SHARED); err != nil {
+ } else if file.Buf, err = gommap.Map(file.Fh, gommap.RDWR, 0); err != nil {
return
}
file.Size += file.Growth
@@ -98,12 +98,12 @@ func (file *File) Ensure(more uint64) (err error) {
// Synchronize mapped region with underlying storage device.
func (file *File) Flush() error {
- return file.Buf.Sync(gommap.MS_SYNC)
+ return file.Buf.Flush()
}
// Close the file.
func (file *File) Close() (err error) {
- if err = file.Buf.UnsafeUnmap(); err != nil {
+ if err = file.Buf.Unmap(); err != nil {
return
}
return file.Fh.Close()
|
experiment with another go mmap implementation
|
HouzuoGuo_tiedot
|
train
|
2ee5707c47e666f16a6979790b77003b67ac954c
|
diff --git a/tests/about_test.go b/tests/about_test.go
index <HASH>..<HASH> 100644
--- a/tests/about_test.go
+++ b/tests/about_test.go
@@ -16,7 +16,6 @@ package tests
import (
"encoding/json"
- "regexp"
"runtime"
"testing"
@@ -43,7 +42,7 @@ func TestAboutCommands(t *testing.T) {
stdout, _ := e.RunCommand("pulumi", "about", "--json")
var res interface{}
assert.NoError(t, json.Unmarshal([]byte(stdout), &res), "Should be valid json")
- assert.Contains(t, stdout, runtimeMajorMinor())
+ assert.Regexp(t, `Go Version\s+go\d+.\d+`, stdout)
assert.Contains(t, stdout, runtime.Compiler)
assert.Contains(t, stdout, "Failed to get information about the current stack:")
})
@@ -61,14 +60,7 @@ func TestAboutCommands(t *testing.T) {
integration.CreateBasicPulumiRepo(e)
e.SetBackend(e.LocalURL())
stdout, _ := e.RunCommand("pulumi", "about")
- assert.Contains(t, stdout, runtimeMajorMinor())
+ assert.Regexp(t, `Go Version\s+go\d+.\d+`, stdout)
assert.Contains(t, stdout, runtime.Compiler)
})
}
-
-// Given a runtime version like "go1.17.123", returns "go1.17.", trimming patch and prerelease
-// values.
-func runtimeMajorMinor() string {
- re := regexp.MustCompile(`go\d+.\d+.`)
- return re.FindString(runtime.Version())
-}
|
chore: Relax integration test and only check for a valid go version (#<I>)
|
pulumi_pulumi
|
train
|
29d97eb447820526a6c693856813e0647b48a9a1
|
diff --git a/src/argue.js b/src/argue.js
index <HASH>..<HASH> 100644
--- a/src/argue.js
+++ b/src/argue.js
@@ -64,14 +64,15 @@ function quantifierParser(begin, end) {
}
if (consumedTotal >= begin && consumedTotal <= maxNumber) {
- if (quantifierParsedArgs.length === 1) {
+ if (maxNumber === 1 && quantifierParsedArgs.length === 1) {
+ //they only wanted 1 so give it to them
parsedToArgs.push(quantifierParsedArgs[0]);
- } else if (quantifierParsedArgs.length > 1) {
- parsedToArgs.push(quantifierParsedArgs);
- } else if (begin === 0) {
+ } else if (begin === 0 && maxNumber === 1 && quantifierParsedArgs.length === 0) {
+ //optional arg just wasn't given
parsedToArgs.push(undefined);
+ } else {
+ parsedToArgs.push(quantifierParsedArgs);
}
-
return consumedTotal;
}
@@ -86,12 +87,10 @@ function quantifierParser(begin, end) {
}
function alternation(parsers) {
- var name = "";
+ var name = parsers.map(function (parser) { return parser.name; }).join(' OR ');
- name = parsers.map(function (parser) { return parser.name; }).join(' OR ');
-
- var parser = function (position, argsToParse, parsedToArgs) {
- for(var i = 0; i < parser.length; i++) {
+ var alt = function (position, argsToParse, parsedToArgs) {
+ for(var i = 0; i < parsers.length; i++) {
try {
//return on the first one to succeed
return parsers[i](position, argsToParse, parsedToArgs);
@@ -106,8 +105,8 @@ function alternation(parsers) {
name + ' at position ' + position);
};
- parser.name = name;
- return parser;
+ alt.name = name;
+ return alt;
}
var argue = function () {
diff --git a/test/argue_spec.js b/test/argue_spec.js
index <HASH>..<HASH> 100644
--- a/test/argue_spec.js
+++ b/test/argue_spec.js
@@ -677,7 +677,7 @@ describe('argue', function () {
});
it('correctly passes the argument when 1 is given', function () {
- expect(wrapped('test')).to.equal('test');
+ expect(wrapped('test')).to.eql(['test']);
});
it('correctly passes the argument when many is given', function () {
@@ -708,11 +708,11 @@ describe('argue', function () {
});
it('allows the argument to not be given', function () {
- expect(wrapped()).to.equal(undefined);
+ expect(wrapped()).to.eql([]);
});
it('correctly passes the argument when 1 is given', function () {
- expect(wrapped('test')).to.equal('test');
+ expect(wrapped('test')).to.eql(['test']);
});
it('correctly passes the argument when many is given', function () {
@@ -733,4 +733,83 @@ describe('argue', function () {
});
});
});
+
+ describe('dummy examples', function () {
+ it('publish msg with optional data', function () {
+ var publish = argue('string', 'any?', function (msg, data) {
+ return {
+ msg: msg,
+ data: data
+ };
+ });
+
+ var results = publish('email.valid', false);
+ expect(results).to.eql({
+ msg: 'email.valid',
+ data: false
+ });
+
+ results = publish('document.ready');
+ expect(results).to.eql({
+ msg: 'document.ready',
+ data: undefined
+ });
+ });
+
+ it('async action with optional options', function () {
+ var action = argue('object?', 'function', function (opts, cb) {
+ cb(opts);
+ });
+
+ action(function (opts) {
+ expect(opts).to.equal(undefined);
+ });
+
+ action({ flag: true }, function (opts) {
+ expect(opts).to.eql({ flag: true });
+ });
+ });
+
+ it('sum allowing variable args or an array', function () {
+ //NOTE: putting 'number*' first would never let the 'array' match
+ var sum = argue('array|number*', function (nums) {
+ return nums;
+ });
+
+ expect(sum(1, 2, 3)).to.eql([1, 2, 3]);
+ expect(sum([1, 2, 3, 4])).to.eql([1, 2, 3, 4]);
+ });
+
+ it('router that only needs the first arg', function () {
+ var router = argue('string', 'any*', function (url, etc) {
+ if (url === '/test') {
+ return etc[0];
+ }
+ else {
+ return etc;
+ }
+ });
+
+ expect(router('/test')).to.equal(undefined);
+ expect(router('/test', true)).to.equal(true);
+ expect(router('/another', 42, 'something', false))
+ .to.eql([42, 'something', false]);
+ });
+
+ it('map that takes any but a mapper that does not', function () {
+ //partly to get to 100 tests exactly
+ var map = argue('array', 'function', function (arr, cb) {
+ var results = []
+ for(var i = 0; i < arr.length; i++) {
+ results.push(cb(arr[i]));
+ }
+ });
+
+ expect(function () {
+ map([2, 'this', 'will', 'blow'], argue('number', function (num) {
+ return num * num;
+ }));
+ }).to.throw(Error);
+ });
+ });
});
|
filling out a few example scenario tests, not very good ones
|
copenhas_funs
|
train
|
f083411567b17c2ed213d6bda0d7a84e00626e1b
|
diff --git a/src/SocialiteManager.php b/src/SocialiteManager.php
index <HASH>..<HASH> 100644
--- a/src/SocialiteManager.php
+++ b/src/SocialiteManager.php
@@ -109,7 +109,7 @@ class SocialiteManager extends Manager implements Contracts\Factory
return $this->buildProvider(
GitlabProvider::class, $config
- );
+ )->setHost(Arr::get($config, 'host'));
}
/**
diff --git a/src/Two/GitlabProvider.php b/src/Two/GitlabProvider.php
index <HASH>..<HASH> 100644
--- a/src/Two/GitlabProvider.php
+++ b/src/Two/GitlabProvider.php
@@ -12,11 +12,29 @@ class GitlabProvider extends AbstractProvider implements ProviderInterface
protected $scopes = ['read_user'];
/**
+ * @var string
+ */
+ protected $host = 'https://gitlab.com';
+
+ /**
+ * @param string|null $host
+ * @return $this
+ */
+ public function setHost($host)
+ {
+ if (! empty($host)) {
+ $this->host = rtrim($host, '/');
+ }
+
+ return $this;
+ }
+
+ /**
* {@inheritdoc}
*/
protected function getAuthUrl($state)
{
- return $this->buildAuthUrlFromBase('https://gitlab.com/oauth/authorize', $state);
+ return $this->buildAuthUrlFromBase($this->host.'/oauth/authorize', $state);
}
/**
@@ -24,7 +42,7 @@ class GitlabProvider extends AbstractProvider implements ProviderInterface
*/
protected function getTokenUrl()
{
- return 'https://gitlab.com/oauth/token';
+ return $this->host.'/oauth/token';
}
/**
@@ -32,7 +50,7 @@ class GitlabProvider extends AbstractProvider implements ProviderInterface
*/
protected function getUserByToken($token)
{
- $userUrl = 'https://gitlab.com/api/v3/user?access_token='.$token;
+ $userUrl = $this->host.'/api/v3/user?access_token='.$token;
$response = $this->getHttpClient()->get($userUrl);
|
Added support for self hosted Gitlab instances
|
laravel_socialite
|
train
|
e0bd815f82839b15d3defd2647f37350d7f27ae4
|
diff --git a/src/stringProcessing/SentenceTokenizer.js b/src/stringProcessing/SentenceTokenizer.js
index <HASH>..<HASH> 100644
--- a/src/stringProcessing/SentenceTokenizer.js
+++ b/src/stringProcessing/SentenceTokenizer.js
@@ -97,8 +97,8 @@ export default class SentenceTokenizer {
* the smaller than sign works as expected.
* E.g. 'A sentence. < Hello world!' = ['A sentence.', '< Hello world!'].
*
- * @param {string} character the character to check.
- * @returns {boolean} whether the character is a smaller than sign ('<') or not.
+ * @param {string} character The character to check.
+ * @returns {boolean} Whether the character is a smaller than sign ('<') or not.
*/
isSmallerThanSign( character ) {
return character === "<";
@@ -160,10 +160,10 @@ export default class SentenceTokenizer {
* Tokens that represent a '<', followed by content until it enters another '<' or '>'
* gets another pass by the tokenizer.
*
- * @param {Object} token a token of type 'smaller-than-sign-content'.
- * @param {String[]} tokenSentences the current array of found sentences. Sentences may get added by this method.
- * @param {String} currentSentence the current sentence. Sentence parts may get appended by this method.
- * @returns {{tokenSentences, currentSentence}} the found sentences and the current sentence, appended when necessary.
+ * @param {Object} token A token of type 'smaller-than-sign-content'.
+ * @param {string[]} tokenSentences The current array of found sentences. Sentences may get added by this method.
+ * @param {string} currentSentence The current sentence. Sentence parts may get appended by this method.
+ * @returns {{tokenSentences, currentSentence}} The found sentences and the current sentence, appended when necessary.
*/
tokenizeSmallerThanContent( token, tokenSentences, currentSentence ) {
/*
@@ -236,9 +236,9 @@ export default class SentenceTokenizer {
/**
* Tokenizes the given text using the given tokenizer.
*
- * @param {Object} tokenizer the tokenizer to use.
- * @param {String} text the text to tokenize.
- * @returns {String[]} the tokens as retrieved from the text.
+ * @param {Object} tokenizer The tokenizer to use.
+ * @param {string} text The text to tokenize.
+ * @returns {string[]} The tokens as retrieved from the text.
*/
tokenize( tokenizer, text ) {
tokenizer.onText( text );
|
Changed some first letters in some comments to capital letters.
|
Yoast_YoastSEO.js
|
train
|
c627b59dea367979f7714bba7846f490ada5e2fa
|
diff --git a/core-bundle/contao/dca/tl_content.php b/core-bundle/contao/dca/tl_content.php
index <HASH>..<HASH> 100644
--- a/core-bundle/contao/dca/tl_content.php
+++ b/core-bundle/contao/dca/tl_content.php
@@ -803,6 +803,17 @@ class tl_content extends Backend
*/
public function checkPermission()
{
+ // Prevent deleting referenced elements (see #4898)
+ if (Input::get('act') == 'deleteAll')
+ {
+ $objCes = $this->Database->prepare("SELECT cteAlias FROM tl_content WHERE (ptable='tl_article' OR ptable='') AND type='alias'")
+ ->execute();
+
+ $session = $this->Session->getData();
+ $session['CURRENT']['IDS'] = array_diff($session['CURRENT']['IDS'], $objCes->fetchEach('cteAlias'));
+ $this->Session->setData($session);
+ }
+
if ($this->User->isAdmin)
{
return;
@@ -1081,12 +1092,12 @@ class tl_content extends Backend
return $arrAlias;
}
- $objAlias = $this->Database->prepare("SELECT c.id, c.pid, c.type, (CASE c.type WHEN 'module' THEN m.name WHEN 'form' THEN f.title WHEN 'table' THEN c.summary ELSE c.headline END) AS headline, c.text, a.title FROM tl_content c LEFT JOIN tl_article a ON a.id=c.pid LEFT JOIN tl_module m ON m.id=c.module LEFT JOIN tl_form f on f.id=c.form WHERE a.pid IN(". implode(',', array_map('intval', array_unique($arrPids))) .") AND c.id!=? ORDER BY a.title, c.sorting")
+ $objAlias = $this->Database->prepare("SELECT c.id, c.pid, c.type, (CASE c.type WHEN 'module' THEN m.name WHEN 'form' THEN f.title WHEN 'table' THEN c.summary ELSE c.headline END) AS headline, c.text, a.title FROM tl_content c LEFT JOIN tl_article a ON a.id=c.pid LEFT JOIN tl_module m ON m.id=c.module LEFT JOIN tl_form f on f.id=c.form WHERE a.pid IN(". implode(',', array_map('intval', array_unique($arrPids))) .") AND (c.ptable='tl_article' OR c.ptable='') AND c.id!=? ORDER BY a.title, c.sorting")
->execute(Input::get('id'));
}
else
{
- $objAlias = $this->Database->prepare("SELECT c.id, c.pid, c.type, (CASE c.type WHEN 'module' THEN m.name WHEN 'form' THEN f.title WHEN 'table' THEN c.summary ELSE c.headline END) AS headline, c.text, a.title FROM tl_content c LEFT JOIN tl_article a ON a.id=c.pid LEFT JOIN tl_module m ON m.id=c.module LEFT JOIN tl_form f on f.id=c.form WHERE c.id!=? ORDER BY a.title, c.sorting")
+ $objAlias = $this->Database->prepare("SELECT c.id, c.pid, c.type, (CASE c.type WHEN 'module' THEN m.name WHEN 'form' THEN f.title WHEN 'table' THEN c.summary ELSE c.headline END) AS headline, c.text, a.title FROM tl_content c LEFT JOIN tl_article a ON a.id=c.pid LEFT JOIN tl_module m ON m.id=c.module LEFT JOIN tl_form f on f.id=c.form WHERE (c.ptable='tl_article' OR c.ptable='') AND c.id!=? ORDER BY a.title, c.sorting")
->execute(Input::get('id'));
}
@@ -1447,9 +1458,9 @@ class tl_content extends Backend
*/
public function deleteElement($row, $href, $label, $title, $icon, $attributes)
{
- $objElement = $this->Database->prepare("SELECT id FROM tl_content WHERE cteAlias=? AND type=?")
+ $objElement = $this->Database->prepare("SELECT id FROM tl_content WHERE cteAlias=? AND type='alias'")
->limit(1)
- ->execute($row['id'], 'alias');
+ ->execute($row['id']);
return $objElement->numRows ? $this->generateImage(preg_replace('/\.gif$/i', '_.gif', $icon)) . ' ' : '<a href="'.$this->addToUrl($href.'&id='.$row['id']).'" title="'.specialchars($title).'"'.$attributes.'>'.$this->generateImage($icon, $label).'</a> ';
}
|
[Core] Prevent deleting referenced content elements using "edit multiple" (see #<I>)
|
contao_contao
|
train
|
5f2aedb90b142e8a9632c372b682cc998073b589
|
diff --git a/lib/podio/models/item.rb b/lib/podio/models/item.rb
index <HASH>..<HASH> 100644
--- a/lib/podio/models/item.rb
+++ b/lib/podio/models/item.rb
@@ -24,6 +24,7 @@ class Podio::Item < ActivePodio::Base
property :link, :string
property :invite, :hash
property :participants, :hash
+ property :linked_account_id, :integer
# Get items
property :comment_count, :integer
|
Added linked_account_id to the item model.
|
podio_podio-rb
|
train
|
bce886e7a59bce3808d33567acb93386a3ec320c
|
diff --git a/django_x509/base/models.py b/django_x509/base/models.py
index <HASH>..<HASH> 100644
--- a/django_x509/base/models.py
+++ b/django_x509/base/models.py
@@ -47,9 +47,15 @@ SIGNATURE_MAPPING = {
def default_validity_start():
"""
- sets validity_start field to 1 day before the current date
- (avoids "certificate not valid yet" edge case)
- intentionally returns naive datetime (not timezone aware)
+ Sets validity_start field to 1 day before the current date
+ (avoids "certificate not valid yet" edge case).
+
+ In some cases, because of timezone differences, when certificates
+ were just created they were considered valid in a timezone (eg: Europe)
+ but not yet valid in another timezone (eg: US).
+
+ This function intentionally returns naive datetime (not timezone aware),
+ so that certificates are valid from 00:00 AM in all timezones.
"""
start = datetime.now() - timedelta(days=1)
return start.replace(hour=0, minute=0, second=0, microsecond=0)
|
Improved default_validity_start() docstring
Explain why naive datetime object is used.
|
openwisp_django-x509
|
train
|
c1cf47c57f77b66402aa6f4a719d258b02c79e18
|
diff --git a/core/src/main/java/jenkins/security/ClassFilterImpl.java b/core/src/main/java/jenkins/security/ClassFilterImpl.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/jenkins/security/ClassFilterImpl.java
+++ b/core/src/main/java/jenkins/security/ClassFilterImpl.java
@@ -130,7 +130,7 @@ public class ClassFilterImpl extends ClassFilter {
return true;
}
String name = c.getName();
- if (Main.isUnitTest && name.contains("$$EnhancerByMockitoWithCGLIB$$")) {
+ if (Main.isUnitTest && (name.contains("$$EnhancerByMockitoWithCGLIB$$") || name.contains("$$FastClassByMockitoWithCGLIB$$") || name.startsWith("org.mockito."))) {
mockOff();
return false;
}
@@ -222,11 +222,11 @@ public class ClassFilterImpl extends ClassFilter {
LOGGER.log(Level.WARNING, "problem checking " + loc, x);
}
}
- if (Main.isUnitTest || Main.isDevelopmentMode) {
- if (loc.endsWith("/target/classes/")) {
- LOGGER.log(Level.FINE, "{0} seems to be current plugin classes, OK", loc);
- return true;
- }
+ if (loc.endsWith("/target/classes/")) {
+ LOGGER.log(Level.FINE, "{0} seems to be current plugin classes, OK", loc);
+ return true;
+ }
+ if (Main.isUnitTest) {
if (loc.endsWith("/target/test-classes/") || loc.endsWith("-tests.jar")) {
LOGGER.log(Level.FINE, "{0} seems to be test classes, OK", loc);
return true;
|
Some more refinements to ClassFilterImpl shutoff during development.
|
jenkinsci_jenkins
|
train
|
a935fc554473b1234f0062e2de1a4dd82c53f34d
|
diff --git a/src/app/services/mopidy.service.js b/src/app/services/mopidy.service.js
index <HASH>..<HASH> 100644
--- a/src/app/services/mopidy.service.js
+++ b/src/app/services/mopidy.service.js
@@ -313,7 +313,26 @@ angular.module('mopify.services.mopidy', [
},
next: function() {
- return wrapMopidyFunc("mopidy.playback.next", this)();
+ var self = this;
+ var deferred = $q.defer();
+
+ // Start playing when the next track gets called and te state doesn't equal play
+ self.mopidy.playback.getState().then(function(state){
+ if(state === 'playing'){
+ self.mopidy.playback.next().then(function(response){
+ deferred.resolve(response);
+ });
+ }
+ else{
+ self.mopidy.playback.play().then(function(){
+ self.mopidy.playback.next().then(function(response){
+ deferred.resolve(response);
+ });
+ });
+ }
+ });
+
+ return deferred.promise;
},
setConsume: function(){
|
Make sure the player is playing when calling next track
|
dirkgroenen_mopidy-mopify
|
train
|
c1bfbb8ed113f4757126e5ce0baa69a8bddb1d8a
|
diff --git a/cmd/example-scheduler/app/app.go b/cmd/example-scheduler/app/app.go
index <HASH>..<HASH> 100644
--- a/cmd/example-scheduler/app/app.go
+++ b/cmd/example-scheduler/app/app.go
@@ -2,7 +2,6 @@ package app
import (
"errors"
- "fmt"
"io"
"log"
"math/rand"
@@ -63,6 +62,7 @@ func Run(cfg Config) error {
func buildEventHandler(state *internalState) events.Handler {
callOptions := scheduler.CallOptions{} // should be applied to every outgoing call
return events.NewMux(
+ events.DefaultHandler(events.HandlerFunc(controller.DefaultHandler)),
events.Handle(scheduler.Event_FAILURE, events.HandlerFunc(func(e *scheduler.Event) error {
log.Println("received a FAILURE event")
f := e.GetFailure()
@@ -82,12 +82,6 @@ func buildEventHandler(state *internalState) events.Handler {
statusUpdate(state, callOptions[:], e.GetUpdate().GetStatus())
return nil
})),
- events.Handle(scheduler.Event_ERROR, events.HandlerFunc(func(e *scheduler.Event) error {
- // it's recommended that we abort and re-try subscribing; returning an
- // error here will cause the event loop to terminate and the connection
- // will be reset.
- return fmt.Errorf("ERROR: " + e.GetError().GetMessage())
- })),
events.Handle(scheduler.Event_SUBSCRIBED, events.HandlerFunc(func(e *scheduler.Event) (err error) {
log.Println("received a SUBSCRIBED event")
if state.frameworkID == "" {
@@ -102,7 +96,7 @@ func buildEventHandler(state *internalState) events.Handler {
return
})),
)
-} // buildEventHandler
+}
func failure(eid *mesos.ExecutorID, aid *mesos.AgentID, stat *int32) {
if eid != nil {
diff --git a/extras/scheduler/controller/controller.go b/extras/scheduler/controller/controller.go
index <HASH>..<HASH> 100644
--- a/extras/scheduler/controller/controller.go
+++ b/extras/scheduler/controller/controller.go
@@ -1,6 +1,8 @@
package controller
import (
+ "fmt"
+
"github.com/mesos/mesos-go"
"github.com/mesos/mesos-go/encoding"
"github.com/mesos/mesos-go/scheduler"
@@ -49,7 +51,7 @@ type (
// order to allow the framework registration process to continue. May be nil.
RegistrationTokens <-chan struct{}
- // Caller (optional) indicates a change of caller; the decorator returns the caller that will be
+ // Caller (optional) invoked upon a change of caller; the decorator returns the caller that will be
// used by the controller going forward until the next change-of-caller. May be nil.
Caller calls.Decorator
}
@@ -94,7 +96,7 @@ func (control *Controller) processSubscription(resp mesos.Response, err error) e
func (control *Controller) eventLoop(eventDecoder encoding.Decoder) (err error) {
h := control.Handler
if h == nil {
- h = events.HandlerFunc(func(*scheduler.Event) error { return nil })
+ h = events.HandlerFunc(DefaultHandler)
}
for err == nil && !control.Context.Done() {
var e scheduler.Event
@@ -121,3 +123,14 @@ func (ca *ContextAdapter) Error(err error) {
ca.ErrorFunc(err)
}
}
+
+// DefaultHandler provides the minimum implementation required for correct controller behavior.
+func DefaultHandler(e *scheduler.Event) (err error) {
+ if e.GetType() == scheduler.Event_ERROR {
+ // it's recommended that we abort and re-try subscribing; returning an
+ // error here will cause the event loop to terminate and the connection
+ // will be reset.
+ err = fmt.Errorf("ERROR: %q", e.GetError().GetMessage())
+ }
+ return
+}
|
refactor: default error handling impl as part of extras/scheduler/controller
|
mesos_mesos-go
|
train
|
e4eed5cd04d28726de47e0eb194d9ad1414ba5ca
|
diff --git a/go/vt/worker/instance.go b/go/vt/worker/instance.go
index <HASH>..<HASH> 100644
--- a/go/vt/worker/instance.go
+++ b/go/vt/worker/instance.go
@@ -92,12 +92,19 @@ func (wi *Instance) setAndStartWorker(ctx context.Context, wrk Worker, wr *wrang
if wi.currentWorker != nil {
// During the grace period, we answer with a retryable error.
+ // This way any automation can retry to issue 'Reset' and then the original
+ // command. We can end up in this situation when the automation job was
+ // restarted and therefore the previously running vtworker command was
+ // canceled.
+ // TODO(mberlin): This can be simplified when we move to a model where
+ // vtworker runs commands independent of an RPC and the automation polls for
+ // the current status, based on an assigned unique id, instead.
const gracePeriod = 1 * time.Minute
- gracePeriodEnd := time.Now().Add(gracePeriod)
- if wi.lastRunStopTime.Before(gracePeriodEnd) {
+ sinceLastStop := time.Since(wi.lastRunStopTime)
+ if sinceLastStop <= gracePeriod {
return nil, vterrors.Errorf(vtrpcpb.Code_UNAVAILABLE,
"A worker job was recently stopped (%f seconds ago): If you run commands manually, run the 'Reset' command to clear the vtworker state. Job: %v",
- time.Now().Sub(wi.lastRunStopTime).Seconds(),
+ sinceLastStop.Seconds(),
wi.currentWorker)
}
|
vtworker: Simplify calculation for grace period during which we return a retryable error.
I also tried to better document why we do this in the first place.
|
vitessio_vitess
|
train
|
1c75996e0b0bae5cc02b5ba671a72c35c15674e3
|
diff --git a/djangocms_helper/base_test.py b/djangocms_helper/base_test.py
index <HASH>..<HASH> 100644
--- a/djangocms_helper/base_test.py
+++ b/djangocms_helper/base_test.py
@@ -85,7 +85,6 @@ class BaseTestCaseMixin(object):
@classmethod
def setUpClass(cls):
from django.contrib.sites.models import Site
- super(BaseTestCaseMixin, cls).setUpClass()
cls.request_factory = RequestFactory()
cls.user = create_user(
cls._admin_user_username, cls._admin_user_email, cls._admin_user_password,
@@ -99,13 +98,14 @@ class BaseTestCaseMixin(object):
cls._user_user_username, cls._user_user_email, cls._user_user_password,
is_staff=False, is_superuser=False
)
- cls.site_1 = Site.objects.get(pk=1)
+ cls.site_1 = Site.objects.all().first()
try:
from cms.utils import get_language_list
cls.languages = get_language_list()
except ImportError:
cls.languages = [x[0] for x in settings.LANGUAGES]
+ super(BaseTestCaseMixin, cls).setUpClass()
@classmethod
def tearDownClass(cls):
@@ -170,6 +170,7 @@ class BaseTestCaseMixin(object):
def get_pages(self):
"""
Create pages using self._pages_data and self.languages
+
:return: list of created pages
"""
return self.create_pages(self._pages_data, self.languages)
|
More robust site selection logic in BaseTestCaseMixin
|
nephila_djangocms-helper
|
train
|
b482f4b691d8a6ac110a1e4f7b753535111461de
|
diff --git a/ipyvolume/embed.py b/ipyvolume/embed.py
index <HASH>..<HASH> 100644
--- a/ipyvolume/embed.py
+++ b/ipyvolume/embed.py
@@ -124,7 +124,7 @@ def add_referring_widgets(states, drop_defaults=False):
return found_new
def embed_html(filename, widgets, drop_defaults=False, all=False, title="ipyvolume embed example", external_json=False,
indent=2,
- template=template, template_options={"embed_url":"https://unpkg.com/jupyter-js-widgets@~3.0.0/dist/embed.js"},
+ template=template, template_options={"embed_url":"https://unpkg.com/jupyter-js-widgets@~3.0.0-alpha.0/dist/embed.js"},
widget_view_template=widget_view_template, **kwargs):
try:
widgets[0]
|
use jupyter-js-widget ~<I>-alpha0 for embedding
|
maartenbreddels_ipyvolume
|
train
|
04501e04a732aa60eceb8df3ccfe773e5cdab49f
|
diff --git a/tests/org/xbill/DNS/AddressTest.java b/tests/org/xbill/DNS/AddressTest.java
index <HASH>..<HASH> 100644
--- a/tests/org/xbill/DNS/AddressTest.java
+++ b/tests/org/xbill/DNS/AddressTest.java
@@ -283,7 +283,7 @@ public class AddressTest extends TestCase
public void test_getByName_invalid() throws UnknownHostException
{
try {
- Address.getByName("bogushost.com");
+ Address.getByName("example.invalid");
fail("UnknownHostException not thrown");
}
catch( UnknownHostException e ){
@@ -317,7 +317,7 @@ public class AddressTest extends TestCase
public void test_getAllByName_invalid() throws UnknownHostException
{
try {
- Address.getAllByName("bogushost.com");
+ Address.getAllByName("example.invalid");
fail("UnknownHostException not thrown");
}
catch( UnknownHostException e ){
|
Change uses of "bogushost.com" to "example.invalid", which (a) is defined
by RFC <I> to not exist, and (b) fails to resolve immediately.
git-svn-id: <URL>
|
dnsjava_dnsjava
|
train
|
7c381f9d7dc73ec30ca09356c9ae2efb9f0de883
|
diff --git a/packages/graphiql/src/utility/commonKeys.js b/packages/graphiql/src/utility/commonKeys.js
index <HASH>..<HASH> 100644
--- a/packages/graphiql/src/utility/commonKeys.js
+++ b/packages/graphiql/src/utility/commonKeys.js
@@ -1,7 +1,8 @@
+const isMacOs = window.navigator.platform === 'MacIntel';
+
const commonKeys = {
// Persistent search box in Query Editor
- 'Cmd-F': 'findPersistent',
- 'Ctrl-F': 'findPersistent',
+ [isMacOs ? 'Cmd-F' : 'Ctrl-F']: 'findPersistent',
'Cmd-G': 'findPersistent',
'Ctrl-G': 'findPersistent',
|
fix: preserve ctrl-f key for macOS
|
graphql_graphiql
|
train
|
e3d8c6422e4e8600472ff3e48e321c18db9fb4f2
|
diff --git a/test/src/Validator/IPAddressTest.php b/test/src/Validator/IPAddressTest.php
index <HASH>..<HASH> 100644
--- a/test/src/Validator/IPAddressTest.php
+++ b/test/src/Validator/IPAddressTest.php
@@ -28,26 +28,71 @@ class IPAddressTest extends \PHPUnit_Framework_TestCase {
}
+ /**
+ * Dataprovider for testValidate and testValidateBool
+ *
+ * @return array()
+ */
+ public function dataProvider() {
+ return array(
+ array(null, false),
+ array('TRUE', false),
+ array('abc', false),
+ array(1, false),
+ array('123.123.123.123', true),
+ array('2001:0db8:85a3:08d3:1319:8a2e:0370:7344', true),
+ array('2001:ghij:85a3:08d3:1319:8a2e:0370:7344', false),
+ array('123.456.789.123', false),
+ array('123.121.12.121', true),
+ array('123.1121.12.121', false),
+ array('', false)
+ );
+ }
+
/**
* @covers Wellid\Validator\IPAddress::validate
- * @todo Implement testValidate().
+ * @dataProvider dataProvider
+ * @param mixed $value
+ * @param boolean $expected
*/
- public function testValidate() {
- // Remove the following lines when you implement this test.
- $this->markTestIncomplete(
- 'This test has not been implemented yet.'
- );
+ public function testValidate($value, $expected) {
+ $result = $this->object->validate($value);
+
+ $this->assertInstanceOf('Wellid\ValidationResult', $result);
+
+ if ($expected) {
+ $this->assertTrue($result->hasPassed());
+ $this->assertFalse($result->isError());
+ $this->assertEmpty($result->getMessage());
+ $this->assertEquals(\Wellid\ValidationResult::ERR_NONE, $result->getCode());
+ $this->assertEquals('passed', (string) $result);
+ } else {
+ $this->assertFalse($result->hasPassed());
+ $this->assertTrue($result->isError());
+ $this->assertNotEmpty($result->getMessage());
+ $this->assertNotEquals(\Wellid\ValidationResult::ERR_NONE, $result->getCode());
+ $this->assertNotEquals('passed', (string) $result);
+ }
+ }
+
+ /**
+ *
+ */
+ public function testArrayAndObjectValidation() {
+ $this->assertFalse($this->object->validateBool(array(true)));
+ $x = new \stdClass();
+ $x->y = 'z';
+ $this->assertFalse($this->object->validateBool($x));
}
/**
* @covers Wellid\Validator\IPAddress::validateBool
- * @todo Implement testValidateBool().
+ * @dataProvider dataProvider
+ * @param mixed $value
+ * @param boolean $expected
*/
- public function testValidateBool() {
- // Remove the following lines when you implement this test.
- $this->markTestIncomplete(
- 'This test has not been implemented yet.'
- );
+ public function testValidateBool($value, $expected) {
+ $this->assertEquals($expected, $this->object->validateBool($value));
}
}
|
Added test for IPAddress-Validator
|
broeser_wellid
|
train
|
b276c08d3c75eb100edc7f067043a4602ff5dcad
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -105,6 +105,8 @@ CITIES_PLUGINS = [
'cities.plugin.reset_queries.Plugin', # plugin that helps to reduce memory usage when importing large datasets (e.g. "allCountries.zip")
]
```
+# Import cities without region or subregion
+CITIES_IGNORE_EMPTY_REGIONS = True
### Examples
diff --git a/cities/conf.py b/cities/conf.py
index <HASH>..<HASH> 100644
--- a/cities/conf.py
+++ b/cities/conf.py
@@ -228,3 +228,9 @@ def create_plugins():
settings = create_settings()
if hasattr(django_settings, "CITIES_PLUGINS"):
create_plugins()
+
+if hasattr(django_settings, "CITIES_IGNORE_EMPTY_REGIONS"):
+ CITIES_IGNORE_EMPTY_REGIONS = django_settings.CITIES_IGNORE_EMPTY_REGIONS
+else:
+ CITIES_IGNORE_EMPTY_REGIONS = False
+
diff --git a/cities/management/commands/cities.py b/cities/management/commands/cities.py
index <HASH>..<HASH> 100644
--- a/cities/management/commands/cities.py
+++ b/cities/management/commands/cities.py
@@ -30,13 +30,13 @@ from itertools import chain
from optparse import make_option
import django
-from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand
from django.template.defaultfilters import slugify
-from django.db import connection, transaction
+from django.db import transaction
from django.contrib.gis.gdal.envelope import Envelope
from ...conf import *
+from ...conf import CITIES_IGNORE_EMPTY_REGIONS
from ...models import *
from ...util import geo_distance
@@ -353,9 +353,13 @@ class Command(BaseCommand):
region = self.region_index[country_code + "." + region_code]
city.region = region
except:
- self.logger.warning("%s: %s: Cannot find region: %s -- skipping",
- country_code, city.name, region_code)
- continue
+ if CITIES_IGNORE_EMPTY_REGIONS:
+ city.region = None
+ else:
+ self.logger.warning("%s: %s: Cannot find region: %s -- skipping",
+ country_code, city.name, region_code)
+ continue
+
subregion_code = item['admin2Code']
try:
@@ -365,7 +369,7 @@ class Command(BaseCommand):
if subregion_code:
self.logger.warning("%s: %s: Cannot find subregion: %s -- skipping",
country_code, city.name, subregion_code)
- pass
+ continue
if not self.call_hook('city_post', city, item): continue
city.save()
|
Added possibility to import cities without region
|
coderholic_django-cities
|
train
|
e5cf718a91c0b96ffda7f175b082d6fe8f60b260
|
diff --git a/synapse/tests/test_cortex.py b/synapse/tests/test_cortex.py
index <HASH>..<HASH> 100644
--- a/synapse/tests/test_cortex.py
+++ b/synapse/tests/test_cortex.py
@@ -670,6 +670,10 @@ class CortexTest(s_test.SynTest):
self.genraises(s_exc.NoSuchOpt, core.eval, '%foo=asdf')
self.genraises(s_exc.BadOptValu, core.eval, '%limit=asdf')
+ self.genraises(s_exc.NoSuchCmpr, core.eval, 'teststr*near=newp')
+ self.genraises(s_exc.NoSuchCmpr, core.eval, 'teststr +teststr@=2018')
+ self.genraises(s_exc.NoSuchCmpr, core.eval, 'teststr +#test*near=newp')
+ self.genraises(s_exc.NoSuchCmpr, core.eval, 'teststr +teststr:tick*near=newp')
self.genraises(s_exc.BadStormSyntax, core.eval, ' | | ')
self.len(2, list(core.eval(('[ teststr=foo teststr=bar ]'))))
diff --git a/synapse/tests/test_lib_types.py b/synapse/tests/test_lib_types.py
index <HASH>..<HASH> 100644
--- a/synapse/tests/test_lib_types.py
+++ b/synapse/tests/test_lib_types.py
@@ -9,7 +9,9 @@ import synapse.datamodel as s_datamodel
class TypesTest(s_test.SynTest):
def test_type(self):
- self.skip('Implement base type test')
+ model = s_datamodel.Model()
+ t = model.type('bool')
+ self.raises(s_exc.NoSuchCmpr, t.cmpr, val1=1, name='newp', val2=0)
def test_bool(self):
model = s_datamodel.Model()
|
Add additional test coverage for noSuchCmpr
|
vertexproject_synapse
|
train
|
905011642d82272f8268c4fa93e23d4f6e581aa5
|
diff --git a/src/shared/js/ch.Popover.js b/src/shared/js/ch.Popover.js
index <HASH>..<HASH> 100644
--- a/src/shared/js/ch.Popover.js
+++ b/src/shared/js/ch.Popover.js
@@ -69,9 +69,7 @@
var $document = $(window.document),
$body = $('body'),
- /**
- * Inheritance
- */
+
parent = ch.util.inherits(Popover, ch.Widget),
openEvent = {
@@ -91,7 +89,7 @@
'classes': 'ch-box-lite',
'width': 'auto',
'height': 'auto',
- 'open': 'click', // mouseenter
+ 'open': 'click',
'close': 'button-only'
};
@@ -105,9 +103,6 @@
// Used to ARIA attributes
id = ['ch', this.name, this.uid].join('-');
- // Grab the instances map to close all sibling on show
- this._instances = ch.instances[this.name];
-
/**
* Inner function that resolves the component's layout and returns a static reference.
* @protected
@@ -126,10 +121,6 @@
'height': this._options.height
});
- this.on('hide', function () {
- that.$container.remove(null, true);
- });
-
/**
* Inner reference to content container. Here is where the content will be added.
* @protected
@@ -139,7 +130,9 @@
*/
this._$content = $('<div class="ch-popover-content">').appendTo(this.$container);
- // Add functionality to the trigger if it exists
+ /**
+ * Trigger: Add functionality to the trigger if it exists
+ */
if (this.$el !== undefined) {
// Set WAI-ARIA to the main element
@@ -158,8 +151,8 @@
this._options.reference = this.$el;
}
- // Use the "title" or "alt" attributes when a content was not defined
- if (this._options.content === undefined) {
+ if (this._options.content === undefined && (this.el.title || this.el.alt)) {
+ // Use the "title" or "alt" attributes when a content was not defined
this._options.content = this.el.title || this.el.alt;
// Keep the attributes content into the element for possible usage
this.el.setAttribute('data-title', this._options.content);
@@ -168,7 +161,9 @@
}
}
- // Configure Content
+ /**
+ * Configure abilities
+ */
this.content.configure({
'input': this._options.content,
'method': this._options.method,
@@ -189,10 +184,8 @@
that.position.refresh();
};
- // Configure Closable
this._closable();
- // Configure Positioner
this.position = new ch.Positioner({
'target': this.$container,
'reference': this._options.reference,
@@ -202,11 +195,18 @@
'offsetY': this._options.offsetY
});
+ /**
+ * Bind behaviors
+ */
$document.on(ch.events.layout.CHANGE, function () {
if (that._active) {
that.position.refresh();
}
});
+
+ this.on('hide', function () {
+ that.$container.remove(null, true);
+ });
};
/**
@@ -222,7 +222,9 @@
// Open the collapsible
this._show();
// Request the content
- this.content.set({'input': content});
+ this.content.set({
+ 'input': content
+ });
return this;
};
@@ -235,7 +237,9 @@
* @returns itself
*/
Popover.prototype.hide = function () {
+
this._hide();
+
return this;
};
|
GH-<I> Popover: Don't reset the title nor alt attributes if it don't exists on the trigger.
|
mercadolibre_chico
|
train
|
900dd575cbbb437bb00414afd28037726179ba8c
|
diff --git a/src/Mandango/Behavior/Sluggable.php b/src/Mandango/Behavior/Sluggable.php
index <HASH>..<HASH> 100644
--- a/src/Mandango/Behavior/Sluggable.php
+++ b/src/Mandango/Behavior/Sluggable.php
@@ -100,8 +100,8 @@ EOF
);
$this->definitions['document_base']->addMethod($method);
- // repository ->findBySlug()
- $method = new Method('public', 'findBySlug', '$slug', <<<EOF
+ // repository ->findOneBySlug()
+ $method = new Method('public', 'findOneBySlug', '$slug', <<<EOF
return \$this->createQuery(array('$slugField' => \$slug))->one();
EOF
);
diff --git a/tests/Mandango/Tests/Behavior/SluggableTest.php b/tests/Mandango/Tests/Behavior/SluggableTest.php
index <HASH>..<HASH> 100644
--- a/tests/Mandango/Tests/Behavior/SluggableTest.php
+++ b/tests/Mandango/Tests/Behavior/SluggableTest.php
@@ -32,7 +32,7 @@ class SluggableTest extends TestCase
$this->assertSame('testing-sluggable-extension-2', $documents[2]->getSlug());
}
- public function testRepositoryFindBySlug()
+ public function testRepositoryFindOneBySlug()
{
$documents = array();
for ($i = 0; $i < 9; $i++) {
@@ -43,7 +43,7 @@ class SluggableTest extends TestCase
$repository = $this->mandango->getRepository('Model\Sluggable');
- $this->assertSame($documents[3], $repository->findBySlug($documents[3]->getSlug()));
- $this->assertSame($documents[6], $repository->findBySlug($documents[6]->getSlug()));
+ $this->assertSame($documents[3], $repository->findOneBySlug($documents[3]->getSlug()));
+ $this->assertSame($documents[6], $repository->findOneBySlug($documents[6]->getSlug()));
}
}
|
[Sluggable] changed ->fineBySlug() by ->findOneBySlug()
|
mongator_behaviors
|
train
|
eead0815f5f9474331263ad2c70e48352c2113e7
|
diff --git a/source/org/jasig/portal/UserLayoutManager.java b/source/org/jasig/portal/UserLayoutManager.java
index <HASH>..<HASH> 100644
--- a/source/org/jasig/portal/UserLayoutManager.java
+++ b/source/org/jasig/portal/UserLayoutManager.java
@@ -103,6 +103,7 @@ public class UserLayoutManager {
// determine the default user
this.person=new org.jasig.portal.security.provider.PersonImpl();
this.person.setID(guestId);
+ this.person.setFullName("Guest");
}
// load user preferences
|
in constructing guest IPerson object (which shouldn't be done here anyway),
UserLayoutManager now sets full name to "Guest". (needed for the header chan.)
git-svn-id: <URL>
|
Jasig_uPortal
|
train
|
0739a4046099fdb4babdf121f0f7baa4dc279505
|
diff --git a/satpy/readers/fci_l1c_fdhsi.py b/satpy/readers/fci_l1c_fdhsi.py
index <HASH>..<HASH> 100644
--- a/satpy/readers/fci_l1c_fdhsi.py
+++ b/satpy/readers/fci_l1c_fdhsi.py
@@ -46,6 +46,39 @@ Imager (FCI) Full Disk High Spectral Imagery (FDHSI) data. FCI will fly
on the MTG Imager (MTG-I) series of satellites, scheduled to be launched
in 2021 by the earliest. For more information about FCI, see `EUMETSAT`_.
+Geolocation is based on a combination of information from the Product User
+Guide (`PUG`_) and from the data files. It uses:
+
+ * Extent information from the PUG for the three different possible
+ resolutions. In the PUG dated 2019-06-27 (EUM/MTG/USR/13/719113),
+ this is Table 3.
+ * From the shape of the data variable ``data/<channel>/measured/effective_radiance``,
+ start and end line columns of current swath.
+ * From the data variable ``data/<channel>/measured/x``, the x-coordinates
+ for the grid, in radians
+ * From the data variable ``data/<channel>/measured/y``, the y-coordinates
+ for the grid, in radians
+ * From the attribute ``semi_major_axis`` on the data variable
+ ``data/mtg_geos_projection``, the Earth equatorial radius
+ * From the attribute ``semi_minor_axis`` on the same, the Earth polar
+ radius
+ * From the attribute ``perspective_point_height`` on the same data
+ variable, the geostationary altitude in the normalised geostationary
+ projection (see PUG §5.2)
+ * From the attribute ``longitude_of_projection_origin`` on the same
+ data variable, the longitude of the projection origin
+ * From the attribute ``sweep_angle_axis`` on the same, the sweep angle
+ axis, see https://proj.org/operations/projections/geos.html
+
+From the pixel centre angles in radians and the geostationary altitude, the
+extremities of the lower left and upper right corners are calculated in units
+of arc length in m. This extent along with the number of columns and rows, the
+sweep angle axis, and a dictionary with equatorial radius, polar radius,
+geostationary altitude, and longitude of projection origin, are passed on to
+``pyresample.geometry.AreaDefinition``, which then uses proj4 for the actual
+geolocation calculations.
+
+.. _PUG: http://www.eumetsat.int/website/wcm/idc/idcplg?IdcService=GET_FILE&dDocName=PDF_DMT_719113&RevisionSelectionMethod=LatestReleased&Rendition=Web
.. _EUMETSAT: https://www.eumetsat.int/website/home/Satellites/FutureSatellites/MeteosatThirdGeneration/MTGDesign/index.html#fci # noqa: E501
"""
@@ -154,7 +187,7 @@ class FCIFDHSIFileHandler(NetCDF4FileHandler):
C"""
# Calculate the area extent of the swath based on start line and column
# information, total number of segments and channel resolution
- # numbers from Package Description, Table 8
+ # numbers from PUG, Table 3
xyres = {500: 22272, 1000: 11136, 2000: 5568}
chkres = xyres[key.resolution]
|
DOC: Added info on how geolocation is done
Added to the reader module docstring information on how the geolocation
is performed.
|
pytroll_satpy
|
train
|
9ad01fdfcf34e5367e9b8e44b2d4405970be705d
|
diff --git a/Middleware/EnsureEmailIsVerified.php b/Middleware/EnsureEmailIsVerified.php
index <HASH>..<HASH> 100644
--- a/Middleware/EnsureEmailIsVerified.php
+++ b/Middleware/EnsureEmailIsVerified.php
@@ -23,7 +23,7 @@ class EnsureEmailIsVerified
! $request->user()->hasVerifiedEmail())) {
return $request->expectsJson()
? abort(403, 'Your email address is not verified.')
- : Redirect::route($redirectToRoute ?: 'verification.notice');
+ : Redirect::guest(route($redirectToRoute ?: 'verification.notice'));
}
return $next($request);
|
Set intended URL before email verification (#<I>)
|
illuminate_auth
|
train
|
1d26f05b87cdb3ab678eb5c0b4741a07b6aff41c
|
diff --git a/src/com/google/javascript/jscomp/Es6RewriteArrowFunction.java b/src/com/google/javascript/jscomp/Es6RewriteArrowFunction.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/Es6RewriteArrowFunction.java
+++ b/src/com/google/javascript/jscomp/Es6RewriteArrowFunction.java
@@ -20,10 +20,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import com.google.javascript.jscomp.parsing.parser.FeatureSet;
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
import com.google.javascript.rhino.IR;
-import com.google.javascript.rhino.JSDocInfoBuilder;
-import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
-import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.jstype.JSType;
import java.util.ArrayDeque;
import java.util.Deque;
@@ -153,13 +150,7 @@ public class Es6RewriteArrowFunction implements NodeTraversal.Callback, HotSwapC
NodeUtil.addFeatureToScript(t.getCurrentScript(), Feature.CONST_DECLARATIONS);
scopeBody.addChildToFront(argumentsVar);
- JSDocInfoBuilder jsdoc = new JSDocInfoBuilder(false);
- jsdoc.recordType(
- new JSTypeExpression(
- new Node(Token.BANG, IR.string("Arguments")), "<Es6RewriteArrowFunction>"));
- argumentsVar.setJSDocInfo(jsdoc.build());
argumentsVar.useSourceInfoIfMissingFromForTree(scopeBody);
-
compiler.reportChangeToEnclosingScope(argumentsVar);
}
}
diff --git a/test/com/google/javascript/jscomp/Es6RewriteArrowFunctionTest.java b/test/com/google/javascript/jscomp/Es6RewriteArrowFunctionTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/Es6RewriteArrowFunctionTest.java
+++ b/test/com/google/javascript/jscomp/Es6RewriteArrowFunctionTest.java
@@ -174,7 +174,6 @@ public class Es6RewriteArrowFunctionTest extends CompilerTestCase {
"}"),
lines(
"function f() {",
- " /** @type {!Arguments} */",
" const $jscomp$arguments = arguments;",
" var x = function() { return $jscomp$arguments; };",
"}"));
|
Stop adding @type info in Es6RewriteArrowFunctions now that it's post-typechecking
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
f3acae6eb6fb09a424f9a03870631f492164e6b9
|
diff --git a/python/ray/autoscaler/_private/command_runner.py b/python/ray/autoscaler/_private/command_runner.py
index <HASH>..<HASH> 100644
--- a/python/ray/autoscaler/_private/command_runner.py
+++ b/python/ray/autoscaler/_private/command_runner.py
@@ -779,7 +779,8 @@ class DockerCommandRunner(CommandRunnerInterface):
"differ from those on the running container.")
return re_init_required
- def run_init(self, *, as_head, file_mounts, sync_run_yet):
+ def run_init(self, *, as_head: bool, file_mounts: Dict[str, str],
+ sync_run_yet: bool):
BOOTSTRAP_MOUNTS = [
"~/ray_bootstrap_config.yaml", "~/ray_bootstrap_key.pem"
]
@@ -820,6 +821,12 @@ class DockerCommandRunner(CommandRunnerInterface):
run_env="host")
if (not container_running) or requires_re_init:
+ if not sync_run_yet:
+ # Do not start the actual image as we need to run file_sync
+ # first to ensure that all folders are created with the
+ # correct ownership. Docker will create the folders with
+ # `root` as the owner.
+ return True
# Get home directory
image_env = self.ssh_command_runner.run(
f"{self.docker_cmd} " + "inspect -f '{{json .Config.Env}}' " +
diff --git a/python/ray/autoscaler/command_runner.py b/python/ray/autoscaler/command_runner.py
index <HASH>..<HASH> 100644
--- a/python/ray/autoscaler/command_runner.py
+++ b/python/ray/autoscaler/command_runner.py
@@ -85,6 +85,6 @@ class CommandRunnerInterface:
sync_run_yet (bool): Whether sync has been run yet.
Returns:
- optional (bool): Whether initialization was run.
+ optional (bool): Whether initialization is necessary.
"""
pass
diff --git a/python/ray/tests/test_autoscaler.py b/python/ray/tests/test_autoscaler.py
index <HASH>..<HASH> 100644
--- a/python/ray/tests/test_autoscaler.py
+++ b/python/ray/tests/test_autoscaler.py
@@ -828,6 +828,10 @@ class AutoscalingTest(unittest.TestCase):
x for x in commands_with_mount if "docker cp" in x[1]
]
first_mkdir = min(x[0] for x in commands_with_mount if "mkdir" in x[1])
+ docker_run_cmd_indx = [
+ i for i, cmd in enumerate(runner.command_history())
+ if "docker run" in cmd
+ ][0]
for file_to_check in [
"ray_bootstrap_config.yaml", "ray_bootstrap_key.pem"
]:
@@ -835,7 +839,12 @@ class AutoscalingTest(unittest.TestCase):
if "ray_bootstrap_config.yaml" in x[1])
first_cp = min(
x[0] for x in docker_cp_commands if file_to_check in x[1])
+ # Ensures that `mkdir -p` precedes `docker run` because Docker
+ # will auto-create the folder with wrong permissions.
+ assert first_mkdir < docker_run_cmd_indx
+ # Ensures that the folder is created before running rsync.
assert first_mkdir < first_rsync
+ # Checks that the file is present before copying into the container
assert first_rsync < first_cp
def testGetOrCreateHeadNodeFromStoppedRestartOnly(self):
@@ -2392,6 +2401,15 @@ class AutoscalingTest(unittest.TestCase):
runner.assert_has_call("172.0.0.0", "start_ray_worker")
runner.assert_has_call("172.0.0.0", "docker run")
+ docker_run_cmd_indx = [
+ i for i, cmd in enumerate(runner.command_history())
+ if "docker run" in cmd
+ ][0]
+ mkdir_cmd_indx = [
+ i for i, cmd in enumerate(runner.command_history())
+ if "mkdir -p" in cmd
+ ][0]
+ assert mkdir_cmd_indx < docker_run_cmd_indx
runner.clear_history()
autoscaler.update()
runner.assert_not_has_call("172.0.0.0", "setup_cmd")
|
[Autoscaler] Sync Files before Starting Docker (#<I>)
|
ray-project_ray
|
train
|
f70c4c5f46ff1309f5e9c8b9db6b12763791e7cb
|
diff --git a/resources/views/adminarea/pages/tenant.blade.php b/resources/views/adminarea/pages/tenant.blade.php
index <HASH>..<HASH> 100644
--- a/resources/views/adminarea/pages/tenant.blade.php
+++ b/resources/views/adminarea/pages/tenant.blade.php
@@ -301,7 +301,8 @@
<span class="input-group-btn">
<span class="btn btn-default btn-file">
{{ trans('cortex/tenants::common.browse') }}
- {{ Form::file('profile_picture', ['class' => 'form-control', 'id' => 'profile_picture_browse']) }}
+ {{-- Skip Javascrip validation for file input fields to avoid size validation conflict with jquery.validator --}}
+ {{ Form::file('profile_picture', ['class' => 'form-control skip-validation', 'id' => 'profile_picture_browse']) }}
</span>
</span>
</div>
@@ -336,7 +337,8 @@
<span class="input-group-btn">
<span class="btn btn-default btn-file">
{{ trans('cortex/tenants::common.browse') }}
- {{ Form::file('cover_photo', ['class' => 'form-control', 'id' => 'cover_photo_browse']) }}
+ {{-- Skip Javascrip validation for file input fields to avoid size validation conflict with jquery.validator --}}
+ {{ Form::file('cover_photo', ['class' => 'form-control skip-validation', 'id' => 'cover_photo_browse']) }}
</span>
</span>
</div>
|
Skip Javascrip validation for file input fields to avoid size validation conflict with jquery.validator
|
rinvex_cortex-tenants
|
train
|
549b58169de8e79f3fdb0977fde146e3496ded2e
|
diff --git a/packages/react/src/components/Button/Button-story.js b/packages/react/src/components/Button/Button-story.js
index <HASH>..<HASH> 100644
--- a/packages/react/src/components/Button/Button-story.js
+++ b/packages/react/src/components/Button/Button-story.js
@@ -19,7 +19,7 @@ const { prefix } = settings;
const icons = {
None: 'None',
- 'Add with filled circle (Add16 from `@carbon/icons-react`)': 'Add16',
+ 'Add (Add16 from `@carbon/icons-react`)': 'Add16',
'Search (Search16 from `@carbon/icons-react`)': 'Search16',
};
|
docs(button): Update Button-story.js (#<I>)
corrects icon description in the Button story
|
carbon-design-system_carbon-components
|
train
|
7c4877a57b44cea31118f906a83668d718d19c11
|
diff --git a/generator/src/DocPage.php b/generator/src/DocPage.php
index <HASH>..<HASH> 100644
--- a/generator/src/DocPage.php
+++ b/generator/src/DocPage.php
@@ -124,6 +124,9 @@ class DocPage
if (preg_match('/&null;\s+on\s+failure/', $file)) {
return true;
}
+ if (preg_match('/&null;\s+if\s+an\s+error\s+occurs/', $file)) {
+ return true;
+ }
return false;
}
|
added more cases fro nullsy functions
|
thecodingmachine_safe
|
train
|
ecbb8640f5934831d086172676f3bab29a9c32a4
|
diff --git a/ryu/base/app_manager.py b/ryu/base/app_manager.py
index <HASH>..<HASH> 100644
--- a/ryu/base/app_manager.py
+++ b/ryu/base/app_manager.py
@@ -31,6 +31,7 @@ import os
from ryu import cfg
from ryu import utils
+from ryu.app import wsgi
from ryu.controller.handler import register_instance, get_dependent_services
from ryu.controller.controller import Datapath
from ryu.controller import event
@@ -326,6 +327,25 @@ class AppManager(object):
_instance = None
@staticmethod
+ def run_apps(app_lists):
+ """Run a set of Ryu applications
+
+ A convenient method to load and instantiate apps.
+ This blocks until all relevant apps stop.
+ """
+ app_mgr = AppManager.get_instance()
+ app_mgr.load_apps(app_lists)
+ contexts = app_mgr.create_contexts()
+ services = app_mgr.instantiate_apps(**contexts)
+ webapp = wsgi.start_service(app_mgr)
+ if webapp:
+ services.append(hub.spawn(webapp))
+ try:
+ hub.joinall(services)
+ finally:
+ app_mgr.close()
+
+ @staticmethod
def get_instance():
if not AppManager._instance:
AppManager._instance = AppManager()
|
AppManager: Add a convenient method to run apps
|
osrg_ryu
|
train
|
6f8a7d393d99d652e1aabc9c43627a18d5125143
|
diff --git a/lib/weblib.php b/lib/weblib.php
index <HASH>..<HASH> 100644
--- a/lib/weblib.php
+++ b/lib/weblib.php
@@ -2526,7 +2526,10 @@ function print_header ($title='', $heading='', $navigation='', $focus='',
$htmlEditorObject = new htmlEditor();
$htmlEditor = $htmlEditorObject->configure(NULL, $COURSE->id);
+ ob_start();
include($CFG->header);
+ $output = ob_get_contents();
+ ob_end_clean();
// container debugging info
$THEME->open_header_containers = open_containers();
|
MDL-<I>: Reverting removal of output buffering.
|
moodle_moodle
|
train
|
567fabbbc624c8dab135c1b104fbc148e2063758
|
diff --git a/test/rails_app/config/application.rb b/test/rails_app/config/application.rb
index <HASH>..<HASH> 100644
--- a/test/rails_app/config/application.rb
+++ b/test/rails_app/config/application.rb
@@ -32,6 +32,9 @@ module RailsApp
config.action_mailer.default_url_options = { :host => "localhost:3000" }
+ # Disable forcing whitelist attributes from protected attributes.
+ config.active_record.whitelist_attributes = false
+
# This was used to break devise in some situations
config.to_prepare do
Devise::SessionsController.layout "application"
|
Disable forcing whitelist attributes from protected attributes
This was the previous functionality since we didn't set anything in the
application configuration. Now when using protected attributes gem, it
sets whitelist to true, forcing us to always declare the accessible
attributes, and this is not the case for the Admin model.
|
plataformatec_devise
|
train
|
6f6045bf085b64863a568fc3b4bb88ceb886203d
|
diff --git a/PROTOCOLS.md b/PROTOCOLS.md
index <HASH>..<HASH> 100644
--- a/PROTOCOLS.md
+++ b/PROTOCOLS.md
@@ -62,12 +62,30 @@
### 9. Jump to slide
{
"service" : 9,
- "data" : slide_number
+ "data" : {
+ "slide" : slide_number
+ }
+ }
+
+### 10. User dump
+ {
+ "service" : 10,
+ "data" : {
+ user property name : user value
+ }
+ }
+
+### 11. Users dump
+ {
+ "service" : 11,
+ "data" : {
+ user =[user property name : user value]
+ }
}
### 999. Error
{
- "service" : 999
+ "service" : 999,
"data" : {
"code" : error_code,
"message" : "error_message"
@@ -127,11 +145,29 @@
### 7. Jump to slide
{
"request" : 7,
- "data" : slide_number
+ "data" : {
+ "slide" : slide_number
+ }
+ }
+### 8. Get user dump
+ {
+ "request" : 8,
+ "data" : {
+ "name" : "user name"
+ }
+ }
+### 9. Get users dump
+ {
+ "request" : 9,
+ "data" : {
+ "room" : "room_name"
+ }
}
### 112. Change name
{
"request" : 112,
- "data" : "new name"
+ "data" : {
+ "name" : "new name"
+ }
}
\ No newline at end of file
diff --git a/pychatjs/server/protocol.py b/pychatjs/server/protocol.py
index <HASH>..<HASH> 100644
--- a/pychatjs/server/protocol.py
+++ b/pychatjs/server/protocol.py
@@ -9,6 +9,8 @@ requests = {0 : 'join',
5 : 'next_slide',
6 : 'previous_slide',
7 : 'jump_to_slide',
+ 8 : 'get_user_dump',
+ 9 : 'get_users_dump',
112 : 'change_name'}
def create_message(username, message):
@@ -62,6 +64,12 @@ def create_error(error_code, error_message):
error_message = error_message.replace('\n', '<br/>')
return dumps({ 'service': 999, 'data' : {'message' : error_message, 'code' : error_code}})
+def create_user_dump(user):
+ return dumps({ 'service' : 10, 'data' : user._to_json()})
+
+def create_user_dumps(users):
+ return dumps({ 'service' : 11, 'data' : [user._to_json() for user in users]})
+
services = {1 : create_message,
2 : create_pong,
3 : create_userlist,
@@ -71,6 +79,7 @@ services = {1 : create_message,
7 : create_next_slide,
8 : create_previous_slide,
9 : create_jump_to,
+ 10 : create_user_dump,
999 : create_error}
def __test():
diff --git a/pychatjs/server/run_server.py b/pychatjs/server/run_server.py
index <HASH>..<HASH> 100644
--- a/pychatjs/server/run_server.py
+++ b/pychatjs/server/run_server.py
@@ -23,7 +23,6 @@ rooms = [Room('Darkness')]
# anything can be used, however this format allows for easy debugging.
usernames = ['Shauna', 'Tomuel', 'Darkok', 'Endl', 'Frumo']
-
user_server = UserServer(usernames[:])
|
updating the protocols to support user dumps
|
eeue56_PyChat.js
|
train
|
0eea8ea0a0af056ef15ad8c0fc200a43494ffce0
|
diff --git a/src/Illuminate/Foundation/Testing/CrawlerTrait.php b/src/Illuminate/Foundation/Testing/CrawlerTrait.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Foundation/Testing/CrawlerTrait.php
+++ b/src/Illuminate/Foundation/Testing/CrawlerTrait.php
@@ -2,6 +2,7 @@
namespace Illuminate\Foundation\Testing;
+use Exception;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use InvalidArgumentException;
@@ -663,6 +664,52 @@ trait CrawlerTrait
}
/**
+ * Assert that an input field contains the given value.
+ *
+ * @param string $selector
+ * @param string $expected
+ * @return $this
+ */
+ public function seeInField($selector, $expected)
+ {
+ $this->assertSame(
+ $this->getInputOrTextareaValue($selector),
+ $expected,
+ "The input [{$selector}] has not the value [{$expected}]."
+ );
+
+ return $this;
+ }
+
+ /**
+ * Get an input or textarea value.
+ *
+ * @param string $selector
+ * @return string
+ * @throws Exception
+ */
+ protected function getInputOrTextareaValue($selector)
+ {
+ $field = $this->filterByNameOrId($selector);
+
+ if ($field->count() == 0) {
+ throw new Exception("There are no elements with the name or ID [$selector]");
+ }
+
+ $element = $field->nodeName();
+
+ if ($element == 'input') {
+ return $field->attr('value');
+ }
+
+ if ($element == 'textarea') {
+ return $field->text();
+ }
+
+ throw new Exception("[$selector] is neither an input nor a textarea");
+ }
+
+ /**
* Assert that a filtered Crawler returns nodes.
*
* @param string $filter
diff --git a/tests/Foundation/FoundationCrawlerTraitTest.php b/tests/Foundation/FoundationCrawlerTraitTest.php
index <HASH>..<HASH> 100644
--- a/tests/Foundation/FoundationCrawlerTraitTest.php
+++ b/tests/Foundation/FoundationCrawlerTraitTest.php
@@ -12,6 +12,63 @@ class FoundationCrawlerTraitTest extends PHPUnit_Framework_TestCase
m::close();
}
+ public function testSeeInFieldInput()
+ {
+ $input = m::mock(Crawler::class)->makePartial();
+ $input->shouldReceive('count')->andReturn(1);
+ $input->shouldReceive('nodeName')->once()->andReturn('input');
+ $input->shouldReceive('attr')
+ ->withArgs(['value'])
+ ->once()
+ ->andReturn('Laravel');
+
+ $this->crawler = m::mock(Crawler::class)->makePartial();
+
+ $this->crawler->shouldReceive('filter')
+ ->withArgs(["*#framework, *[name='framework']"])
+ ->once()
+ ->andReturn($input);
+
+ $this->seeInField('framework', 'Laravel');
+ }
+
+ public function testSeeInFieldTextarea()
+ {
+ $textarea = m::mock(Crawler::class)->makePartial();
+ $textarea->shouldReceive('count')->andReturn(1);
+ $textarea->shouldReceive('nodeName')->once()->andReturn('textarea');
+ $textarea->shouldReceive('text')->once()->andReturn('Laravel is awesome');
+
+ $this->crawler = m::mock(Crawler::class)->makePartial();
+
+ $this->crawler->shouldReceive('filter')
+ ->withArgs(["*#description, *[name='description']"])
+ ->once()
+ ->andReturn($textarea);
+
+ $this->seeInField('description', 'Laravel is awesome');
+ }
+
+ /**
+ * @expectedException Exception
+ * @expectedExceptionMessage [select] is neither an input nor a textarea
+ */
+ public function testSeeInFieldWrongElementException()
+ {
+ $select = m::mock(Crawler::class)->makePartial();
+ $select->shouldReceive('count')->andReturn(1);
+ $select->shouldReceive('nodeName')->once()->andReturn('select');
+
+ $this->crawler = m::mock(Crawler::class)->makePartial();
+
+ $this->crawler->shouldReceive('filter')
+ ->withArgs(["*#select, *[name='select']"])
+ ->once()
+ ->andReturn($select);
+
+ $this->seeInField('select', 'selected_value');
+ }
+
public function testExtractsRequestParametersFromForm()
{
$form = m::mock('\Symfony\Component\DomCrawler\Form');
|
Integration tests: seeInField method proposal
|
laravel_framework
|
train
|
3c4f343615399669449a57d1915ea7cd2c7f0bff
|
diff --git a/src/VersionedGridFieldStateExtension.php b/src/VersionedGridFieldStateExtension.php
index <HASH>..<HASH> 100644
--- a/src/VersionedGridFieldStateExtension.php
+++ b/src/VersionedGridFieldStateExtension.php
@@ -15,6 +15,8 @@ class VersionedGridFieldStateExtension extends Extension
{
/** @var GridFieldConfig $owner */
$owner = $this->getOwner();
- $owner->addComponent(new VersionedGridFieldState());
+ if (!$owner->getComponentByType(VersionedGridFieldState::class)) {
+ $owner->addComponent(new VersionedGridFieldState());
+ }
}
}
|
Prevent two VersionedGridFieldState being added by the extension
|
silverstripe_silverstripe-versioned
|
train
|
c6c44fdf2fa3fc77d5e713e51b6dd19eec8146a6
|
diff --git a/www/src/libs/random.js b/www/src/libs/random.js
index <HASH>..<HASH> 100644
--- a/www/src/libs/random.js
+++ b/www/src/libs/random.js
@@ -392,6 +392,11 @@ Random.choices = function(){
}else if(cum_weights !== _b_.None){
throw _b_.TypeError.$factory("Cannot specify both weights and " +
"cumulative weights")
+ }else{
+ if(weights.length != population.length){
+ throw _b_.ValueError.$factory('The number of weights does not ' +
+ 'match the population')
+ }
}
if(cum_weights === _b_.None){
var cum_weights = [weights[0]]
@@ -400,7 +405,11 @@ Random.choices = function(){
cum_weights.push(cum_weights[rank - 1] + weight)
}
})
+ }else if(cum_weights.length != population.length){
+ throw _b_.ValueError.$factory('The number of weights does not ' +
+ 'match the population')
}
+
var result = []
for(var i = 0; i < k; i++){
var rand = Math.random() * cum_weights[cum_weights.length - 1]
|
Improvement to random.choices : test that length of weights or cum_weights is the same as length of population
|
brython-dev_brython
|
train
|
7a6861fb251b63727ae8702e32c223376b5c85b0
|
diff --git a/native_tags/nodes.py b/native_tags/nodes.py
index <HASH>..<HASH> 100644
--- a/native_tags/nodes.py
+++ b/native_tags/nodes.py
@@ -7,8 +7,13 @@ from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe
from registry import register
+class Constant(unicode):
+ """Just a placeholder unicode constant so you can tell
+ which variables failed lookup and should be considered constant.
+ You can tell by using ``isinstance(var_or_constant, Constant)``"""
+ pass
-def lookup(var, context, resolve=True):
+def lookup(parser, var, context, resolve=True, apply_filters=True):
"""
Try to resolve the varialbe in a context
If ``resolve`` is ``False``, only string variables are returned
@@ -17,7 +22,9 @@ def lookup(var, context, resolve=True):
try:
return Variable(var).resolve(context)
except VariableDoesNotExist:
- pass
+ if apply_filters and var.find('|') > -1:
+ return parser.compile_filter(var).resolve(context)
+ return Constant(force_unicode(var))
except TypeError:
# already resolved
return var
@@ -51,7 +58,8 @@ def get_signature(token, contextable=False, comparison=False):
class NativeNode(template.Node):
bucket = None
- def __init__(self, name, *args, **kwargs):
+ def __init__(self, parser, name, *args, **kwargs):
+ self.parser = parser
self.func = register[self.bucket][name]
self.name = name
self.args = args
@@ -61,10 +69,13 @@ class NativeNode(template.Node):
resolve = True
if hasattr(self.func, 'resolve'):
resolve = getattr(self.func, 'resolve')
- self.args = (lookup(var, context, resolve) for var in self.args)
+ apply_filters = True
+ if hasattr(self.func, 'apply_filters'):
+ apply_filters = getattr(self.func, 'apply_filters')
+ self.args = (lookup(self.parser, var, context, resolve) for var in self.args)
if hasattr(self.func, 'takes_context') and getattr(self.func, 'takes_context'):
self.args = (context,) + tuple(self.args)
- self.kwargs = dict(((k, lookup(var, context, resolve)) for k, var in self.kwargs.items()))
+ self.kwargs = dict(((k, lookup(self.parser, var, context, resolve)) for k, var in self.kwargs.items()))
varname = self.kwargs.pop('varname', None)
result = self.get_result(context)
@@ -135,6 +146,7 @@ def do_comparison(parser, token):
"""
name, args, kwargs = get_signature(token, comparison=True)
+ name = name.replace('if_if', 'if')
end_tag = 'end' + name
kwargs['nodelist_true'] = parser.parse(('else', end_tag))
token = parser.next_token()
@@ -143,7 +155,9 @@ def do_comparison(parser, token):
parser.delete_first_token()
else:
kwargs['nodelist_false'] = template.NodeList()
- return ComparisonNode(name.split('if_')[1], *args, **kwargs)
+ if name.startswith('if_'):
+ name = name.split('if_')[1]
+ return ComparisonNode(parser, name, *args, **kwargs)
class FunctionNode(NativeNode):
bucket = 'function'
@@ -174,7 +188,7 @@ def do_function(parser, token):
"""
name, args, kwargs = get_signature(token, True, True)
- return FunctionNode(name, *args, **kwargs)
+ return FunctionNode(parser, name, *args, **kwargs)
class BlockNode(NativeNode):
bucket = 'block'
@@ -207,4 +221,4 @@ def do_block(parser, token):
name, args, kwargs = get_signature(token, contextable=True)
kwargs['nodelist'] = parser.parse(('end%s' % name,))
parser.delete_first_token()
- return BlockNode(name, *args, **kwargs)
+ return BlockNode(parser, name, *args, **kwargs)
|
fixes for filter expressions and comparisons that you want to start with if
|
justquick_django-native-tags
|
train
|
785acc967f4184441e1faf3c5db59c79ad0b0819
|
diff --git a/pymbar/mbar.py b/pymbar/mbar.py
index <HASH>..<HASH> 100644
--- a/pymbar/mbar.py
+++ b/pymbar/mbar.py
@@ -846,7 +846,7 @@ class MBAR:
dims = len(np.shape(A_n))
if dims > 2:
- print("expecting dim=2 (state_dependent=True) or dim=1 for (state_dependent=False) observables")
+ print("Warning: dim=3 for (state_dependent==True) matrices for observables and dim=2 for (state_dependent==False) observables are deprecated; we suggest you convert to NxK form instead of NxKxK form.")
if not state_dependent:
if dims==2:
|
changes to warning to make clear what is deprecated.
Changed the computExpectations warning to make it clearer
that NxKxK format is deprecated.
|
choderalab_pymbar
|
train
|
e732f2bbef2b24d6a9de42c2e14f6c90530aea69
|
diff --git a/src/Cognos.js b/src/Cognos.js
index <HASH>..<HASH> 100644
--- a/src/Cognos.js
+++ b/src/Cognos.js
@@ -748,7 +748,7 @@ class Cognos {
if (id) {
result = me.requester
.put('bi/v1/palettes/' + id, false, palette)
- .then(function(data) {
+ .then(function() {
me.log('saved palette ' + id);
return id;
})
@@ -762,7 +762,7 @@ class Cognos {
.then(function() {
me.log('We have been reset, savePalette again');
me.resetting = false;
- return me.savePalettes(id, palette);
+ return me.savePalette(id, palette);
})
.catch(function() {
throw err;
@@ -771,7 +771,7 @@ class Cognos {
} else {
result = me.requester
.post('bi/v1/palettes/my', palette, true)
- .then(function(data) {
+ .then(function() {
me.log('saved palette');
})
.catch(function(err) {
@@ -781,7 +781,7 @@ class Cognos {
.then(function() {
me.log('We have been reset, savePalette again');
me.resetting = false;
- return me.savePalettes(palette, id);
+ return me.savePalette(palette, id);
})
.catch(function() {
throw err;
@@ -790,6 +790,37 @@ class Cognos {
}
return result;
}
+
+ deletePalette(id) {
+ var me = this;
+ var params = {
+ force: 'true'
+ };
+
+ var result = me.requester
+ .delete('bi/v1/palettes/' + id, params, false)
+ .then(function() {
+ me.log('deleted palette ' + id);
+ return id;
+ })
+ .catch(function(err) {
+ me.error('CognosRequest : Error in deletePalette', err);
+ if (err == 'Not Found') {
+ throw 'Palette with id ' + id + ' is not found';
+ }
+ return me
+ .handleError(err)
+ .then(function() {
+ me.log('We have been reset, deletePalette again');
+ me.resetting = false;
+ return me.deletePalette(id);
+ })
+ .catch(function() {
+ throw err;
+ });
+ });
+ return result;
+ }
}
/**
|
feat: Added deletePalette function
|
CognosExt_jcognos
|
train
|
c8e3e9829e8f81988455a12293f2e107b717b5e4
|
diff --git a/src/joint.dia.element.js b/src/joint.dia.element.js
index <HASH>..<HASH> 100644
--- a/src/joint.dia.element.js
+++ b/src/joint.dia.element.js
@@ -771,7 +771,9 @@ joint.dia.ElementView = joint.dia.CellView.extend({
if (!_.isUndefined(yAlignment) || !_.isUndefined(xAlignment)) {
- var velBBox = vel.bbox(true /* without transformations */);
+ // Get the boundind box with the tranformations applied by the the
+ // element itself only.
+ var velBBox = vel.bbox(false, vel.node.parentNode);
// Componsate the size with the bounding box origin offset.
velBBox.height += velBBox.y;
velBBox.width += velBBox.x;
|
dia.ElementView: y-alignment & x-alignment takes the measured element transformation into account (#<I>)
|
clientIO_joint
|
train
|
dbf43569dc7cb7910f0a56fda7321b64cc32b5e1
|
diff --git a/drools-api/src/main/java/org/drools/KnowledgeBase.java b/drools-api/src/main/java/org/drools/KnowledgeBase.java
index <HASH>..<HASH> 100644
--- a/drools-api/src/main/java/org/drools/KnowledgeBase.java
+++ b/drools-api/src/main/java/org/drools/KnowledgeBase.java
@@ -8,7 +8,6 @@ import org.drools.runtime.KnowledgeSessionConfiguration;
import org.drools.runtime.StatefulKnowledgeSession;
public interface KnowledgeBase extends KnowledgeBaseEventManager {
- void addKnowledgePackage(KnowledgePackage knowledgePackage);
void addKnowledgePackages(Collection<KnowledgePackage> knowledgePackage);
|
JBRULES-<I> Drools API
-Removed single package addition for now, just to keep api slim. Can always add back again later if demand is there.
git-svn-id: <URL>
|
kiegroup_droolsjbpm-knowledge
|
train
|
049c0addf77cd72b7e57af389e1d093a6bbf0d4b
|
diff --git a/internal/security/secrets/helper/helper.go b/internal/security/secrets/helper/helper.go
index <HASH>..<HASH> 100644
--- a/internal/security/secrets/helper/helper.go
+++ b/internal/security/secrets/helper/helper.go
@@ -42,7 +42,7 @@ const (
pkiInitBaseDir = "edgex/security-secrets-setup"
defaultPkiCacheDir = "/etc/edgex/pki"
defaultPkiDeployDir = "/run/edgex/secrets"
- PkiInitFilePerServiceComplete = ".security-secrets-secrets.complete"
+ PkiInitFilePerServiceComplete = ".security-secrets-setup.complete"
)
func CopyFile(fileSrc, fileDest string) (int64, error) {
|
Updated for change made in <URL>
|
edgexfoundry_edgex-go
|
train
|
42b20521f73b078407bb2dc3cb61e3951b1a1509
|
diff --git a/lib/gym/xcodebuild_fixes/package_application_fix.rb b/lib/gym/xcodebuild_fixes/package_application_fix.rb
index <HASH>..<HASH> 100644
--- a/lib/gym/xcodebuild_fixes/package_application_fix.rb
+++ b/lib/gym/xcodebuild_fixes/package_application_fix.rb
@@ -27,13 +27,13 @@ module Gym
# Apply patches to PackageApplication4Gym from patches folder
Dir[File.join(Helper.gem_path("gym"), "lib/assets/package_application_patches/*.diff")].each do |patch|
- Helper.log.info "Applying Package Application patch: #{File.basename(patch)}" unless Gym.config[:silent]
+ Helper.log.info "Applying Package Application patch: #{File.basename(patch)}" if $verbose
command = ["patch #{patched_package_application_path} < #{patch}"]
Runner.new.print_command(command, "Applying Package Application patch: #{File.basename(patch)}") if $verbose
FastlaneCore::CommandExecutor.execute(command: command,
print_all: false,
- print_command: !Gym.config[:silent],
+ print_command: $verbose,
error: proc do |output|
ErrorHandler.handle_package_error(output)
end)
|
Less verbose output when patching the application
|
fastlane_fastlane
|
train
|
a7303294e5f5e2edd9ae1e737966d7a533624651
|
diff --git a/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/ContextException.java b/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/ContextException.java
index <HASH>..<HASH> 100644
--- a/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/ContextException.java
+++ b/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/ContextException.java
@@ -20,7 +20,7 @@ public final class ContextException
super( message );
}
- public ContextException( final String message, final Exception detail )
+ public ContextException( final String message, final Throwable detail )
{
super( message, detail );
}
diff --git a/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/ContextMapAdapter.java b/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/ContextMapAdapter.java
index <HASH>..<HASH> 100644
--- a/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/ContextMapAdapter.java
+++ b/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/ContextMapAdapter.java
@@ -12,6 +12,7 @@ package org.codehaus.plexus.context;
import java.util.AbstractMap;
import java.util.HashSet;
+import java.util.Map;
import java.util.Set;
public final class ContextMapAdapter
@@ -23,7 +24,7 @@ public final class ContextMapAdapter
// Implementation fields
// ----------------------------------------------------------------------
- private final Context context;
+ final Map<Object, Object> contextData;
// ----------------------------------------------------------------------
// Constructors
@@ -31,7 +32,7 @@ public final class ContextMapAdapter
public ContextMapAdapter( final Context context )
{
- this.context = context;
+ contextData = context.getContextData();
}
// ----------------------------------------------------------------------
@@ -39,24 +40,27 @@ public final class ContextMapAdapter
// ----------------------------------------------------------------------
@Override
+ public boolean containsKey( final Object key )
+ {
+ return get( key ) != null;
+ }
+
+ @Override
public Object get( final Object key )
{
- try
- {
- final Object value = context.get( key );
- return value instanceof String ? value : null;
- }
- catch ( final ContextException e )
- {
- return null;
- }
+ final Object value = contextData.get( key );
+ return value instanceof String ? value : null;
}
+ // ----------------------------------------------------------------------
+ // Implementation helpers
+ // ----------------------------------------------------------------------
+
@Override
public Set<Entry<Object, Object>> entrySet()
{
final Set<Entry<Object, Object>> tempSet = new HashSet<Entry<Object, Object>>();
- for ( final Entry<Object, Object> entry : context.getContextData().entrySet() )
+ for ( final Entry<Object, Object> entry : contextData.entrySet() )
{
if ( entry.getValue() instanceof String )
{
diff --git a/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/DefaultContext.java b/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/DefaultContext.java
index <HASH>..<HASH> 100644
--- a/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/DefaultContext.java
+++ b/guice-plexus/guice-plexus-shim/src/main/java/org/codehaus/plexus/context/DefaultContext.java
@@ -35,12 +35,13 @@ public final class DefaultContext
public DefaultContext( final Map<?, ?> context )
{
- if ( context != null )
+ if ( null == context )
{
- for ( final Entry<?, ?> e : context.entrySet() )
- {
- put( e.getKey(), e.getValue() );
- }
+ throw new IllegalArgumentException( "Context is null" );
+ }
+ for ( final Entry<?, ?> e : context.entrySet() )
+ {
+ put( e.getKey(), e.getValue() );
}
}
|
OSGI-<I>: minor context compatibility improvements
|
sonatype_sisu
|
train
|
681c332b98c34f71ff5949a181369c62ebf6959e
|
diff --git a/tests/org.eclipse.xtext.xbase.tests/src/org/eclipse/xtext/xbase/tests/validation/TypeConformanceValidatorTest.java b/tests/org.eclipse.xtext.xbase.tests/src/org/eclipse/xtext/xbase/tests/validation/TypeConformanceValidatorTest.java
index <HASH>..<HASH> 100644
--- a/tests/org.eclipse.xtext.xbase.tests/src/org/eclipse/xtext/xbase/tests/validation/TypeConformanceValidatorTest.java
+++ b/tests/org.eclipse.xtext.xbase.tests/src/org/eclipse/xtext/xbase/tests/validation/TypeConformanceValidatorTest.java
@@ -7,11 +7,8 @@
*******************************************************************************/
package org.eclipse.xtext.xbase.tests.validation;
-import static com.google.common.collect.Lists.*;
import static org.eclipse.xtext.xbase.validation.IssueCodes.*;
-import java.util.List;
-
import org.eclipse.emf.ecore.EClass;
import org.eclipse.xtext.common.types.TypesPackage;
import org.eclipse.xtext.junit.validation.ValidationTestHelper;
|
[Xtend] fixed compiler issue with synthetic dispatch method. (see <URL>)
|
eclipse_xtext-extras
|
train
|
9f892e51d4896efb4c923cc0f7e1321753c35719
|
diff --git a/querybuilder/tables.py b/querybuilder/tables.py
index <HASH>..<HASH> 100644
--- a/querybuilder/tables.py
+++ b/querybuilder/tables.py
@@ -226,12 +226,31 @@ class Table(object):
return [field.get_name() for field in self.fields]
def get_field_identifiers(self):
+ """
+ Loop through this tables fields and calls the get_identifier
+ method on each of them to build a list of field identifiers
+ @return: A list of field identifiers found in this table
+ @rtype: list of str
+ """
return [field.get_identifier() for field in self.fields]
def get_field_prefix(self):
+ """
+ Gets the prefix to be used in front of each field. If no prefix is
+ set, then the identifier for this table is returned
+ @return: The field prefix for this table
+ @rtype: str
+ """
return self.field_prefix or self.get_identifier()
def find_field(self, field=None, alias=None):
+ """
+ Finds a field by name or alias.
+ @param field: string of the field name or alias, dict of {'alias': field}, or a Field instance
+ @type field: str or dict or Field
+ @return: The field if it is found, otherwise None
+ @rtype: Field or None
+ """
if alias:
field = alias
field = FieldFactory(field, table=self, alias=alias)
|
* Finished documenting base table class
|
ambitioninc_django-query-builder
|
train
|
f7c4e022c69094fde29c4fa8eef99062337e701f
|
diff --git a/go/protocol/chat1/extras.go b/go/protocol/chat1/extras.go
index <HASH>..<HASH> 100644
--- a/go/protocol/chat1/extras.go
+++ b/go/protocol/chat1/extras.go
@@ -975,6 +975,8 @@ func (b MessageBody) TextForDecoration() string {
case MessageType_ATTACHMENT:
// Exclude the filename for text decoration.
return b.Attachment().Object.Title
+ case MessageType_REQUESTPAYMENT:
+ return ""
default:
return b.SearchableText()
}
|
dont decorate payment request (#<I>)
|
keybase_client
|
train
|
bffbcc70bf63025e70d61b7efe3fc76b7b6e8c21
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -452,11 +452,24 @@ Pagelet.readable('connect', function connect(spark, next) {
case 'get':
pagelet.render({ substream: true }, function renderd(err, fragment) {
- stream.write({ type: 'fragment', fragment: fragment, err: err });
+ stream.write({ type: 'fragment', frag: fragment, err: err });
});
break;
- // @TODO handle post/put
+ case 'post':
+ case 'put':
+ if (!(data.type in pagelet)) {
+ return stream.write({ type: data.type, err: new Error('Method not supported by pagelet') });
+ }
+
+ pagelet[data.type](data.body || {}, data.files || [], function processed(err, data) {
+ if (err) return stream.write({ type: data.type, err: err });
+
+ pagelet.render({ data: data, substream: true }, function rendered(err, fragment) {
+ stream.write({ type: 'fragment', frag: fragment, err: err });
+ });
+ });
+ break;
}
});
|
[minor] Added support for streaming POST/PUT data
|
bigpipe_pagelet
|
train
|
51b7999a7d07048f066ae3054fbfb37d90ce0538
|
diff --git a/src/jsonapi/resource.js b/src/jsonapi/resource.js
index <HASH>..<HASH> 100644
--- a/src/jsonapi/resource.js
+++ b/src/jsonapi/resource.js
@@ -18,8 +18,8 @@ function compound({model, relationshipModel, relationshipPath, include, included
included[id] = resource({
document,
model: relationshipModel,
- include,
- path: relationshipPath,
+ // FIXME workaround to get the next sibling in include path
+ include: include.split('.').slice(1).join('.'),
included
})
}
diff --git a/test/methods/read.js b/test/methods/read.js
index <HASH>..<HASH> 100644
--- a/test/methods/read.js
+++ b/test/methods/read.js
@@ -2,8 +2,14 @@ import request from 'supertest'
import uuid from 'uuid'
import util from 'util'
import appMock from '../utils/app'
+import campaignFixture from '../fixtures/campaign'
+import componentFixture from '../fixtures/component'
+import nodeFixture from '../fixtures/node'
import projectFixture from '../fixtures/project'
import userFixture from '../fixtures/user'
+import Campaign from '../models/campaign'
+import Component from '../models/component'
+import Node from '../models/node'
import Project from '../models/project'
import User from '../models/user'
import {
@@ -47,26 +53,39 @@ describe('netiam', () => {
after(teardown)
it('should create a user', done => {
- User
- .create({
- username: 'eliias',
- email: 'hannes@impossiblearts.com',
- birthday: new Date(2015, 7, 3)
- })
- .then(document => {
- user = document
- user.get({plain: true}).should.have.properties([
- 'id',
- 'email',
- 'username',
- 'birthday',
- 'createdAt',
- 'updatedAt'
- ])
+ const project = Project.create(projectFixture)
+ const campaign = Campaign.create(campaignFixture)
+ const node = Node.create(nodeFixture)
+ const component = Component.create(componentFixture)
+
+ Promise
+ .all([campaign, node, component, project])
+ .then(values => {
+ const [campaign, node, component, project] = values
+ return User
+ .create({
+ username: 'eliias',
+ email: 'hannes@impossiblearts.com',
+ birthday: new Date(2015, 7, 3)
+ })
+ .then(document => {
+ user = document
+ user.toJSON().should.have.properties([
+ 'id',
+ 'email',
+ 'username',
+ 'birthday',
+ 'createdAt',
+ 'updatedAt'
+ ])
- return Project
- .create(projectFixture)
- .then(document => user.setProjects([document]))
+ return Promise.all([
+ campaign.setNodes([node]),
+ node.setComponents([component]),
+ user.setCampaigns([campaign]),
+ user.setProjects([project])
+ ])
+ })
})
.then(() => done())
.catch(done)
@@ -162,5 +181,51 @@ describe('netiam', () => {
.end(done)
})
+ it('should get a user and deep nested documents', done => {
+ request(app)
+ .get(`/users/${user.id}?include=campaigns.nodes.components`)
+ .set('Accept', 'application/json')
+ .expect(200)
+ .expect('Content-Type', /json/)
+ .expect(res => {
+ const json = res.body
+
+ json.should.have.properties(['data', 'included'])
+ json.data.should.be.Object()
+ json.data.should.be.Object()
+ json.data.should.have.properties([
+ 'id',
+ 'type',
+ 'attributes',
+ 'relationships'
+ ])
+ json.data.id.should.be.String()
+ json.data.id.should.have.length(36)
+ json.data.type.should.be.String()
+ json.data.type.should.eql('user')
+ json.data.attributes.should.be.Object()
+ json.data.attributes.should.have.properties([
+ 'email',
+ 'username',
+ 'birthday',
+ 'createdAt',
+ 'updatedAt'
+ ])
+ json.data.attributes.email.should.eql('hannes@impossiblearts.com')
+ json.data.attributes.username.should.eql('eliias')
+ json.data.relationships.should.be.Object()
+ json.data.relationships.should.have.properties([
+ 'campaigns',
+ 'projects'
+ ])
+ json.included.should.be.Array()
+ json.included.should.have.length(3)
+ json.included[0].type.should.eql('component')
+ json.included[1].type.should.eql('node')
+ json.included[2].type.should.eql('campaign')
+ })
+ .end(done)
+ })
+
})
})
|
fix: deep nested resource were not displayed correctly
A new test has been added to prevent a deployment of this behavior in
the future.
|
netiam_contrib-rest
|
train
|
7277147df784cca24fddd46b1c3d3d56f1e9de1d
|
diff --git a/pyocd/target/builtin/target_MIMXRT1015xxxxx.py b/pyocd/target/builtin/target_MIMXRT1015xxxxx.py
index <HASH>..<HASH> 100644
--- a/pyocd/target/builtin/target_MIMXRT1015xxxxx.py
+++ b/pyocd/target/builtin/target_MIMXRT1015xxxxx.py
@@ -728,15 +728,14 @@ class MIMXRT1015xxxxx(IMXRT):
VENDOR = "NXP"
- # Note: itcm, dtcm, and ocram share a single 128 KB block of RAM that can be configurably
- # divided between those regions (this is called FlexRAM). Thus, the memory map regions for
- # each of these RAMs allocate the maximum possible of 128 KB, but that is the maximum and
- # will not actually be available in all regions simultaneously.
+ # Note: by default there are 64 KB ITCM, 64 KB DTCM and 128 KB OCRAM available for MIMXRT1015.
+ # And it also has 256 KB FlexRAM that can be enabled and configured by GPR17, customers can
+ # allocate this 256 KB FlexRAM to ITCM/DTCM/OCRAM, but the FlexRAM is not available by default.
MEMORY_MAP = MemoryMap(
- RamRegion(name="itcm", start=0x00000000, length=0x8000), # 32 KB
+ RamRegion(name="itcm", start=0x00000000, length=0x10000), # 64 KB
RomRegion(name="romcp", start=0x00200000, length=0x18000), # 96 KB
- RamRegion(name="dtcm", start=0x20000000, length=0x8000), # 32 KB
- RamRegion(name="ocram", start=0x20200000, length=0x10000), # 64 KB
+ RamRegion(name="dtcm", start=0x20000000, length=0x10000), # 64 KB
+ RamRegion(name="ocram", start=0x20200000, length=0x20000), # 128 KB
FlashRegion(name="flexspi", start=0x60000000, end=0x60ffffff, blocksize=0x1000, is_boot_memory=True,
algo=FLASH_ALGO_QUADSPI, page_size=0x100),
)
|
Fix MIMXRT<I> memory map issue in target_MIMXRT<I>xxxxx.py
|
mbedmicro_pyOCD
|
train
|
bbdbbe32bf73204670e6363ed176337208316130
|
diff --git a/domain/command-handling/src/main/java/io/motown/domain/chargingstation/ChargingStation.java b/domain/command-handling/src/main/java/io/motown/domain/chargingstation/ChargingStation.java
index <HASH>..<HASH> 100644
--- a/domain/command-handling/src/main/java/io/motown/domain/chargingstation/ChargingStation.java
+++ b/domain/command-handling/src/main/java/io/motown/domain/chargingstation/ChargingStation.java
@@ -68,11 +68,7 @@ public class ChargingStation extends AbstractAnnotatedAggregateRoot {
@CommandHandler
public void handle(RequestUnlockConnectorCommand command) {
- if(!this.isRegistered || !this.isConfigured){
- //TODO: Decide what to do in this situation (respond with event or return value) - Ingo Pak 21 nov 2013
- throw new RuntimeException("Chargingstation is not registered or configured");
- }
-
+ checkCommunicationAllowed();
if (command.getConnectorId() > numberOfConnectors) {
apply(new ConnectorNotFoundEvent(id, command.getConnectorId()));
} else {
diff --git a/domain/command-handling/src/test/java/io/motown/domain/chargingstation/ChargingStationTest.java b/domain/command-handling/src/test/java/io/motown/domain/chargingstation/ChargingStationTest.java
index <HASH>..<HASH> 100644
--- a/domain/command-handling/src/test/java/io/motown/domain/chargingstation/ChargingStationTest.java
+++ b/domain/command-handling/src/test/java/io/motown/domain/chargingstation/ChargingStationTest.java
@@ -106,6 +106,20 @@ public class ChargingStationTest {
}
@Test
+ public void testRequestingToUnlockConnectorForUnregisteredChargingStation() {
+ fixture.given(getConfiguredChargingStation())
+ .when(new RequestUnlockConnectorCommand(getChargingStationId(), 1))
+ .expectException(IllegalStateException.class);
+ }
+
+ @Test
+ public void testRequestingToUnlockConnectorForUnconfiguredChargingStation() {
+ fixture.given(getRegisteredChargingStation())
+ .when(new RequestUnlockConnectorCommand(getChargingStationId(), 1))
+ .expectException(IllegalStateException.class);
+ }
+
+ @Test
public void testRequestingToUnlockConnector() {
fixture.given(getChargingStation())
.when(new RequestUnlockConnectorCommand(getChargingStationId(), 1))
|
Refactored handling unlock connector command
The method which handles the RequestUnlockConnectorCommand now uses a
recently added generic method to check if communication with a charging
station is allowed.
|
motown-io_motown
|
train
|
5204431827dbd7be8f4a6eef6029184065413350
|
diff --git a/tang/src/test/java/com/microsoft/tang/TestBindSingleton.java b/tang/src/test/java/com/microsoft/tang/TestBindSingleton.java
index <HASH>..<HASH> 100644
--- a/tang/src/test/java/com/microsoft/tang/TestBindSingleton.java
+++ b/tang/src/test/java/com/microsoft/tang/TestBindSingleton.java
@@ -40,6 +40,14 @@ public class TestBindSingleton {
}
+ public static class AA {
+ @Inject
+ public AA() {
+ // Intentionally blank
+ }
+
+ }
+
public static class B extends A {
@Inject
public B() {
@@ -96,12 +104,12 @@ public class TestBindSingleton {
@Test
public void testMultipleInjectorInstaceWithSingleton() throws BindException, InjectionException {
final JavaConfigurationBuilder cb = Tang.Factory.getTang().newConfigurationBuilder();
- cb.bindSingleton(A.class);
+ cb.bindSingleton(AA.class);
final Injector i1 = Tang.Factory.getTang().newInjector(cb.build());
final Injector i2 = Tang.Factory.getTang().newInjector(cb.build());
- assertTrue("Different injectors should return different singleton object instances", i1.getInstance(A.class) != i2.getInstance(A.class));
+ assertTrue("Different injectors should return different singleton object instances", i1.getInstance(AA.class) != i2.getInstance(AA.class));
}
@Test
|
Fix bind singleton test.
It was using an unintended class, causing an error that is unrelated to
the issue it was trying to reproduce.
|
apache_reef
|
train
|
2691ef587c8ae9fc506ed0c3139c16a9c11c8aab
|
diff --git a/lib/zelastic/index_manager.rb b/lib/zelastic/index_manager.rb
index <HASH>..<HASH> 100644
--- a/lib/zelastic/index_manager.rb
+++ b/lib/zelastic/index_manager.rb
@@ -27,7 +27,12 @@ module Zelastic
config.write_alias
end
+ total = config.data_source.count
+ indexed_count = 0
+
config.data_source.find_in_batches(batch_size: batch_size) do |batch|
+ indexed_count += batch_size
+ logger.info("ES: (#{(indexed_count.to_f/total * 100).round(2)}% - #{indexed_count}/#{total}) Indexing #{config.type} records")
indexer.index_batch(batch, client: client, index_name: index_name)
end
end
diff --git a/lib/zelastic/indexer.rb b/lib/zelastic/indexer.rb
index <HASH>..<HASH> 100644
--- a/lib/zelastic/indexer.rb
+++ b/lib/zelastic/indexer.rb
@@ -18,12 +18,10 @@ module Zelastic
end
def index_batch(batch, client: nil, index_name: nil)
- logger.info("ES: Indexing #{config.type} record")
-
version = current_version
- execute_bulk(client: client, index_name: index_name) do |index_name|
+ execute_bulk(client: client, index_name: index_name) do |index|
batch.map do |record|
- index_command(index: index_name, version: version, record: record)
+ index_command(index: index, version: version, record: record)
end
end
end
|
v1 -- Show percentage and count
|
carwow_zelastic
|
train
|
999d2c5304fcced7844d34f2b3102e8a296744fe
|
diff --git a/src/Analyser/Analyser.php b/src/Analyser/Analyser.php
index <HASH>..<HASH> 100644
--- a/src/Analyser/Analyser.php
+++ b/src/Analyser/Analyser.php
@@ -95,9 +95,15 @@ class Analyser
* @param string[] $files
* @param bool $onlyFiles
* @param \Closure|null $progressCallback
+ * @param bool $debug
* @return string[]|\PHPStan\Analyser\Error[] errors
*/
- public function analyse(array $files, bool $onlyFiles, \Closure $progressCallback = null): array
+ public function analyse(
+ array $files,
+ bool $onlyFiles,
+ \Closure $progressCallback = null,
+ bool $debug = false
+ ): array
{
$errors = [];
@@ -155,6 +161,9 @@ class Analyser
} catch (\PHPStan\AnalysedCodeException $e) {
$errors[] = new Error($e->getMessage(), $file, null, false);
} catch (\Throwable $t) {
+ if ($debug) {
+ throw $t;
+ }
$errors[] = new Error(sprintf('Internal error: %s', $t->getMessage()), $file);
}
}
diff --git a/src/Command/AnalyseApplication.php b/src/Command/AnalyseApplication.php
index <HASH>..<HASH> 100644
--- a/src/Command/AnalyseApplication.php
+++ b/src/Command/AnalyseApplication.php
@@ -54,13 +54,15 @@ class AnalyseApplication
* @param \Symfony\Component\Console\Style\OutputStyle $style
* @param \PHPStan\Command\ErrorFormatter\ErrorFormatter $errorFormatter
* @param bool $defaultLevelUsed
+ * @param bool $debug
* @return int Error code.
*/
public function analyse(
array $paths,
OutputStyle $style,
ErrorFormatter $errorFormatter,
- bool $defaultLevelUsed
+ bool $defaultLevelUsed,
+ bool $debug
): int
{
$errors = [];
@@ -94,13 +96,10 @@ class AnalyseApplication
$this->updateMemoryLimitFile();
- $progressStarted = false;
-
- $fileOrder = 0;
- $errors = array_merge($errors, $this->analyser->analyse(
- $files,
- $onlyFiles,
- function () use ($style, &$progressStarted, $files, &$fileOrder) {
+ if (!$debug) {
+ $progressStarted = false;
+ $fileOrder = 0;
+ $progressCallback = function () use ($style, &$progressStarted, $files, &$fileOrder) {
if (!$progressStarted) {
$style->progressStart(count($files));
$progressStarted = true;
@@ -110,10 +109,21 @@ class AnalyseApplication
$this->updateMemoryLimitFile();
}
$fileOrder++;
- }
+ };
+ } else {
+ $progressCallback = function (string $file) use ($style) {
+ $style->writeln($file);
+ };
+ }
+
+ $errors = array_merge($errors, $this->analyser->analyse(
+ $files,
+ $onlyFiles,
+ $progressCallback,
+ $debug
));
- if ($progressStarted) {
+ if (isset($progressStarted) && $progressStarted) {
$style->progressFinish();
}
diff --git a/src/Command/AnalyseCommand.php b/src/Command/AnalyseCommand.php
index <HASH>..<HASH> 100644
--- a/src/Command/AnalyseCommand.php
+++ b/src/Command/AnalyseCommand.php
@@ -33,6 +33,7 @@ class AnalyseCommand extends \Symfony\Component\Console\Command\Command
new InputOption('configuration', 'c', InputOption::VALUE_REQUIRED, 'Path to project configuration file'),
new InputOption(self::OPTION_LEVEL, 'l', InputOption::VALUE_REQUIRED, 'Level of rule options - the higher the stricter'),
new InputOption(ErrorsConsoleStyle::OPTION_NO_PROGRESS, null, InputOption::VALUE_NONE, 'Do not show progress bar, only results'),
+ new InputOption('debug', null, InputOption::VALUE_NONE, 'Show debug information - which file is analysed, do not catch internal errors'),
new InputOption('autoload-file', 'a', InputOption::VALUE_REQUIRED, 'Project\'s additional autoload file path'),
new InputOption('errorFormat', null, InputOption::VALUE_REQUIRED, 'Format in which to print the result of the analysis', 'table'),
new InputOption('memory-limit', null, InputOption::VALUE_REQUIRED, 'Memory limit for analysis'),
@@ -191,7 +192,8 @@ class AnalyseCommand extends \Symfony\Component\Console\Command\Command
$input->getArgument('paths'),
$consoleStyle,
$errorFormatter,
- $defaultLevelUsed
+ $defaultLevelUsed,
+ $input->getOption('debug')
),
$memoryLimitFile
);
diff --git a/tests/PHPStan/Command/AnalyseApplicationIntegrationTest.php b/tests/PHPStan/Command/AnalyseApplicationIntegrationTest.php
index <HASH>..<HASH> 100644
--- a/tests/PHPStan/Command/AnalyseApplicationIntegrationTest.php
+++ b/tests/PHPStan/Command/AnalyseApplicationIntegrationTest.php
@@ -60,6 +60,7 @@ class AnalyseApplicationIntegrationTest extends \PHPStan\Testing\TestCase
[$path],
$style,
new TableErrorFormatter(),
+ false,
false
);
if (file_exists($memoryLimitFile)) {
|
--debug option for finding out on which file PHPStan crashes; rethrow internal errors
|
phpstan_phpstan
|
train
|
bc03a3d241c48d7e5c0dda4d1e975a653e285678
|
diff --git a/test/com/google/javascript/jscomp/ScopeSubject.java b/test/com/google/javascript/jscomp/ScopeSubject.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/ScopeSubject.java
+++ b/test/com/google/javascript/jscomp/ScopeSubject.java
@@ -24,7 +24,9 @@ import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.truth.FailureMetadata;
import com.google.common.truth.Subject;
+import com.google.javascript.rhino.Node;
import javax.annotation.CheckReturnValue;
+import javax.annotation.Nullable;
/**
* A Truth Subject for the AbstractScope class. Usage:
@@ -58,7 +60,7 @@ public final class ScopeSubject extends Subject<ScopeSubject, AbstractScope<?, ?
AbstractVar<?, ?> var = getVar(name);
if (var == null) {
ImmutableList<AbstractVar<?, ?>> declared =
- ImmutableList.copyOf(getSubject().getAllAccessibleVariables());
+ ImmutableList.copyOf(actual().getAllAccessibleVariables());
ImmutableList<String> names =
declared.stream().map(AbstractVar::getName).collect(toImmutableList());
if (names.size() > 10) {
@@ -74,24 +76,24 @@ public final class ScopeSubject extends Subject<ScopeSubject, AbstractScope<?, ?
}
private AbstractVar<?, ?> getVar(String name) {
- return getSubject().hasSlot(name) ? checkNotNull(getSubject().getVar(name)) : null;
+ return actual().hasSlot(name) ? checkNotNull(actual().getVar(name)) : null;
}
public final class DeclarationSubject {
private final AbstractVar<?, ?> var;
private DeclarationSubject(AbstractVar<?, ?> var) {
- this.var = var;
+ this.var = checkNotNull(var);
}
/**
- * Expects the variable to be defined on the given {@code scope}. The {@code preposition}
- * is either "on" or "", depending on whether it is needed for grammatical correctness.
- * The {@code expected} object is displayed in brackets, in parallel to the actual scope
- * that the variable is defined on.
+ * Expects the variable to be defined on the given {@code scope}. The {@code preposition} is
+ * either "on" or "", depending on whether it is needed for grammatical correctness. The {@code
+ * expected} object is displayed in brackets, in parallel to the actual scope that the variable
+ * is defined on.
*/
private void expectScope(String preposition, Object expected, AbstractScope<?, ?> scope) {
- if (var != null && var.getScope() != scope) {
+ if (var.getScope() != scope) {
failWithBadResults(
"declares " + var.getName() + (!preposition.isEmpty() ? " " : "") + preposition,
expected,
@@ -102,38 +104,71 @@ public final class ScopeSubject extends Subject<ScopeSubject, AbstractScope<?, ?
/** Expects the declared variable to be declared on the subject scope. */
public void directly() {
- expectScope("", "directly", getSubject());
+ expectScope("", "directly", actual());
}
/** Expects the declared variable to be declared on the given scope. */
public void on(AbstractScope<?, ?> scope) {
checkState(
- scope != getSubject(),
+ scope != actual(),
"It doesn't make sense to pass the scope already being asserted about. Use .directly()");
expectScope("on", scope, scope);
}
/** Expects the declared variable to be declared on the closest container scope. */
public void onClosestContainerScope() {
- expectScope("on", "the closest container scope", getSubject().getClosestContainerScope());
+ expectScope("on", "the closest container scope", actual().getClosestContainerScope());
}
/** Expects the declared variable to be declared on the closest hoist scope. */
public void onClosestHoistScope() {
- expectScope("on", "the closest hoist scope", getSubject().getClosestHoistScope());
+ expectScope("on", "the closest hoist scope", actual().getClosestHoistScope());
}
/** Expects the declared variable to be declared on the global scope. */
public void globally() {
- expectScope("", "globally", getSubject().getGlobalScope());
+ expectScope("", "globally", actual().getGlobalScope());
}
/** Expects the declared variable to be declared on any scope other than the subject. */
public void onSomeParent() {
- if (var != null && var.getScope() == getSubject()) {
+ if (var != null && var.getScope() == actual()) {
failWithBadResults(
"declares " + var.getName(), "on a parent scope", "declares it", "directly");
}
}
+
+ /** Expects the declared variable to be declared on some scope with the given label. */
+ public void onScopeLabeled(String expectedLabel) {
+ checkNotNull(expectedLabel);
+ String actualLabel = getLabel(var.getScopeRoot());
+ if (actualLabel == null) {
+ failWithBadResults(
+ "declares " + var.getName(),
+ "on a scope labeled \"" + expectedLabel + "\"",
+ "declares it",
+ "on an unlabeled scope");
+ } else if (!actualLabel.equals(expectedLabel)) {
+ failWithBadResults(
+ "declares " + var.getName(),
+ "on a scope labeled \"" + expectedLabel + "\"",
+ "declares it",
+ "on a scope labeled \"" + actualLabel + "\"");
+ }
+ }
+ }
+
+ /** Returns the name of the label applied to n, or null if none exists. */
+ @Nullable
+ private String getLabel(Node n) {
+ // If the node is labeled it will be the second child of a LABEL and the first child
+ // will be a LABEL_NAME.
+ Node labelNameNode = n.getPrevious();
+ if (labelNameNode != null && labelNameNode.isLabelName()) {
+ checkState(labelNameNode.getParent().isLabel());
+ return labelNameNode.getString();
+ } else {
+ return null;
+ }
}
}
|
Add onScopeLabeled() to ScopeSubject
Also perform some cleanup:
1. Replace deprecated getSubject() with actual()
2. add some checkNotNull assertions
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
5a7028d4195e19f9fa3979edaf656dd0045e3d91
|
diff --git a/languagetool-language-modules/uk/src/main/java/org/languagetool/tagging/uk/UkrainianTagger.java b/languagetool-language-modules/uk/src/main/java/org/languagetool/tagging/uk/UkrainianTagger.java
index <HASH>..<HASH> 100644
--- a/languagetool-language-modules/uk/src/main/java/org/languagetool/tagging/uk/UkrainianTagger.java
+++ b/languagetool-language-modules/uk/src/main/java/org/languagetool/tagging/uk/UkrainianTagger.java
@@ -124,32 +124,20 @@ public class UkrainianTagger extends BaseTagger {
rightPartsWithLeftTagMap.put("то", "(.*pron|noun|adv|part|conj).*");
rightPartsWithLeftTagMap.put("таки", "(verb(:rev)?:(futr|past|pres)|.*pron|noun|part|predic|insert).*");
- try {
- InputStream is = JLanguageTool.getDataBroker().getFromResourceDirAsStream("/uk/dash_prefixes.txt");
- Scanner scanner = new Scanner(is,"UTF-8");
- String text = scanner.useDelimiter("\\A").next();
- scanner.close();
- dashPrefixes = new HashSet<>( java.util.Arrays.asList(text.split("[\r\n]+")) );
-
- is = JLanguageTool.getDataBroker().getFromResourceDirAsStream("/uk/dash_left_master.txt");
- scanner = new Scanner(is,"UTF-8");
- text = scanner.useDelimiter("\\A").next();
- scanner.close();
- leftMasterSet = new HashSet<>( java.util.Arrays.asList(text.split("[\r\n]+")) );
-
- is = JLanguageTool.getDataBroker().getFromResourceDirAsStream("/uk/dash_slaves.txt");
- scanner = new Scanner(is,"UTF-8");
- text = scanner.useDelimiter("\\A").next();
- scanner.close();
- slaveSet = new HashSet<>( java.util.Arrays.asList(text.split("[\r\n]+")) );
- // TODO: "бабуся", "лялька", "рятівник" - not quite slaves, could be masters too
+ dashPrefixes = loadSet("/uk/dash_prefixes.txt");
+ leftMasterSet = loadSet("/uk/dash_left_master.txt");
+ slaveSet = loadSet("/uk/dash_slaves.txt");
+ // TODO: "бабуся", "лялька", "рятівник" - not quite slaves, could be masters too
+ }
- }
- catch(Exception e) {
- throw new RuntimeException(e);
+ private static Set<String> loadSet(String path) {
+ InputStream is = JLanguageTool.getDataBroker().getFromResourceDirAsStream(path);
+ try (Scanner scanner = new Scanner(is,"UTF-8")) {
+ String text = scanner.useDelimiter("\\A").next();
+ return new HashSet<>( Arrays.asList(text.split("[\r\n]+")) );
}
}
-
+
@Override
public final String getFileName() {
return "/uk/ukrainian.dict";
|
[uk] refactoring: avoid code duplication
|
languagetool-org_languagetool
|
train
|
c2f93e5ada6a83c850c1246cff00427b789bf071
|
diff --git a/lib/veritas/optimizer/logic/predicate/greater_than_or_equal_to.rb b/lib/veritas/optimizer/logic/predicate/greater_than_or_equal_to.rb
index <HASH>..<HASH> 100644
--- a/lib/veritas/optimizer/logic/predicate/greater_than_or_equal_to.rb
+++ b/lib/veritas/optimizer/logic/predicate/greater_than_or_equal_to.rb
@@ -2,22 +2,36 @@ module Veritas
class Optimizer
module Logic
class Predicate
+
+ # Abstract base class representing GreaterThanOrEqualTo optimizations
class GreaterThanOrEqualTo < self
include Comparable
+ # Optimize when the operands are always false
class AlwaysFalse < self
include Comparable::NeverComparable
include Predicate::AlwaysFalse
+ # Test if the operands are always false
+ #
+ # @return [Boolean]
+ #
+ # @api private
def optimizable?
super || LessThan::AlwaysTrue.new(operation.inverse).optimizable?
end
end # class AlwaysFalse
+ # Optimize when the operands are always true
class AlwaysTrue < self
include Predicate::AlwaysTrue
+ # Test if the operands are always true
+ #
+ # @return [Boolean]
+ #
+ # @api private
def optimizable?
operation = self.operation
GreaterThan::AlwaysTrue.new(operation).optimizable? ||
|
Added YARD docs for Optimizer::Logic::Predicate::GreaterThanOrEqualTo
|
dkubb_axiom
|
train
|
a6d711066727b2b5189e0907843f9eb90b600363
|
diff --git a/spec/window_spec.rb b/spec/window_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/window_spec.rb
+++ b/spec/window_spec.rb
@@ -53,7 +53,7 @@ describe RAutomation::Window do
it "#class_names" do
window = RAutomation::Window.new(:title => SpecHelper::DATA[:window1_title])
- window.class_names.size.should == 24
+ window.class_names.size.should == 26
fail "Expected class name not found." unless window.class_names.include?("WindowsForms10.Window.8.app.0.2bf8098_r15_ad1") or
window.class_names.include?("WindowsForms10.Window.8.app.0.2bf8098_r16_ad1")
|
fix Window#class_names spec to account for new windows
|
jarmo_RAutomation
|
train
|
62fc2c821b7b9d757a5dee74a4c17e0010c8301e
|
diff --git a/cluster.go b/cluster.go
index <HASH>..<HASH> 100644
--- a/cluster.go
+++ b/cluster.go
@@ -595,8 +595,16 @@ func (c *clusterState) slotRandomNode(slot int) (*clusterNode, error) {
if len(nodes) == 0 {
return c.nodes.Random()
}
- n := rand.Intn(len(nodes))
- return nodes[n], nil
+ if len(nodes) == 1 {
+ return nodes[0], nil
+ }
+ randomNodes := rand.Perm(len(nodes))
+ for _, idx := range randomNodes {
+ if node := nodes[idx]; !node.Failing() {
+ return node, nil
+ }
+ }
+ return nodes[randomNodes[0]], nil
}
func (c *clusterState) slotNodes(slot int) []*clusterNode {
|
Check Failing() before serving random node (#<I>)
* Check Failing() before serving random node
* Revert condition
* Addressed review comments
* Fallback to random failing node
|
go-redis_redis
|
train
|
2c439db4c68e410635f407355eb7dad8de67485a
|
diff --git a/examples/pay.php b/examples/pay.php
index <HASH>..<HASH> 100644
--- a/examples/pay.php
+++ b/examples/pay.php
@@ -10,7 +10,6 @@ $payment = array(
"currency" => "EUR",
"manualClearing" => "false", // Optional: set to true if you want to do a manual clearing
"useProfile" => "false", // Optional: set if you want to create a profile
- "profileID" => "profile123", // Optional: set the profile ID for the customer
);
// All fields are optional, but most of them are highly recommended
|
Update because of error
If a merchant is not enabled for profiles, the error "PROFILE_FLEX_NOT_SUPPORTED" occur, independent of the useProfile setting. Therefore we should remove the profileID.
|
mpay24_mpay24-php
|
train
|
d1f2eceb7993f2e7a7cc887e653abc77be144ae8
|
diff --git a/lib/draper/base.rb b/lib/draper/base.rb
index <HASH>..<HASH> 100644
--- a/lib/draper/base.rb
+++ b/lib/draper/base.rb
@@ -125,6 +125,13 @@ module Draper
@model
end
+ # Delegates == to the decorated models
+ #
+ # @return [Boolean] true if other's model == self's model
+ def ==(other)
+ @model == other.model
+ end
+
private
def select_methods
specified = self.allowed || (model.public_methods.map{|s| s.to_sym} - denied.map{|s| s.to_sym})
diff --git a/spec/base_spec.rb b/spec/base_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/base_spec.rb
+++ b/spec/base_spec.rb
@@ -132,6 +132,13 @@ describe Draper::Base do
end
end
+ context('.==') do
+ it "should compare the decorated models" do
+ other = Draper::Base.new(source)
+ subject.should == other
+ end
+ end
+
describe "a sample usage with denies" do
let(:subject_with_denies){ DecoratorWithDenies.new(source) }
|
Delegate == to the decorated models
|
drapergem_draper
|
train
|
4c88bbcb05ff24c3b10dcacef100102522133f64
|
diff --git a/src/theme/components/Segment.js b/src/theme/components/Segment.js
index <HASH>..<HASH> 100644
--- a/src/theme/components/Segment.js
+++ b/src/theme/components/Segment.js
@@ -26,13 +26,13 @@ export default (variables = variable) => {
}
},
'.first': {
- borderTopLeftRadius: (platform=='ios') ? 5 : undefined,
- borderBottomLeftRadius: (platform=='ios') ? 5 : undefined,
+ borderTopLeftRadius: (platform==='ios') ? 5 : undefined,
+ borderBottomLeftRadius: (platform==='ios') ? 5 : undefined,
borderRightWidth: 0
},
'.last': {
- borderTopRightRadius: (platform=='ios') ? 5 : undefined,
- borderBottomRightRadius: (platform=='ios') ? 5 : undefined,
+ borderTopRightRadius: (platform==='ios') ? 5 : undefined,
+ borderBottomRightRadius: (platform==='ios') ? 5 : undefined,
borderLeftWidth: 0
},
'NativeBase.Text': {
diff --git a/src/theme/components/TabContainer.js b/src/theme/components/TabContainer.js
index <HASH>..<HASH> 100644
--- a/src/theme/components/TabContainer.js
+++ b/src/theme/components/TabContainer.js
@@ -13,7 +13,7 @@ export default (variables = variable) => {
shadowOpacity: (platformStyle==='material') ? 0.2 : undefined,
shadowRadius: (platformStyle==='material') ? 1.2 : undefined,
justifyContent: 'space-around',
- borderBottomWidth: (Platform.OS=='ios') ? variables.borderWidth : 0,
+ borderBottomWidth: (Platform.OS==='ios') ? variables.borderWidth : 0,
borderColor: variables.topTabBarBorderColor,
};
|
consistency: equivalence checking
|
GeekyAnts_NativeBase
|
train
|
4b741740b6f8c5ca52b94e83e31ef4476ad7158a
|
diff --git a/Fist.js b/Fist.js
index <HASH>..<HASH> 100644
--- a/Fist.js
+++ b/Fist.js
@@ -152,10 +152,10 @@ var Fist = Server.extend(/** @lends Fist.prototype */ {
};
}
- dirlist.list.forEach(processList, this);
+ forEach(dirlist.list, processList, this);
}
- dirs.forEach(processDir, this);
+ forEach(dirs, processDir, this);
return done.call(this, null, result);
}
diff --git a/util/readdir.js b/util/readdir.js
index <HASH>..<HASH> 100644
--- a/util/readdir.js
+++ b/util/readdir.js
@@ -14,12 +14,11 @@ module.exports = function (dirname, done) {
return done.call(ctx, err);
}
- list = list.sort();
- return done.call(ctx, null, list);
+ return done.call(ctx, null, list.sort());
});
} catch (err) {
- done.call(ctx, err, done);
+ done.call(ctx, err);
}
};
diff --git a/util/readdirs.js b/util/readdirs.js
index <HASH>..<HASH> 100644
--- a/util/readdirs.js
+++ b/util/readdirs.js
@@ -1,11 +1,10 @@
'use strict';
var readdir = require('./readdir');
+var forEach = require('fist.lang.foreach');
module.exports = function (dirs, done) {
- var i;
- var l;
var result = [];
var reject = false;
var count = dirs.length;
@@ -16,7 +15,7 @@ module.exports = function (dirs, done) {
return;
}
- function read (i, name) {
+ forEach(dirs, function (name, i) {
readdir.call(this, name, function (err, list) {
if ( reject ) {
@@ -43,10 +42,5 @@ module.exports = function (dirs, done) {
done.call(this, null, result);
}
});
- }
-
- for ( i = 0, l = dirs.length; i < l; i += 1) {
- read.call(this, i, dirs[i]);
- }
-
+ }, this);
};
|
<I>.x: change native forEach to fist.lang.foreach to correct ctx pass
|
fistlabs_fist
|
train
|
f892350b0ff77b9d110bae806796fe78afba4aad
|
diff --git a/revapi-java/src/test/java/org/revapi/java/SupplementaryJarsTest.java b/revapi-java/src/test/java/org/revapi/java/SupplementaryJarsTest.java
index <HASH>..<HASH> 100644
--- a/revapi-java/src/test/java/org/revapi/java/SupplementaryJarsTest.java
+++ b/revapi-java/src/test/java/org/revapi/java/SupplementaryJarsTest.java
@@ -92,7 +92,8 @@ public class SupplementaryJarsTest extends AbstractJavaElementAnalyzerTest {
"B$PrivateUsedClass.class")
.addAsResource(compRes2.compilationPath.resolve("B$UsedByIgnoredClass.class").toFile(),
"B$UsedByIgnoredClass.class")
- .addAsResource(compRes1.compilationPath.resolve("A$PrivateEnum.class").toFile(), "A$PrivateEnum.class");
+ .addAsResource(compRes2.compilationPath.resolve("A$PrivateEnum.class").toFile(), "A$PrivateEnum.class")
+ .addAsResource(compRes2.compilationPath.resolve("B$PrivateBase.class").toFile(), "B$PrivateBase.class");
}
@After
@@ -182,4 +183,32 @@ public class SupplementaryJarsTest extends AbstractJavaElementAnalyzerTest {
Assert.assertFalse(containsDifference(allReports, "method void B.UsedByIgnoredClass::<init>()", null,
Code.METHOD_REMOVED.code()));
}
+
+ @Test
+ public void testExcludedClassesInAPI() throws Exception {
+ List<Report> allReports = new ArrayList<>();
+ Reporter reporter = new CollectingReporter(allReports);
+
+ try (Revapi revapi = createRevapi(reporter)) {
+ revapi.analyze(AnalysisContext.builder()
+ .withOldAPI(API.of(new ShrinkwrapArchive(apiV1)).supportedBy(new ShrinkwrapArchive(supV1)).build())
+ .withNewAPI(API.of(new ShrinkwrapArchive(apiV2)).supportedBy(new ShrinkwrapArchive(supV2)).build())
+ .withConfigurationFromJSON("{\"revapi\": {\"java\": {" +
+ "\"filter\": {\"classes\": {\"exclude\": [\"C\", \"B.T$2\"]}}}}}").build());
+ }
+
+ Assert.assertEquals(3, allReports.size());
+ Assert.assertFalse(
+ containsDifference(allReports, null, "class B.T$1.Private", Code.CLASS_NON_PUBLIC_PART_OF_API.code()));
+ Assert.assertFalse(containsDifference(allReports, null, "field B.T$2.f2", Code.FIELD_ADDED.code()));
+ Assert.assertTrue(containsDifference(allReports, null, "field A.f3", Code.FIELD_ADDED.code()));
+ Assert.assertFalse(containsDifference(allReports, "class B.T$2", "class B.T$2", Code.CLASS_NOW_FINAL.code()));
+ Assert.assertTrue(containsDifference(allReports, null, "class B.T$3", Code.CLASS_ADDED.code()));
+ Assert.assertTrue(containsDifference(allReports, null, "class B.PrivateUsedClass",
+ Code.CLASS_NON_PUBLIC_PART_OF_API.code()));
+ Assert.assertFalse(containsDifference(allReports, "class B.UsedByIgnoredClass", "class B.UsedByIgnoredClass",
+ Code.CLASS_KIND_CHANGED.code()));
+ Assert.assertFalse(containsDifference(allReports, "method void B.UsedByIgnoredClass::<init>()", null,
+ Code.METHOD_REMOVED.code()));
+ }
}
diff --git a/revapi-java/src/test/resources/v2/supplementary/b/B.java b/revapi-java/src/test/resources/v2/supplementary/b/B.java
index <HASH>..<HASH> 100644
--- a/revapi-java/src/test/resources/v2/supplementary/b/B.java
+++ b/revapi-java/src/test/resources/v2/supplementary/b/B.java
@@ -43,7 +43,7 @@ public class B {
}
- private static class PrivateSuperClass {
+ private static class PrivateBase {
/**
* This will be reported as a usage of private class in a public capacity, because T$3 is in the API and
@@ -54,6 +54,9 @@ public class B {
}
}
+ private static class PrivateSuperClass extends PrivateBase {
+ }
+
/**
* This will NOT be reported as a usage of a private class in a public capacity. Inheriting from a
* private class by a public API class is a valid design pattern.
|
Added a test for the case where a filtered out class is also in the API.
(no surprises here, added just for the sake of the number of twists
in the tests ;) )
|
revapi_revapi
|
train
|
f752f2d316127bfb726ce9daf1cf62fd79be1352
|
diff --git a/lib/mongo/server/description.rb b/lib/mongo/server/description.rb
index <HASH>..<HASH> 100644
--- a/lib/mongo/server/description.rb
+++ b/lib/mongo/server/description.rb
@@ -223,7 +223,7 @@ module Mongo
@load_balancer = !!load_balancer
@features = Features.new(wire_versions, me || @address.to_s)
@average_round_trip_time = average_round_trip_time
- @last_update_time = Time.now.dup.freeze
+ @last_update_time = Time.now.freeze
@last_update_monotime = Utils.monotonic_time
if Mongo::Lint.enabled?
diff --git a/spec/mongo/server/description_spec.rb b/spec/mongo/server/description_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/mongo/server/description_spec.rb
+++ b/spec/mongo/server/description_spec.rb
@@ -56,20 +56,6 @@ describe Mongo::Server::Description do
end
end
- describe '#initialize' do
- context 'when Time.now is mocked' do
- it 'does not freeze mocked time' do
- obj = Time.now
- expect(Time).to receive(:now).at_least(:once).and_return(obj)
- expect(obj.frozen?).to be false
-
- description = described_class.new(address, replica)
- expect(description.last_update_time).to eq(obj)
- expect(obj.frozen?).to be false
- end
- end
- end
-
describe '#arbiters' do
context 'when the replica set has arbiters' do
|
RUBY-<I> Stop duplicating Time instances (#<I>)
|
mongodb_mongo-ruby-driver
|
train
|
38d4e7e0dad9fc28e6755ee06ae9a17005899975
|
diff --git a/parler/admin.py b/parler/admin.py
index <HASH>..<HASH> 100644
--- a/parler/admin.py
+++ b/parler/admin.py
@@ -14,9 +14,10 @@ from django.forms import Media
from django.forms.models import BaseInlineFormSet
from django.http import HttpResponseRedirect, Http404, HttpRequest
from django.shortcuts import render
-from django.utils.encoding import iri_to_uri, force_unicode
+from django.utils.encoding import iri_to_uri, force_text
from django.utils.functional import lazy
from django.utils.translation import ugettext_lazy as _, get_language
+from django.utils import six
from parler import appsettings
from parler.forms import TranslatableModelForm
from parler.managers import TranslatableQuerySet
@@ -385,12 +386,12 @@ class TranslatableAdmin(BaseTranslatableAdmin, admin.ModelAdmin):
if request.POST: # The user has already confirmed the deletion.
if perms_needed:
raise PermissionDenied
- obj_display = _('{0} translation of {1}').format(lang, force_unicode(translation)) # in hvad: (translation.master)
+ obj_display = _('{0} translation of {1}').format(lang, force_text(translation)) # in hvad: (translation.master)
self.log_deletion(request, translation, obj_display)
self.delete_model_translation(request, translation)
self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % dict(
- name=force_unicode(opts.verbose_name), obj=force_unicode(obj_display)
+ name=force_text(opts.verbose_name), obj=force_text(obj_display)
))
if self.has_change_permission(request, None):
@@ -398,7 +399,7 @@ class TranslatableAdmin(BaseTranslatableAdmin, admin.ModelAdmin):
else:
return HttpResponseRedirect(reverse('admin:index'))
- object_name = _('{0} Translation').format(force_unicode(opts.verbose_name))
+ object_name = _('{0} Translation').format(force_text(opts.verbose_name))
if perms_needed or protected:
title = _("Cannot delete %(name)s") % {"name": object_name}
else:
@@ -433,7 +434,7 @@ class TranslatableAdmin(BaseTranslatableAdmin, admin.ModelAdmin):
'opts': opts,
'app_label': opts.app_label,
'language_name': get_language_title(language_code),
- 'object_name': force_unicode(opts.verbose_name)
+ 'object_name': force_text(opts.verbose_name)
}
return render(request, self.deletion_not_allowed_template, context)
@@ -487,7 +488,7 @@ class TranslatableAdmin(BaseTranslatableAdmin, admin.ModelAdmin):
))
-_lazy_select_template_name = lazy(select_template_name, unicode)
+_lazy_select_template_name = lazy(select_template_name, six.text_type)
class TranslatableBaseInlineFormSet(BaseInlineFormSet):
diff --git a/parler/utils/i18n.py b/parler/utils/i18n.py
index <HASH>..<HASH> 100644
--- a/parler/utils/i18n.py
+++ b/parler/utils/i18n.py
@@ -73,4 +73,6 @@ def is_multilingual_project(site_id=None):
Whether the current Django project is configured for multilingual support.
"""
from parler import appsettings
- return appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS or appsettings.PARLER_LANGUAGES.has_key(site_id or settings.SITE_ID)
+ if site_id is None:
+ site_id = settings.SITE_ID
+ return appsettings.PARLER_SHOW_EXCLUDED_LANGUAGE_TABS or site_id in appsettings.PARLER_LANGUAGES
diff --git a/parler/utils/template.py b/parler/utils/template.py
index <HASH>..<HASH> 100644
--- a/parler/utils/template.py
+++ b/parler/utils/template.py
@@ -1,5 +1,6 @@
from django.template import TemplateDoesNotExist
from django.template.loader import find_template
+from django.utils import six
_cached_name_lookups = {}
@@ -21,8 +22,8 @@ def select_template_name(template_name_list):
except TemplateDoesNotExist:
continue
else:
- template_name = unicode(template_name) # consistent value for lazy() function.
+ template_name = six.text_type(template_name) # consistent value for lazy() function.
_cached_name_lookups[template_name_list] = template_name
return template_name
- return None
\ No newline at end of file
+ return None
|
a few more python3 fixes
|
django-parler_django-parler
|
train
|
6a21927f91a36cb766ab35f6cbb008f565b2d3c9
|
diff --git a/kconfiglib.py b/kconfiglib.py
index <HASH>..<HASH> 100644
--- a/kconfiglib.py
+++ b/kconfiglib.py
@@ -2455,16 +2455,20 @@ class Symbol(Item, _HasVisibility):
things will just work with regards to dependencies.
v -- The value to give to the symbol."""
+ old_user_val = self.user_val
+
self._set_value_no_invalidate(v, False)
- # There might be something more efficient you could do here, but play
- # it safe.
- if self.name == "MODULES":
- self.config._invalidate_all()
- return
+ # If the user value changed, invalidate all dependent symbols
+ if self.user_val != old_user_val:
+ # There might be something more efficient you could do here, but play
+ # it safe.
+ if self.name == "MODULES":
+ self.config._invalidate_all()
+ return
- self._invalidate()
- self._invalidate_dependent()
+ self._invalidate()
+ self._invalidate_dependent()
def reset(self):
"""Resets the value of the symbol, as if the symbol had never gotten a
|
Only invalidate if the user value actually changes.
|
ulfalizer_Kconfiglib
|
train
|
a4d85198dd1447a3739b72a043f3ec10af22eb68
|
diff --git a/telemetry/telemetry/page/page_runner.py b/telemetry/telemetry/page/page_runner.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/page/page_runner.py
+++ b/telemetry/telemetry/page/page_runner.py
@@ -55,16 +55,17 @@ class _RunState(object):
self._last_archive_path = page.archive_path
if self.browser.supports_tab_control:
- # Create a tab.
- if not self.tab:
- if len(self.browser.tabs) == 0:
- self.browser.tabs.New()
- self.tab = self.browser.tabs[0]
+ # Create a tab if there's none.
+ if len(self.browser.tabs) == 0:
+ self.browser.tabs.New()
# Ensure only one tab is open.
while len(self.browser.tabs) > 1:
self.browser.tabs[-1].Close()
+ if not self.tab:
+ self.tab = self.browser.tabs[0]
+
if self.first_page:
self.first_page = False
test.WillRunPageSet(self.tab)
|
[telemetry] Assign a tab even if there's no tab control.
I think this will fix Android WebView.
Small logic bug that was broken from <URL>
|
catapult-project_catapult
|
train
|
d251ad73c7ab13a31ea5f8115250e7abf98c2840
|
diff --git a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java
index <HASH>..<HASH> 100755
--- a/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java
+++ b/client/src/main/java/com/orientechnologies/orient/client/remote/OStorageRemote.java
@@ -488,6 +488,9 @@ public class OStorageRemote extends OStorageAbstract implements OStorageProxy, O
}
public void shutdown() {
+ if (status == STATUS.CLOSED || status == STATUS.CLOSING)
+ return;
+
stateLock.acquireWriteLock();
try {
if (status == STATUS.CLOSED)
|
add additional check for avoid deadlocks on push requests
|
orientechnologies_orientdb
|
train
|
8c9610c9842fd059d1c441794894161aad54e759
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -1,12 +1,17 @@
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
+from pathlib import Path
from setuptools import setup, find_packages
requires = ['itsdangerous', 'Jinja2', 'misaka>=2.0,<3.0', 'html5lib',
'werkzeug>=1.0', 'bleach', 'Flask-Caching>=1.9', 'Flask']
tests_require = ['pytest', 'pytest-cov']
+# https://packaging.python.org/en/latest/guides/making-a-pypi-friendly-readme/
+this_directory = Path(__file__).parent
+long_description = (this_directory / "README.md").read_text()
+
setup(
name='isso',
version='0.12.5',
@@ -18,6 +23,8 @@ setup(
url='https://github.com/posativ/isso/',
license='MIT',
description='lightweight Disqus alternative',
+ long_description=long_description,
+ long_description_content_type='text/markdown',
python_requires='>=3.5',
classifiers=[
"Development Status :: 4 - Beta",
|
setup.py: Include README in pypi upload
This allows for more information by embedding the README at
<URL>
|
posativ_isso
|
train
|
45753395f18376a92ce7651be9f9af44126315d6
|
diff --git a/ChangeLog b/ChangeLog
index <HASH>..<HASH> 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -25,6 +25,10 @@ Release Date: TBA
Close PyCQA/pylint#2326
Close PyCQA/pylint#2021
+* ``assert`` only functions are properly inferred as returning ``None``
+
+ Close #668
+
* Add support for Python 3.8's `NamedExpr` nodes, which is part of assignment expressions.
Close #674
diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py
index <HASH>..<HASH> 100644
--- a/astroid/scoped_nodes.py
+++ b/astroid/scoped_nodes.py
@@ -1656,7 +1656,13 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda):
first_return = next(returns, None)
if not first_return:
- raise exceptions.InferenceError("Empty return iterator")
+ if self.body and isinstance(self.body[-1], node_classes.Assert):
+ yield node_classes.Const(None)
+ return
+
+ raise exceptions.InferenceError(
+ "The function does not have any return statements"
+ )
for returnnode in itertools.chain((first_return,), returns):
if returnnode.value is None:
diff --git a/astroid/tests/unittest_inference.py b/astroid/tests/unittest_inference.py
index <HASH>..<HASH> 100644
--- a/astroid/tests/unittest_inference.py
+++ b/astroid/tests/unittest_inference.py
@@ -5289,5 +5289,19 @@ def test_ifexp_inference():
assert [third[0].value, third[1].value] == [1, 2]
+def test_assert_last_function_returns_none_on_inference():
+ code = """
+ def check_equal(a, b):
+ res = do_something_with_these(a, b)
+ assert a == b == res
+
+ check_equal(a, b)
+ """
+ node = extract_node(code)
+ inferred = next(node.infer())
+ assert isinstance(inferred, nodes.Const)
+ assert inferred.value is None
+
+
if __name__ == "__main__":
unittest.main()
|
``assert`` only functions are properly inferred as returning ``None``
Close #<I>
|
PyCQA_astroid
|
train
|
e28be58e5c37c926ac72008c710a44b185b573c2
|
diff --git a/lib/artifactory/version.rb b/lib/artifactory/version.rb
index <HASH>..<HASH> 100644
--- a/lib/artifactory/version.rb
+++ b/lib/artifactory/version.rb
@@ -1,3 +1,3 @@
module Artifactory
- VERSION = '0.0.1'
+ VERSION = '1.0.0'
end
|
Version bump to <I> for initial release
|
chef_artifactory-client
|
train
|
a7945371427d8c1f07cd4e13bc19e517e8ef0cc6
|
diff --git a/lib/gds_api/json_client.rb b/lib/gds_api/json_client.rb
index <HASH>..<HASH> 100644
--- a/lib/gds_api/json_client.rb
+++ b/lib/gds_api/json_client.rb
@@ -166,7 +166,7 @@ module GdsApi
end
def with_headers(method_params, headers)
- headers.merge!(govuk_request_id: GdsApi::GovukRequestId.value) if GdsApi::GovukRequestId.set?
+ headers = headers.merge(govuk_request_id: GdsApi::GovukRequestId.value) if GdsApi::GovukRequestId.set?
method_params.merge(
headers: method_params[:headers].merge(headers)
)
diff --git a/test/json_client_test.rb b/test/json_client_test.rb
index <HASH>..<HASH> 100644
--- a/test/json_client_test.rb
+++ b/test/json_client_test.rb
@@ -635,6 +635,15 @@ class JsonClientTest < MiniTest::Spec
end
end
+ def test_additional_headers_passed_in_do_not_get_modified
+ stub_request(:get, "http://some.other.endpoint/some.json").to_return(:status => 200)
+
+ headers = { 'HEADER-A' => 'A' }
+ GdsApi::JsonClient.new.get_json("http://some.other.endpoint/some.json", headers)
+
+ assert_equal({ 'HEADER-A' => 'A' }, headers)
+ end
+
def test_client_can_decompress_gzip_responses
url = "http://some.endpoint/some.json"
# {"test": "hello"}
|
Ensuring headers passed-in don't get modified
|
alphagov_gds-api-adapters
|
train
|
6a518b3d84d826bfbb2f325fcfb9267699930eea
|
diff --git a/src/server/pps/server/master.go b/src/server/pps/server/master.go
index <HASH>..<HASH> 100644
--- a/src/server/pps/server/master.go
+++ b/src/server/pps/server/master.go
@@ -451,7 +451,14 @@ For:
continue
}
if workersUp {
- if err := a.transitionPipelineState(ctx, op.name, op.ptr.State, pps.PipelineState_PIPELINE_RUNNING, ""); err != nil {
+ if err := a.transitionPipelineState(ctx, op.name,
+ pps.PipelineState_PIPELINE_CRASHING,
+ pps.PipelineState_PIPELINE_RUNNING, ""); err != nil {
+ if pte, ok := err.(ppsutil.PipelineTransitionError); ok &&
+ pte.Current == pps.PipelineState_PIPELINE_CRASHING {
+ log.Print(err) // Pipeline has moved to STOPPED or been updated--give up
+ return nil
+ }
log.Printf("error in monitorCrashingPipeline: %v", err)
continue
}
|
exit monitorCrashingPipeline if not crashing
|
pachyderm_pachyderm
|
train
|
86d4f9adab4d105095c22699f7f87dde81254044
|
diff --git a/Concentrate/Packer.php b/Concentrate/Packer.php
index <HASH>..<HASH> 100644
--- a/Concentrate/Packer.php
+++ b/Concentrate/Packer.php
@@ -24,7 +24,9 @@ class Concentrate_Packer
$filename = $root . DIRECTORY_SEPARATOR . $destinationFile;
- if (!is_writeable($filename)) {
+ if ( (!file_exists($filename) && !is_writable($root))
+ || (file_exists($filename) && !is_writable($filename))
+ ) {
throw new Concentrate_FileException(
"The file '{$filename}' could not be written."
);
|
Fix writable detection. If file does not exist, is_writable() returns false.
|
silverorange_Concentrate
|
train
|
07c408f30ae67653ea2459eac5124d7c57336181
|
diff --git a/default-input.js b/default-input.js
index <HASH>..<HASH> 100644
--- a/default-input.js
+++ b/default-input.js
@@ -176,4 +176,4 @@ if (!package.author) {
: prompt('author')
}
-exports.license = prompt('license', 'BSD')
+exports.license = prompt('license', 'BSD-2-Clause')
|
default license to BSD-2-Clause, rather than just 'BSD'
|
npm_init-package-json
|
train
|
7d225563bd123cdd86e5c6d1930c2bcf6f97ee83
|
diff --git a/mod/forum/lib.php b/mod/forum/lib.php
index <HASH>..<HASH> 100644
--- a/mod/forum/lib.php
+++ b/mod/forum/lib.php
@@ -3823,26 +3823,16 @@ function forum_user_can_post_discussion($forum, $currentgroup=-1, $groupmode=-1,
// $forum is an object
global $USER, $SESSION, $COURSE;
- // shortcut - guest and not-logged-in users can not post
- if (isguestuser() or !isloggedin()) {
- return false;
+ if (!$cm) {
+ debugging('missing cm', DEBUG_DEVELOPER);
+ if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
+ error('Course Module ID was incorrect');
+ }
}
-
if (!$context) {
- if (!$cm) {
- debugging('missing cm', DEBUG_DEVELOPER);
- if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
- error('Course Module ID was incorrect');
- }
- }
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
}
- // normal users with temporary guest access can not add discussions
- if (has_capability('moodle/legacy:guest', $context, $USER->id, false)) {
- return false;
- }
-
if ($currentgroup == -1) {
$currentgroup = get_current_group($cm->course);
}
@@ -3891,15 +3881,6 @@ function forum_user_can_post_discussion($forum, $currentgroup=-1, $groupmode=-1,
* @param $user - user object
*/
function forum_user_can_post($forum, $user=NULL, $cm=NULL, $context=NULL) {
- global $USER;
- if (empty($user)) {
- $user = $USER;
- }
-
- // shortcut - guest and not-logged-in users can not post
- if (isguestuser($user) or empty($user->id)) {
- return false;
- }
if (!$context) {
if (!$cm) {
@@ -3911,18 +3892,21 @@ function forum_user_can_post($forum, $user=NULL, $cm=NULL, $context=NULL) {
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
}
- // normal users with temporary guest access can not post
- if (has_capability('moodle/legacy:guest', $context, $user->id, false)) {
- return false;
- }
-
if ($forum->type == 'news') {
$capname = 'mod/forum:replynews';
} else {
$capname = 'mod/forum:replypost';
}
- return has_capability($capname, $context, $user->id, false);
+ if (!empty($user)) {
+ $canreply = has_capability($capname, $context, $user->id, false)
+ && !has_capability('moodle/legacy:guest', $context, $user->id, false);
+ } else {
+ $canreply = has_capability($capname, $context, NULL, false)
+ && !has_capability('moodle/legacy:guest', $context, NULL, false);
+ }
+
+ return $canreply;
}
@@ -4110,7 +4094,7 @@ function forum_print_latest_discussions($course, $forum, $maxdiscussions=5, $dis
// and the current user is a guest.
if (forum_user_can_post_discussion($forum, $currentgroup, $groupmode, $cm, $context) ||
- ($forum->type != 'news' and (isguestuser() or !isloggedin())) ) {
+ ($forum->type != 'news' && has_capability('moodle/legacy:guest', $context, NULL, false)) ) {
echo '<div class="singlebutton forumaddnew">';
echo "<form id=\"newdiscussionform\" method=\"get\" action=\"$CFG->wwwroot/mod/forum/post.php\">";
|
Merged MDL-<I> (5) revert in <I>
|
moodle_moodle
|
train
|
de9f76cdceebbd86f3ca47c967a58c57411f0655
|
diff --git a/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_binary.py b/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_binary.py
index <HASH>..<HASH> 100644
--- a/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_binary.py
+++ b/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_binary.py
@@ -14,19 +14,14 @@ from pants.contrib.cpp.targets.cpp_target import CppTarget
class CppBinary(CppTarget):
"""A C++ binary."""
- def __init__(self,
- libraries=None,
- *args,
- **kwargs):
+ def __init__(self, libraries=None, payload=None, **kwargs):
"""
:param libraries: Libraries that this target depends on that are not pants targets.
For example, 'm' or 'rt' that are expected to be installed on the local system.
:type libraries: List of libraries to link against.
"""
- payload = Payload()
- payload.add_fields({
- 'libraries': PrimitiveField(libraries)
- })
+ payload = payload or Payload()
+ payload.add_field('libraries', PrimitiveField(libraries))
super(CppBinary, self).__init__(payload=payload, **kwargs)
@property
diff --git a/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_library.py b/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_library.py
index <HASH>..<HASH> 100644
--- a/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_library.py
+++ b/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_library.py
@@ -10,9 +10,3 @@ from pants.contrib.cpp.targets.cpp_target import CppTarget
class CppLibrary(CppTarget):
"""A statically linked C++ library."""
-
- # TODO: public headers
- def __init__(self,
- *args,
- **kwargs):
- super(CppLibrary, self).__init__(*args, **kwargs)
diff --git a/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_target.py b/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_target.py
index <HASH>..<HASH> 100644
--- a/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_target.py
+++ b/contrib/cpp/src/python/pants/contrib/cpp/targets/cpp_target.py
@@ -14,14 +14,12 @@ class CppTarget(Target):
def __init__(self, address=None, payload=None, sources=None, **kwargs):
"""
- :param sources: Source code files to build. Paths are relative to the BUILD
- file's directory.
- :type sources: ``Fileset`` (from globs or rglobs) or list of strings
+ :param sources: Source code files to build. Paths are relative to the BUILD file's directory.
+ :type sources: :class:`pants.source.wrapped_globs.FilesetWithSpec` (from globs or rglobs) or
+ list of strings
"""
payload = payload or Payload()
- payload.add_fields({
- 'sources': self.create_sources_field(sources=sources,
- sources_rel_path=address.spec_path,
- key_arg='sources'),
- })
+ payload.add_field('sources', self.create_sources_field(sources=sources,
+ sources_rel_path=address.spec_path,
+ key_arg='sources'))
super(CppTarget, self).__init__(address=address, payload=payload, **kwargs)
|
Cleanup cpp targets. (#<I>)
Noticed working #<I>.
|
pantsbuild_pants
|
train
|
79b3c4759ccab41e3695438796eac488bb670a47
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "metalsmith-prismic-server",
- "version": "0.0.15",
+ "version": "0.1.0",
"description": "server to compile and preview static sites from prismic.io content",
"main": "index.js",
"scripts": {
@@ -22,10 +22,10 @@
"lodash": "^4.5.1",
"metalsmith": "^2.1.0",
"metalsmith-express": "^0.1.0",
- "metalsmith-prismic": "^0.10.0",
+ "metalsmith-prismic": "git://github.com/aeirola/metalsmith-prismic.git",
"metalsmith-watch": "^1.0.1",
"open": "0.0.5",
- "prismic.io": "git://github.com/ds300/javascript-kit.git#master",
+ "prismic.io": "^2.1.1",
"promise": "^7.1.1",
"request": "^2.69.0"
},
diff --git a/src/build.js b/src/build.js
index <HASH>..<HASH> 100644
--- a/src/build.js
+++ b/src/build.js
@@ -2,9 +2,9 @@ const metalsmith = require('./metalsmith')
const path = require('path');
const DEFAULT_CONFIG = require('./config');
-function build(config, cb) {
+function build(config, modes, cb) {
config = Object.assign({}, DEFAULT_CONFIG, config);
- metalsmith(config, 'build')
+ metalsmith(config, modes)
.destination(path.join(config.buildPath, "master"))
.build(cb);
}
diff --git a/src/config.js b/src/config.js
index <HASH>..<HASH> 100644
--- a/src/config.js
+++ b/src/config.js
@@ -54,10 +54,14 @@ module.exports = {
*/
dev: [],
/**
- * plugins only used for the build task of the prod server
+ * plugins used when building the master project
*/
build: [],
/**
+ * plugins only used by the live production server
+ */
+ deploy: [],
+ /**
* plugins only used for the preview task of the prod server
*/
preview: []
diff --git a/src/metalsmith.js b/src/metalsmith.js
index <HASH>..<HASH> 100644
--- a/src/metalsmith.js
+++ b/src/metalsmith.js
@@ -1,21 +1,27 @@
const metalsmith = require('metalsmith');
const prismic = require('metalsmith-prismic');
-function metalsmithPrismic (config, mode) {
+function metalsmithPrismic (config, modes) {
const smith = metalsmith(config.inputPath)
.use(prismic({
url: config.prismicUrl,
accessToken: config.prismicToken,
release: config.release,
- linkResolver: config.linkResolver
+ linkResolver: config.prismicLinkResolver
}));
const commonPlugins = config.plugins.common || [];
- const modePlugins = config.plugins[mode] || [];
commonPlugins.forEach(smith.use.bind(smith));
- modePlugins.forEach(smith.use.bind(smith));
+ if (typeof modes === 'string') {
+ modes = [modes];
+ }
+ modes
+ // get plugin objects
+ .map(m => config.plugins[m] || [])
+ // use them
+ .forEach(plugins => plugins.forEach(smith.use.bind(smith)));
return smith;
};
diff --git a/src/prod-server.js b/src/prod-server.js
index <HASH>..<HASH> 100644
--- a/src/prod-server.js
+++ b/src/prod-server.js
@@ -54,7 +54,7 @@ function buildRoute(app, config) {
} else if (config.prismicUrl !== req.body.apiUrl) {
reject(res, "mismatching api url");
} else {
- build(config, err => {
+ build(config, ['build', 'deploy'], err => {
if (err) {
console.error("Build Failed", err);
reject(res, "compilation error");
|
multiple modes, linkResolver fix
|
futurice_metalsmith-prismic-server
|
train
|
ddfa8ae79d5c21f8a0afba620d3d092155ead045
|
diff --git a/src/main/java/org/codehaus/mojo/build/CreateMojo.java b/src/main/java/org/codehaus/mojo/build/CreateMojo.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/codehaus/mojo/build/CreateMojo.java
+++ b/src/main/java/org/codehaus/mojo/build/CreateMojo.java
@@ -61,6 +61,9 @@ import org.apache.maven.scm.repository.ScmRepository;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.StringUtils;
+import static java.lang.Boolean.parseBoolean;
+import static java.lang.Integer.parseInt;
+
/**
* This mojo is designed to give you a build number. So when you might make 100 builds of version 1.0-SNAPSHOT, you can
* differentiate between them all.
@@ -310,7 +313,7 @@ public class CreateMojo
{
buildNumberString = "0";
}
- int buildNumber = Integer.valueOf( buildNumberString ).intValue();
+ int buildNumber = parseInt( buildNumberString );
// store the increment
properties.setProperty( s, String.valueOf( ++buildNumber ) );
@@ -730,7 +733,7 @@ public class CreateMojo
if ( doCheckSystemProperty != null )
{
// well, this gets the final say
- this.doCheck = Boolean.valueOf( doCheckSystemProperty ).booleanValue();
+ this.doCheck = parseBoolean( doCheckSystemProperty );
}
else
{
@@ -744,7 +747,7 @@ public class CreateMojo
if ( doUpdateSystemProperty != null )
{
// well, this gets the final say
- this.doUpdate = Boolean.valueOf( doUpdateSystemProperty ).booleanValue();
+ this.doUpdate = parseBoolean( doUpdateSystemProperty );
}
else
{
|
Use parse methods.
Primitives should be created from Strings by the parse method.
|
mojohaus_buildnumber-maven-plugin
|
train
|
b68b3737d77fa635944cb185b56996faa5c21b04
|
diff --git a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java
index <HASH>..<HASH> 100644
--- a/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java
+++ b/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java
@@ -45,8 +45,8 @@ public class Sanitizer {
private static final String[] REGEX_PARTS = { "*", "$", "^", "+" };
private static final Set<String> DEFAULT_KEYS_TO_SANITIZE = new LinkedHashSet<>(
- Arrays.asList("password", "secret", "key", "token", ".*credentials.*", "vcap_services", "sun.java.command",
- "^spring[\\._]application[\\\\._]json$"));
+ Arrays.asList("password", "secret", "key", "token", ".*credentials.*", "vcap_services",
+ "^vcap\\.services.*$", "sun.java.command", "^spring[\\._]application[\\\\._]json$"));
private static final Set<String> URI_USERINFO_KEYS = new LinkedHashSet<>(
Arrays.asList("uri", "uris", "address", "addresses"));
diff --git a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java
index <HASH>..<HASH> 100644
--- a/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java
+++ b/spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/endpoint/SanitizerTests.java
@@ -48,6 +48,8 @@ class SanitizerTests {
assertThat(sanitizer.sanitize("sun.java.command", "--spring.redis.password=pa55w0rd")).isEqualTo("******");
assertThat(sanitizer.sanitize("SPRING_APPLICATION_JSON", "{password:123}")).isEqualTo("******");
assertThat(sanitizer.sanitize("spring.application.json", "{password:123}")).isEqualTo("******");
+ assertThat(sanitizer.sanitize("VCAP_SERVICES", "{json}")).isEqualTo("******");
+ assertThat(sanitizer.sanitize("vcap.services.db.codeword", "secret")).isEqualTo("******");
}
@ParameterizedTest(name = "key = {0}")
|
Sanitize flattened VCAP_SERVICES properties
Update `Sanitizer` to also include flattened `vcap.services.*`
properties.
Fixes gh-<I>
|
spring-projects_spring-boot
|
train
|
f56745f097c25007e40428a655c89f87a1487a8f
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -26,7 +26,7 @@ class BinaryDistribution(Distribution):
def is_pure(self):
return False
-if "download_mmd" in sys.argv:
+if "download_mmd" in sys.argv and "bdist_wheel" in sys.argv:
sys.argv.append('--plat-name')
sys.argv.append(get_platform())
|
Add --plat-name argument only during wheel generation
|
jasedit_pymmd
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.