hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
150be0dfd0cd588ba3ca93f07b3d8f9bb254f417
|
diff --git a/mod/forum/index.php b/mod/forum/index.php
index <HASH>..<HASH> 100644
--- a/mod/forum/index.php
+++ b/mod/forum/index.php
@@ -92,8 +92,13 @@
foreach ($forums as $forum) {
- $cm = get_coursemodule_from_instance("forum", $forum->id, $course->id);
- $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+ if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
+ continue; // Shouldn't happen
+ }
+
+ if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
+ continue; // Shouldn't happen
+ }
if (!has_capability('mod/forum:viewdiscussion', $context)) {
if (isset($forum->keyreference)) {
@@ -158,8 +163,12 @@
if ($generalforums) {
foreach ($generalforums as $forum) {
- $cm = get_coursemodule_from_instance("forum", $forum->id, $course->id);
- $context = get_context_instance(CONTEXT_MODULE, $cm->id);
+ if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
+ continue; // Shouldn't happen
+ }
+ if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
+ continue; // Shouldn't happen
+ }
if (!groups_course_module_visible($cm)) {
continue;
@@ -294,7 +303,11 @@
if ($learningforums) {
$currentsection = "";
foreach ($learningforums as $key => $forum) {
- $cm = get_coursemodule_from_instance("forum", $forum->id, $course->id);
+
+ if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
+ continue; // Shouldn't happen
+ }
+
if (!coursemodule_visible_for_user($cm)) {
continue;
}
|
MDL-<I> Merged return checking from stable <I>
|
moodle_moodle
|
train
|
e0370edde3ec17066cf40ddac8a1c625c3fc9e09
|
diff --git a/test/12-integration-tests.js b/test/12-integration-tests.js
index <HASH>..<HASH> 100644
--- a/test/12-integration-tests.js
+++ b/test/12-integration-tests.js
@@ -549,7 +549,7 @@ describe('Integration tests', () => {
});
describe('Node security project audit', () => {
- it.only('Should fail if there are vulnerable dependencies', () =>
+ it('Should fail if there are vulnerable dependencies', () =>
exec('git checkout master')
.then(() => pkgd())
.then((pkgInfo) => {
@@ -577,9 +577,9 @@ describe('Integration tests', () => {
/* prettier-ignore */
nodeInfos.isAtLeastNpm6
? assert(err.message.indexOf('Vulnerability found') > -1)
- : err.message.indexOf('You do not have permission to publish') > -1 ||
+ : assert(err.message.indexOf('You do not have permission to publish') > -1 ||
err.message.indexOf('auth required for publishing') > -1 ||
- err.message.indexOf('operation not permitted') > -1
+ err.message.indexOf('operation not permitted') > -1)
));
['publish-please@2.4.1', 'testcafe@0.19.2'].forEach(function(
dependency
@@ -608,11 +608,14 @@ describe('Integration tests', () => {
.then(() => {
throw new Error('Promise rejection expected');
})
- .catch((err) =>
- assert(
- // prettier-ignore
- err.message.indexOf(`Vulnerability found in ${chalk.bold(dependency)}`) > -1
- )
+ .catch(
+ (err) =>
+ /* prettier-ignore */
+ nodeInfos.isAtLeastNpm6
+ ? assert(err.message.indexOf(`Vulnerability found in ${chalk.bold(dependency)}`) > -1)
+ : assert(err.message.indexOf('You do not have permission to publish') > -1 ||
+ err.message.indexOf('auth required for publishing') > -1 ||
+ err.message.indexOf('operation not permitted') > -1)
));
});
@@ -641,11 +644,14 @@ describe('Integration tests', () => {
.then(() => {
throw new Error('Promise rejection expected');
})
- .catch((err) =>
- assert(
- // prettier-ignore
- err.message.indexOf(`Vulnerability found in ${chalk.red.bold(dependency)}`) > -1
- )
+ .catch(
+ (err) =>
+ /* prettier-ignore */
+ nodeInfos.isAtLeastNpm6
+ ? assert(err.message.indexOf(`Vulnerability found in ${chalk.red.bold(dependency)}`) > -1)
+ : assert(err.message.indexOf('You do not have permission to publish') > -1 ||
+ err.message.indexOf('auth required for publishing') > -1 ||
+ err.message.indexOf('operation not permitted') > -1)
));
});
@@ -707,11 +713,14 @@ describe('Integration tests', () => {
.then(() => {
throw new Error('Promise rejection expected');
})
- .catch((err) =>
- assert(
- // prettier-ignore
- err.message.indexOf(`Vulnerability found in ${chalk.red.bold('lodash@4.16.4')}`) > -1
- )
+ .catch(
+ (err) =>
+ /* prettier-ignore */
+ nodeInfos.isAtLeastNpm6
+ ? assert(err.message.indexOf(`Vulnerability found in ${chalk.red.bold('lodash@4.16.4')}`) > -1)
+ : assert(err.message.indexOf('You do not have permission to publish') > -1 ||
+ err.message.indexOf('auth required for publishing') > -1 ||
+ err.message.indexOf('operation not permitted') > -1)
));
['lodash@4.17.5', 'ms@0.7.1'].forEach(function(dependency) {
@@ -822,10 +831,21 @@ describe('Integration tests', () => {
throw new Error('Promise rejection expected');
})
.catch((err) => {
- const errors = err.message
- .split('\n')
- .filter((msg) => msg.startsWith(' * '));
- return assert(errors.length === 2);
+ /* prettier-ignore */
+ if (nodeInfos.isAtLeastNpm6) {
+ const errors = err.message
+ .split('\n')
+ .filter((msg) => msg.startsWith(' * '));
+
+ return assert(errors.length === 2);
+ }
+
+ return assert(
+ // prettier-ignore
+ err.message.indexOf('You do not have permission to publish') > -1 ||
+ err.message.indexOf('auth required for publishing') > -1 ||
+ err.message.indexOf('operation not permitted') > -1
+ );
}));
it('Should not perform check if vulnerableDependencies-validation is disabled', () =>
|
test(validation): try fix test on npm version < 6
|
inikulin_publish-please
|
train
|
26acc47c795559ad712672c8aa0c2a1fdcb34f20
|
diff --git a/lib/aws-cloudwatch-statsd-backend.js b/lib/aws-cloudwatch-statsd-backend.js
index <HASH>..<HASH> 100644
--- a/lib/aws-cloudwatch-statsd-backend.js
+++ b/lib/aws-cloudwatch-statsd-backend.js
@@ -81,9 +81,13 @@ console.log(new Date(timestamp*1000).toISOString());
sum = cumulativeValues[count-1];
mean = sum / count;
+ names = this.config.processKeyForNamespace ? this.processKey(key) : {};
+ var namespace = this.config.namespace || names.namespace || "AwsCloudWatchStatsdBackend";
+ var metricName = this.config.metricName || names.metricName || key;
+
cloudwatch.PutMetricData({
MetricData : [{
- MetricName : key,
+ MetricName : metricName,
Unit : 'Milliseconds',
Timestamp: new Date(timestamp*1000).toISOString(),
StatisticValues: {
@@ -104,9 +108,13 @@ console.log(new Date(timestamp*1000).toISOString());
}
for (key in gauges) {
+ names = this.config.processKeyForNamespace ? this.processKey(key) : {};
+ var namespace = this.config.namespace || names.namespace || "AwsCloudWatchStatsdBackend";
+ var metricName = this.config.metricName || names.metricName || key;
+
cloudwatch.PutMetricData({
MetricData : [{
- MetricName : key,
+ MetricName : metricName,
Unit : 'None',
Timestamp: new Date(timestamp*1000).toISOString(),
Value : gauges[key]
@@ -120,9 +128,13 @@ console.log(new Date(timestamp*1000).toISOString());
}
for (key in sets) {
+ names = this.config.processKeyForNamespace ? this.processKey(key) : {};
+ var namespace = this.config.namespace || names.namespace || "AwsCloudWatchStatsdBackend";
+ var metricName = this.config.metricName || names.metricName || key;
+
cloudwatch.PutMetricData({
MetricData : [{
- MetricName : key,
+ MetricName : metricName,
Unit : 'None',
Timestamp: new Date(timestamp*1000).toISOString(),
Value : sets[key].values().length
|
Recent config support to gausges, sets, timer.s
|
camitz_aws-cloudwatch-statsd-backend
|
train
|
42660e73668921c5c5a96346ab50e2aa8b7ef18a
|
diff --git a/src/main/java/org/jboss/pressgang/ccms/rest/v1/jaxrsinterfaces/RESTBaseInterfaceV1.java b/src/main/java/org/jboss/pressgang/ccms/rest/v1/jaxrsinterfaces/RESTBaseInterfaceV1.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jboss/pressgang/ccms/rest/v1/jaxrsinterfaces/RESTBaseInterfaceV1.java
+++ b/src/main/java/org/jboss/pressgang/ccms/rest/v1/jaxrsinterfaces/RESTBaseInterfaceV1.java
@@ -1766,13 +1766,13 @@ public interface RESTBaseInterfaceV1 {
@GET
@Path("/image/get/raw/{id}")
@Consumes({ "*" })
- @Produces({"image/gif", "image/png", "image/png", MediaType.APPLICATION_SVG_XML})
+ @Produces({"image/gif", "image/png", "image/jpeg", MediaType.APPLICATION_SVG_XML})
public byte[] getRAWImage(@PathParam("id") final Integer id, @QueryParam("lang") final String locale) throws InvalidParameterException, InternalProcessingException;
@GET
@Path("/image/get/raw/{id}/thumbnail")
@Consumes({ "*" })
- @Produces({"image/gif", "image/png", "image/png", MediaType.APPLICATION_SVG_XML})
+ @Produces({"image/gif", "image/png", "image/jpeg", MediaType.APPLICATION_SVG_XML})
public byte[] getRAWImageThumbnail(@PathParam("id") final Integer id, @QueryParam("lang") final String locale) throws InvalidParameterException, InternalProcessingException;
/* TOPIC FUNCTIONS */
|
Fixed issue with not setting the content-type header for jpeg images.
|
pressgang-ccms_PressGangCCMSRESTv1Common
|
train
|
9fc847558676adab876c329d0691b5075801f0d7
|
diff --git a/src/ol/PluggableMap.js b/src/ol/PluggableMap.js
index <HASH>..<HASH> 100644
--- a/src/ol/PluggableMap.js
+++ b/src/ol/PluggableMap.js
@@ -464,6 +464,10 @@ class PluggableMap extends BaseObject {
}
+ /**
+ * @abstract
+ * @return {import("./renderer/Map.js").default} The map renderer
+ */
createRenderer() {
throw new Error('Use a map type that has a createRenderer method');
}
@@ -565,7 +569,8 @@ class PluggableMap extends BaseObject {
return;
}
const coordinate = this.getCoordinateFromPixel(pixel);
- opt_options = opt_options !== undefined ? opt_options : {};
+ opt_options = opt_options !== undefined ? opt_options :
+ /** @type {AtPixelOptions} */ ({});
const hitTolerance = opt_options.hitTolerance !== undefined ?
opt_options.hitTolerance * this.frameState_.pixelRatio : 0;
const layerFilter = opt_options.layerFilter !== undefined ?
@@ -637,7 +642,8 @@ class PluggableMap extends BaseObject {
return false;
}
const coordinate = this.getCoordinateFromPixel(pixel);
- opt_options = opt_options !== undefined ? opt_options : {};
+ opt_options = opt_options !== undefined ? opt_options :
+ /** @type {AtPixelOptions} */ ({});
const layerFilter = opt_options.layerFilter !== undefined ? opt_options.layerFilter : TRUE;
const hitTolerance = opt_options.hitTolerance !== undefined ?
opt_options.hitTolerance * this.frameState_.pixelRatio : 0;
@@ -663,7 +669,10 @@ class PluggableMap extends BaseObject {
*/
getEventPixel(event) {
const viewportPosition = this.viewport_.getBoundingClientRect();
- const eventPosition = event.changedTouches ? event.changedTouches[0] : event;
+ const eventPosition = 'changedTouches' in event ?
+ /** @type {TouchEvent} */ (event).changedTouches[0] :
+ /** @type {MouseEvent} */ (event);
+
return [
eventPosition.clientX - viewportPosition.left,
eventPosition.clientY - viewportPosition.top
@@ -1059,7 +1068,7 @@ class PluggableMap extends BaseObject {
}
const view = this.getView();
if (view) {
- this.viewport_.setAttribute('data-view', getUid(view));
+ this.viewport_.setAttribute('data-view', getUid(view).toString());
this.viewPropertyListenerKey_ = listen(
view, ObjectEventType.PROPERTYCHANGE,
this.handleViewPropertyChanged_, this);
@@ -1423,10 +1432,12 @@ function getLoading(layers) {
const layer = layers[i];
if (layer instanceof LayerGroup) {
return getLoading(layer.getLayers().getArray());
- }
- const source = layers[i].getSource();
- if (source && source.loading) {
- return true;
+ } else {
+ const source = /** @type {import("./layer/Layer.js").default} */ (
+ layer).getSource();
+ if (source && source.loading) {
+ return true;
+ }
}
}
return false;
|
Fix type check in ol/PluggableMap.js
- Added JSDoc to getRenderer()
- Cast default options to types
- Cast event to MouseEvent to satisfy tsc. Non mouse/touch events
will simply produce [NaN, NaN]
- Cast to Layer before calling getSource(), as it does not exist
on Base
|
openlayers_openlayers
|
train
|
79ca0ae03ff479e24b0200a72347e7d631390059
|
diff --git a/mungegithub/mungers/sync/issue-sync.go b/mungegithub/mungers/sync/issue-sync.go
index <HASH>..<HASH> 100644
--- a/mungegithub/mungers/sync/issue-sync.go
+++ b/mungegithub/mungers/sync/issue-sync.go
@@ -35,23 +35,18 @@ const (
// PriorityFailingTest represents a failing or flaking test
- PriorityFailingTest = Priority(2)
+ PriorityFailingTest = Priority("priority/failing-test")
)
// RobotUser is a set of name of robot user
var RobotUser = sets.NewString(JenkinsBotName, BotName)
// Priority represents the priority label in an issue
-type Priority int
+type Priority string
// String return the priority label in string
func (p Priority) String() string {
- return fmt.Sprintf(priorityPrefix+"%d", p)
-}
-
-// Priority returns the priority in int
-func (p Priority) Priority() int {
- return int(p)
+ return string(p)
}
// OwnerMapper finds an owner for a given test name.
|
Changed issue-sync.Priority type to a const of string
|
kubernetes_test-infra
|
train
|
d8dd114a169b4694eb403f4cabdd686d421f1459
|
diff --git a/packages/table/src/table-body.js b/packages/table/src/table-body.js
index <HASH>..<HASH> 100644
--- a/packages/table/src/table-body.js
+++ b/packages/table/src/table-body.js
@@ -136,6 +136,14 @@ export default {
return this.store.states.columns.length;
},
+ leftFixedLeafCount() {
+ return this.store.states.fixedLeafColumnsLength;
+ },
+
+ rightFixedLeafCount() {
+ return this.store.states.rightFixedLeafColumnsLength;
+ },
+
leftFixedCount() {
return this.store.states.fixedColumns.length;
},
@@ -170,11 +178,11 @@ export default {
isColumnHidden(index) {
if (this.fixed === true || this.fixed === 'left') {
- return index >= this.leftFixedCount;
+ return index >= this.leftFixedLeafCount;
} else if (this.fixed === 'right') {
- return index < this.columnsCount - this.rightFixedCount;
+ return index < this.columnsCount - this.rightFixedLeafCount;
} else {
- return (index < this.leftFixedCount) || (index >= this.columnsCount - this.rightFixedCount);
+ return (index < this.leftFixedLeafCount) || (index >= this.columnsCount - this.rightFixedLeafCount);
}
},
diff --git a/packages/table/src/table-header.js b/packages/table/src/table-header.js
index <HASH>..<HASH> 100644
--- a/packages/table/src/table-header.js
+++ b/packages/table/src/table-header.js
@@ -188,6 +188,14 @@ export default {
return this.store.states.rightFixedColumns.length;
},
+ leftFixedLeafCount() {
+ return this.store.states.fixedLeafColumnsLength;
+ },
+
+ rightFixedLeafCount() {
+ return this.store.states.rightFixedLeafColumnsLength;
+ },
+
columns() {
return this.store.states.columns;
},
@@ -234,16 +242,17 @@ export default {
methods: {
isCellHidden(index, columns) {
+ let start = 0;
+ for (let i = 0; i < index; i++) {
+ start += columns[i].colSpan;
+ }
+ const after = start + columns[index].colSpan - 1;
if (this.fixed === true || this.fixed === 'left') {
- return index >= this.leftFixedCount;
+ return after >= this.leftFixedLeafCount;
} else if (this.fixed === 'right') {
- let before = 0;
- for (let i = 0; i < index; i++) {
- before += columns[i].colSpan;
- }
- return before < this.columnsCount - this.rightFixedCount;
+ return start < this.columnsCount - this.rightFixedLeafCount;
} else {
- return (index < this.leftFixedCount) || (index >= this.columnsCount - this.rightFixedCount);
+ return (after < this.leftFixedLeafCount) || (start >= this.columnsCount - this.rightFixedLeafCount);
}
},
diff --git a/packages/table/src/table-store.js b/packages/table/src/table-store.js
index <HASH>..<HASH> 100644
--- a/packages/table/src/table-store.js
+++ b/packages/table/src/table-store.js
@@ -56,6 +56,9 @@ const TableStore = function(table, initialState = {}) {
columns: [],
fixedColumns: [],
rightFixedColumns: [],
+ leafColumns: [],
+ fixedLeafColumns: [],
+ rightFixedLeafColumns: [],
isComplex: false,
_data: null,
filteredData: null,
@@ -322,8 +325,19 @@ TableStore.prototype.updateColumns = function() {
_columns[0].fixed = true;
states.fixedColumns.unshift(_columns[0]);
}
- states.originColumns = [].concat(states.fixedColumns).concat(_columns.filter((column) => !column.fixed)).concat(states.rightFixedColumns);
- states.columns = doFlattenColumns(states.originColumns);
+
+ const notFixedColumns = _columns.filter(column => !column.fixed);
+ states.originColumns = [].concat(states.fixedColumns).concat(notFixedColumns).concat(states.rightFixedColumns);
+
+ const leafColumns = doFlattenColumns(notFixedColumns);
+ const fixedLeafColumns = doFlattenColumns(states.fixedColumns);
+ const rightFixedLeafColumns = doFlattenColumns(states.rightFixedColumns);
+
+ states.leafColumnsLength = leafColumns.length;
+ states.fixedLeafColumnsLength = fixedLeafColumns.length;
+ states.rightFixedLeafColumnsLength = rightFixedLeafColumns.length;
+
+ states.columns = [].concat(fixedLeafColumns).concat(leafColumns).concat(rightFixedLeafColumns);
states.isComplex = states.fixedColumns.length > 0 || states.rightFixedColumns.length > 0;
};
|
Table: Fix error in cacluating hidden in `table-header` and `table-body`
|
ElemeFE_element
|
train
|
cc481ca1bdcd9e8bc3a2187944efcfbaed6a8f51
|
diff --git a/src/test/java/io/nats/client/impl/DrainTests.java b/src/test/java/io/nats/client/impl/DrainTests.java
index <HASH>..<HASH> 100644
--- a/src/test/java/io/nats/client/impl/DrainTests.java
+++ b/src/test/java/io/nats/client/impl/DrainTests.java
@@ -513,26 +513,31 @@ public class DrainTests {
assertTrue("Connected Status", Connection.Status.CONNECTED == pubCon.getStatus());
final int total = 5_000;
- final int sleepBetweenDrains = 10;
+ final Duration sleepBetweenDrains = Duration.ofMillis(250);
+ final Duration sleepBetweenMessages = Duration.ofMillis(1);
+ final Duration testTimeout = Duration.ofMillis(5 * total * sleepBetweenMessages.toMillis());
+ final Duration drainTimeout = testTimeout;
+ final Duration waitTimeout = drainTimeout.plusSeconds(1);
AtomicInteger count = new AtomicInteger();
Instant start = Instant.now();
Instant now = start;
Connection working = null;
- Connection draining = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build());
NatsDispatcher workingD = null;
NatsDispatcher drainingD = null;
+ Connection draining = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build());
assertTrue("Connected Status", Connection.Status.CONNECTED == draining.getStatus());
drainingD = (NatsDispatcher) draining.createDispatcher((msg) -> {
count.incrementAndGet();
}).subscribe("draintest", "queue");
+ draining.flush(Duration.ofSeconds(5));
Thread pubThread = new Thread(() -> {
for (int i = 0; i < total; i++) {
pubCon.publish("draintest", null);
try {
- LockSupport.parkNanos(1000); // use a nice stead pace to avoid slow consumers
+ LockSupport.parkNanos(sleepBetweenMessages.toNanos()); // use a nice stead pace to avoid slow consumers
} catch (Exception e) {
}
@@ -546,23 +551,24 @@ public class DrainTests {
pubThread.start();
- while (count.get() < total && Duration.between(start, now).toMillis() < 20_000) {
+ while (count.get() < total && Duration.between(start, now).compareTo(testTimeout) < 0) {
working = Nats.connect(new Options.Builder().server(ts.getURI()).maxReconnects(0).build());
assertTrue("Connected Status", Connection.Status.CONNECTED == working.getStatus());
workingD = (NatsDispatcher) working.createDispatcher((msg) -> {
count.incrementAndGet();
}).subscribe("draintest", "queue");
+ working.flush(Duration.ofSeconds(5));
try {
- LockSupport.parkNanos(1_000_000 * sleepBetweenDrains); // let them both work a bit
+ LockSupport.parkNanos(sleepBetweenDrains.toNanos()); // let them both work a bit
} catch (Exception e) {
}
- CompletableFuture<Boolean> tracker = draining.drain(Duration.ofSeconds(9));
+ CompletableFuture<Boolean> tracker = draining.drain(drainTimeout);
- assertTrue(tracker.get(10, TimeUnit.SECONDS)); // wait for the drain to complete
+ assertTrue(tracker.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS)); // wait for the drain to complete
assertTrue(drainingD.isDrained());
assertTrue(((NatsConnection) draining).isDrained());
draining.close(); // no op, but ide wants this for auto-closable
|
Continuing to clean up drain/queue test for travis.
|
nats-io_java-nats
|
train
|
cfda9dcaea8015297d6364a7025f09092a590d44
|
diff --git a/app/models/fluentd/agent/common.rb b/app/models/fluentd/agent/common.rb
index <HASH>..<HASH> 100644
--- a/app/models/fluentd/agent/common.rb
+++ b/app/models/fluentd/agent/common.rb
@@ -24,7 +24,7 @@ class Fluentd
attr_reader :extra_options
def self.included(base)
- base.send(:include, Fluentd::Agent::ProcessOperation)
+ base.include(Fluentd::Agent::ProcessOperation)
end
# define these methods on each Agent class
|
Module#include is public since Ruby <I>
We don't support old versions of Ruby.
|
fluent_fluentd-ui
|
train
|
54c6abdfa19b51c78cacc5f7b355174217639b08
|
diff --git a/app/controllers/api/sync_controller.rb b/app/controllers/api/sync_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/api/sync_controller.rb
+++ b/app/controllers/api/sync_controller.rb
@@ -37,8 +37,12 @@ class Api::SyncController < Api::ApiController
end
def cancel
- @obj.cancel_sync
- render :text => "cancelled synchronization of #{@sync_of}: #{@obj.id}", :status => 200
+ if @obj.sync_state.to_s == PulpSyncStatus::Status::RUNNING.to_s
+ @obj.cancel_sync
+ render :text => "Cancelled synchronization of #{@sync_of}: #{@obj.id}", :status => 200
+ else
+ render :text => "No synchronization of the #{@sync_of} is currently running", :status => 200
+ end
end
def find_provider
|
sync api - correct message when cancel is called on object that is not being synced
|
Katello_katello
|
train
|
d3932d0de33ffb3c8411f22384682bfa44d8c470
|
diff --git a/py/nupic/frameworks/opf/exp_generator/ExpGenerator.py b/py/nupic/frameworks/opf/exp_generator/ExpGenerator.py
index <HASH>..<HASH> 100755
--- a/py/nupic/frameworks/opf/exp_generator/ExpGenerator.py
+++ b/py/nupic/frameworks/opf/exp_generator/ExpGenerator.py
@@ -925,7 +925,7 @@ def _generateEncoderStringsV2(includedFields, options):
encoderDictsList.remove(encoderDict)
#Remove any encoders not in fiexedFields
- if 'fixedFields' in options:
+ if options.get('fixedFields') is not None:
tempList=[]
for encoderDict in encoderDictsList:
if encoderDict['name'] in options['fixedFields']:
|
didn't realize an option could be None as opposed to just missing
|
numenta_nupic
|
train
|
1131d0a0aa6e9569feb43844e924da0c5722757a
|
diff --git a/h2o-py/tests/pyunit_utils/utilsPY.py b/h2o-py/tests/pyunit_utils/utilsPY.py
index <HASH>..<HASH> 100644
--- a/h2o-py/tests/pyunit_utils/utilsPY.py
+++ b/h2o-py/tests/pyunit_utils/utilsPY.py
@@ -2,6 +2,9 @@
from __future__ import print_function
from future import standard_library
+from h2o import H2OFrame
+from h2o.expr import ExprNode
+
standard_library.install_aliases()
from past.builtins import basestring
@@ -4590,3 +4593,8 @@ def download_mojo(model, mojo_zip_path=None, genmodel_path=None):
"mojo_zip_path": mojo_zip_path,
"genmodel_jar_path": genmodel_path
}
+
+
+def test_java_scoring(model, frame, predictions, epsilon):
+ fr = H2OFrame._expr(ExprNode("model.testJavaScoring", model, frame, predictions, epsilon))
+ return fr.flatten() == 1
diff --git a/h2o-py/tests/testdir_algos/coxph/pyunit_coxph_mojo_interactions.py b/h2o-py/tests/testdir_algos/coxph/pyunit_coxph_mojo_interactions.py
index <HASH>..<HASH> 100644
--- a/h2o-py/tests/testdir_algos/coxph/pyunit_coxph_mojo_interactions.py
+++ b/h2o-py/tests/testdir_algos/coxph/pyunit_coxph_mojo_interactions.py
@@ -34,6 +34,11 @@ def mojo_predict_pandas_test(sandbox_dir, stratify_by=None):
training_frame=data)
print(model)
+ # reference predictions
+ h2o_prediction = model.predict(data)
+
+ assert pyunit_utils.test_java_scoring(model, data, h2o_prediction, 1e-8)
+
# download mojo
mojo = pyunit_utils.download_mojo(model)
@@ -42,7 +47,6 @@ def mojo_predict_pandas_test(sandbox_dir, stratify_by=None):
h2o.export_file(data, input_csv)
pandas_frame = pandas.read_csv(input_csv)
- h2o_prediction = model.predict(data)
mojo_prediction = h2o.mojo_predict_pandas(dataframe=pandas_frame, **mojo)
assert len(mojo_prediction) == h2o_prediction.nrow
|
Use test_java_scoring from Python in CoxPH test
|
h2oai_h2o-3
|
train
|
7644f9f3db5891ddadd8d8456a21cc6edf814627
|
diff --git a/lib/zlib/deflate.js b/lib/zlib/deflate.js
index <HASH>..<HASH> 100644
--- a/lib/zlib/deflate.js
+++ b/lib/zlib/deflate.js
@@ -999,6 +999,9 @@ function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = utils.arrayCreate(s.pending_buf_size);
+ s.d_buf = Math.floor(s.lit_bufsize / 2);
+ s.l_buf = (1 + 2) * s.lit_bufsize;
+
s.level = level;
s.strategy = strategy;
s.method = method;
diff --git a/lib/zlib/trees.js b/lib/zlib/trees.js
index <HASH>..<HASH> 100644
--- a/lib/zlib/trees.js
+++ b/lib/zlib/trees.js
@@ -162,12 +162,12 @@ function send_bits(s, value, length) {
var len = length, val;
if (s.bi_valid > (Buf_size - len)) {
val = value;
- s.bi_buf |= val << s.bi_valid;
+ s.bi_buf |= (val << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = val >> (Buf_size - s.bi_valid);
s.bi_valid += len - Buf_size;
} else {
- s.bi_buf |= value << s.bi_valid;
+ s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += len;
}
}
|
add initialization l_buf and d_buf
|
nodeca_pako
|
train
|
6b438a5a5edd30c675695bbf478e08da3677681c
|
diff --git a/lib/keen/client.rb b/lib/keen/client.rb
index <HASH>..<HASH> 100644
--- a/lib/keen/client.rb
+++ b/lib/keen/client.rb
@@ -25,7 +25,8 @@ module Keen
}
def beacon_url(event_name, properties)
- data = Base64.urlsafe_encode64(MultiJson.encode(properties))
+ json = MultiJson.encode(properties)
+ data = [json].pack("m0").tr("+/", "-_").gsub("\n", "")
"https://#{api_host}/#{api_version}/projects/#{@project_id}/events/#{event_name}?api_key=#{@api_key}&data=#{data}"
end
|
Base<I> encode manually
<I> has no Base<I>.urlsafe_encode<I> method
|
keenlabs_keen-gem
|
train
|
d01d14541ce28998f76eedf7d777cdf96efc55f1
|
diff --git a/aioauth_client.py b/aioauth_client.py
index <HASH>..<HASH> 100644
--- a/aioauth_client.py
+++ b/aioauth_client.py
@@ -145,7 +145,7 @@ class Client(object, metaclass=ClientRegistry):
try:
async with session.request(method, url, **kwargs) as response:
- if response.status / 100 > 2:
+ if response.status // 100 > 2:
raise web.HTTPBadRequest(
reason='HTTP status code: %s' % response.status)
|
don't raise HTTPBadRequest for 2XX status codes
|
klen_aioauth-client
|
train
|
806cd0466d33db0076299409a6ae763873899d05
|
diff --git a/packages/core/parcel-bundler/src/cli.js b/packages/core/parcel-bundler/src/cli.js
index <HASH>..<HASH> 100755
--- a/packages/core/parcel-bundler/src/cli.js
+++ b/packages/core/parcel-bundler/src/cli.js
@@ -14,7 +14,7 @@ program
parseInt
)
.option(
- '-h, --hmr-port <port>',
+ '--hmr-port <port>',
'set the port to serve HMR websockets, defaults to random',
parseInt
)
|
Remove `-h` alias for `hmr-port` option (#<I>)
The alias was clashing with the alias for help
Closes <I>
|
parcel-bundler_parcel
|
train
|
f6d1e9966017e2ca02de69e5477e3c6f0b7fc304
|
diff --git a/pharen.php b/pharen.php
index <HASH>..<HASH> 100644
--- a/pharen.php
+++ b/pharen.php
@@ -324,6 +324,15 @@ class AtArrayNode extends Node{
}
}
+class SuperGlobalNode extends Node{
+
+ public function compile(){
+ $varname = strToUpper($this->children[1]->compile());
+ $key = $this->children[2]->compile();
+ return '$_'.$varname.'['.$key.']';
+ }
+}
+
class Parser{
static $INFIX_OPERATORS = array("+", "-", "*", ".", "/", "and", "or", "==", '=');
@@ -363,7 +372,8 @@ class Parser{
"if" => array("IfNode", "LiteralNode", self::$NODES),
"elseif" => array("ElseIfNode", "LiteralNode", self::$NODES),
"else" => array("ElseNode", "LiteralNode", self::$NODES),
- "at" => array("AtArrayNode", "LeafNode", "VariableNode", "LeafNode")
+ "at" => array("AtArrayNode", "LeafNode", "VariableNode", "LeafNode"),
+ "$" => array("SuperGlobalNode", "LeafNode", "LeafNode", self::$NODE_TOK_MAP)
);
}
@@ -402,7 +412,9 @@ class Parser{
$next = $this->get_next_state_node();
$class = "";
if(is_array($next)){
- if(is_array($next[0]) && is_assoc($next[0])){
+ if(is_assoc($next)){
+ $class = $next[get_class($this->tok)];
+ }else if(is_array($next[0]) && is_assoc($next[0])){
$class = $next[0][get_class($this->tok)];
}else{
$class = $next[0];
|
Add superglobal special form to add a nicer syntax to access POST, GET, etc. data.
|
Scriptor_pharen
|
train
|
3ce92a74e85e8e729c681da1ba0bbc2de9313b0a
|
diff --git a/pyrax/__init__.py b/pyrax/__init__.py
index <HASH>..<HASH> 100755
--- a/pyrax/__init__.py
+++ b/pyrax/__init__.py
@@ -116,7 +116,17 @@ regions = tuple()
services = tuple()
+def _id_type(ityp):
+ """Allow for shorthand names for the most common types."""
+ if ityp.lower() == "rackspace":
+ ityp = "rax_identity.RaxIdentity"
+ elif ityp.lower() == "keystone":
+ ityp = "keystone_identity.KeystoneIdentity"
+ return ityp
+
+
def _import_identity(import_str):
+ import_str = _id_type(import_str)
full_str = "pyrax.identity.%s" % import_str
return utils.import_class(full_str)
@@ -153,7 +163,14 @@ class Settings(object):
return self._settings[env][key]
except KeyError:
# See if it's set in the environment
- env_var = self.env_dct.get(key)
+ if key == "identity_class":
+ # This is defined via the identity_type
+ env_var = self.env_dct.get("identity_type")
+ ityp = os.environ.get(env_var)
+ if ityp:
+ return _import_identity(ityp)
+ else:
+ env_var = self.env_dct.get(key)
try:
return os.environ[env_var]
except KeyError:
@@ -179,10 +196,6 @@ class Settings(object):
dct[key] = val
# If setting the identity_type, also change the identity_class.
if key == "identity_type":
- if val.lower() == "rackspace":
- val = "rax_identity.RaxIdentity"
- elif val.lower() == "keystone":
- val = "keystone_identity.KeystoneIdentity"
dct["identity_class"] = _import_identity(val)
@@ -239,12 +252,7 @@ class Settings(object):
dct = self._settings[section_name] = {}
dct["default_region"] = safe_get(section, "region", default_region)
ityp = safe_get(section, "identity_type", default_identity_type)
- # Allow for shorthand names for the most common types.
- if ityp.lower() == "rackspace":
- ityp = "rax_identity.RaxIdentity"
- elif ityp.lower() == "keystone":
- ityp = "keystone_identity.KeystoneIdentity"
- dct["identity_type"] = ityp
+ dct["identity_type"] = _id_type(ityp)
dct["identity_class"] = _import_identity(ityp)
# Handle both the old and new names for this setting.
debug = safe_get(section, "debug")
diff --git a/pyrax/client.py b/pyrax/client.py
index <HASH>..<HASH> 100644
--- a/pyrax/client.py
+++ b/pyrax/client.py
@@ -147,7 +147,7 @@ class BaseClient(httplib2.Http):
string_parts = ["curl -i"]
for element in args:
- if element in ("GET", "POST"):
+ if element in ("GET", "POST", "PUT", "DELETE", "HEAD"):
string_parts.append(" -X %s" % element)
else:
string_parts.append(" %s" % element)
|
Fixed a bug in the way identity type was set in environment variables. GitHub #<I>.
|
pycontribs_pyrax
|
train
|
16d5e85b8841a9a99ef5550f1019675ffca23596
|
diff --git a/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/parsetree/reconstr/SerializationErrorTest.java b/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/parsetree/reconstr/SerializationErrorTest.java
index <HASH>..<HASH> 100644
--- a/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/parsetree/reconstr/SerializationErrorTest.java
+++ b/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/parsetree/reconstr/SerializationErrorTest.java
@@ -56,20 +56,17 @@ public class SerializationErrorTest extends AbstractXtextTests {
// assertEquals(2, r.getLikelyErrorReasons(3).size());
// assertTrue(r.toString(), r.getLikelyErrorReasons(1).get(0).contains(
// "Test(TwoRequired).one is not set"));
- assertTrue(r.toString(), r.toString().contains(
- "TwoRequired.one is not set"));
+ assertTrue(r.toString(), r.toString().contains("TwoRequired.one is not set"));
}
- public void testElementToMuch() throws Exception {
+ public void testElementTooMuch() throws Exception {
Model m = (Model) getModel("twooptions one a");
// System.out.println(EmfFormatter.objToStr(m));
((TwoOptions) m.getTest()).setTwo("b");
TreeConstructionReport r = ser(m);
assertFalse(r.isSuccess());
assertTrue(r.toString(), r.toString().contains(
- "Can not leave rule 'Parenthesis' "
- + "since the current object "
- + "'TwoOptions' has features with "
+ "Can not leave rule 'Parenthesis' " + "since the current object " + "'TwoOptions' has features with "
+ "unconsumed values: 'two':1"));
// assertTrue(r.toString(), r.getLikelyErrorReasons(1).get(0).contains(
// "Can not leave rule 'Parenthesis' "
@@ -79,7 +76,7 @@ public class SerializationErrorTest extends AbstractXtextTests {
}
- public void testDeepToMuch() throws Exception {
+ public void testDeep() throws Exception {
Model m = (Model) getModel("{ twooptions one a { twooptions one a { twooptions one a }}}");
// System.out.println(EmfFormatter.objToStr(m));
Indent i = ((Indent) m.getTest()).getIndent().get(0).getIndent().get(0);
@@ -87,11 +84,7 @@ public class SerializationErrorTest extends AbstractXtextTests {
TreeConstructionReport r = ser(m);
assertFalse(r.isSuccess());
String msg = r.toString();
- assertTrue(msg, msg.contains("Model {"));
- assertTrue(msg, msg.contains("indent[0] = Indent"));
- assertTrue(msg, msg.contains("Can not leave rule 'TwoOptions' "
- + "since the current object "
- + "'TwoOptions' has features with "
- + "unconsumed values: 'two':1"));
+ assertTrue(msg, msg.contains("Can not leave rule 'TwoOptions' " + "since the current object "
+ + "'TwoOptions' has features with " + "unconsumed values: 'two':1"));
}
}
|
Simplified error reporting of the ParseTreeConstructor. Now, only the <I> most promising deadends during backtracking are kept. This should prevent some OutOfMemoryErrors. Furthermore, the naming of some variables has been improved.
|
eclipse_xtext-extras
|
train
|
d0742daeef0380d972449824cfed5061175357d9
|
diff --git a/spec/support/billy.rb b/spec/support/billy.rb
index <HASH>..<HASH> 100644
--- a/spec/support/billy.rb
+++ b/spec/support/billy.rb
@@ -19,3 +19,57 @@ module EventMachine
end
end
+# Monkey patch for removing
+# warning: instance variable @ssl not initialized
+module Billy
+ class ProxyConnection < EventMachine::Connection
+ def on_message_complete
+ if @parser.http_method == 'CONNECT'
+ restart_with_ssl(@parser.request_url)
+ else
+ if defined?(@ssl) and @ssl # The only line I changed
+ uri = Addressable::URI.parse(@parser.request_url)
+ @url = "https://#{@ssl}#{[uri.path, uri.query].compact.join('?')}"
+ else
+ @url = @parser.request_url
+ end
+ handle_request
+ end
+ end
+ end
+end
+
+# Monkey patch for removing
+# warning: instance variable @cache not initialized
+# warning: instance variable @signature not initialized
+module Billy
+ class Proxy
+
+ def start(threaded = true)
+ if threaded
+ Thread.new { main_loop }
+ sleep(0.01) while (not defined?(@signature)) or @signature.nil? # The only line I changed
+ else
+ main_loop
+ end
+ end
+
+ protected
+
+ def main_loop
+ EM.run do
+ EM.error_handler do |e|
+ Billy.log :error, "#{e.class} (#{e.message}):"
+ Billy.log :error, e.backtrace.join("\n")
+ end
+
+ @signature = EM.start_server('127.0.0.1', Billy.config.proxy_port, ProxyConnection) do |p|
+ p.handler = request_handler
+ p.cache = @cache if defined?(@cache) # The only line I changed
+ end
+
+ Billy.log(:info, "puffing-billy: Proxy listening on #{url}")
+ end
+ end
+ end
+end
\ No newline at end of file
|
patch Billy to avoid "instance variable not initialized" warns
|
algonauti_yasf
|
train
|
25459a10b32e40877f1f1abc1638da3966a09468
|
diff --git a/reef-common/src/main/java/com/microsoft/reef/client/DriverConfiguration.java b/reef-common/src/main/java/com/microsoft/reef/client/DriverConfiguration.java
index <HASH>..<HASH> 100644
--- a/reef-common/src/main/java/com/microsoft/reef/client/DriverConfiguration.java
+++ b/reef-common/src/main/java/com/microsoft/reef/client/DriverConfiguration.java
@@ -27,6 +27,7 @@ import com.microsoft.reef.driver.evaluator.CompletedEvaluator;
import com.microsoft.reef.driver.evaluator.FailedEvaluator;
import com.microsoft.reef.driver.parameters.*;
import com.microsoft.reef.driver.task.*;
+import com.microsoft.reef.runtime.common.DriverRestartCompleted;
import com.microsoft.reef.runtime.common.driver.DriverRuntimeConfiguration;
import com.microsoft.tang.formats.*;
import com.microsoft.wake.EventHandler;
@@ -187,6 +188,11 @@ public final class DriverConfiguration extends ConfigurationModuleBuilder {
public static final OptionalParameter<Integer> EVALUATOR_DISPATCHER_THREADS = new OptionalParameter<>();
/**
+ * Event handler for the event of driver restart completion, default to logging if not bound.
+ */
+ public static final OptionalImpl<EventHandler<DriverRestartCompleted>> ON_DRIVER_RESTART_COMPLETED = new OptionalImpl<>();
+
+ /**
* ConfigurationModule to fill out to get a legal Driver Configuration.
*/
public static final ConfigurationModule CONF = new DriverConfiguration().merge(DriverRuntimeConfiguration.CONF)
@@ -231,5 +237,6 @@ public final class DriverConfiguration extends ConfigurationModuleBuilder {
// Various parameters
.bindNamedParameter(EvaluatorDispatcherThreads.class, EVALUATOR_DISPATCHER_THREADS)
+ .bindSetEntry(DriverRestartCompletedHandlers.class, ON_DRIVER_RESTART_COMPLETED)
.build();
}
|
add restart completed handler to driver configuration
|
apache_reef
|
train
|
79b33bbb4da5d0c76d45398717af8af8cd0f7a3f
|
diff --git a/yfinance/base.py b/yfinance/base.py
index <HASH>..<HASH> 100644
--- a/yfinance/base.py
+++ b/yfinance/base.py
@@ -280,15 +280,41 @@ class TickerBase():
data = utils.get_json(url, proxy)
# holders
- url = "{}/{}/holders".format(self._scrape_url, self.ticker)
- holders = _pd.read_html(url)
- self._major_holders = holders[0]
- self._institutional_holders = holders[1]
- if 'Date Reported' in self._institutional_holders:
- self._institutional_holders['Date Reported'] = _pd.to_datetime(
+ # url = "{}/{}/holders".format(self._scrape_url, self.ticker)
+ # holders = _pd.read_html(url)
+ try:
+ url = "{}/{}".format(self._scrape_url, self.ticker)
+ holders = _pd.read_html(url+'\holders') # Can return No Tables Found!
+ except Exception as e:
+ holders = []
+
+ if len(holders)>=3:
+ self._major_holders = holders[0]
+ self._institutional_holders = holders[1]
+ self._mutualfund_holders = holders[2]
+ elif len(holders)>=2:
+ self._major_holders = holders[0]
+ self._institutional_holders = holders[1]
+ elif len(holders)>=1:
+ self._major_holders = holders[0]
+
+ #self._major_holders = holders[0]
+ #self._institutional_holders = holders[1]
+
+ if self._institutional_holders is not None:
+ if 'Date Reported' in self._institutional_holders:
+ self._institutional_holders['Date Reported'] = _pd.to_datetime(
self._institutional_holders['Date Reported'])
- if '% Out' in self._institutional_holders:
- self._institutional_holders['% Out'] = self._institutional_holders[
+ if '% Out' in self._institutional_holders:
+ self._institutional_holders['% Out'] = self._institutional_holders[
+ '% Out'].str.replace('%', '').astype(float)/100
+
+ if self._mutualfund_holders is not None:
+ if 'Date Reported' in self._mutualfund_holders:
+ self._mutualfund_holders['Date Reported'] = _pd.to_datetime(
+ self._mutualfund_holders['Date Reported'])
+ if '% Out' in self._mutualfund_holders:
+ self._mutualfund_holders['% Out'] = self._mutualfund_holders[
'% Out'].str.replace('%', '').astype(float)/100
# sustainability
|
Fix Holders error for no tables found
This Pull request must be pulled in it is a major fix
|
ranaroussi_fix-yahoo-finance
|
train
|
ec148fb3db5bdf5cae035b629db5daef42c06425
|
diff --git a/duniterpy/helpers/ws2p.py b/duniterpy/helpers/ws2p.py
index <HASH>..<HASH> 100644
--- a/duniterpy/helpers/ws2p.py
+++ b/duniterpy/helpers/ws2p.py
@@ -4,28 +4,25 @@ from duniterpy.api import ws2p
from duniterpy.api.client import WSConnection
from duniterpy.documents.ws2p.messages import Connect, Ack, Ok
from duniterpy.key import SigningKey
+import logging
-async def handshake(
- ws: WSConnection, signing_key: SigningKey, currency: str, verbose: bool = False
-):
+async def handshake(ws: WSConnection, signing_key: SigningKey, currency: str):
"""
Perform ws2p handshake on the web socket connection using the signing_key instance
:param ws: Web socket connection instance
:param signing_key: SigningKey instance
:param currency: Currency name
- :param verbose: Default=False, True to see console progress messages
:return:
"""
# START HANDSHAKE #######################################################
- if verbose:
- print("\nSTART HANDSHAKE...")
+ logging.debug("\nSTART HANDSHAKE...")
connect_document = Connect(currency, signing_key.pubkey)
connect_message = connect_document.get_signed_json(signing_key)
- if verbose:
- print("Send CONNECT message")
+
+ logging.debug("Send CONNECT message")
await ws.send_str(connect_message)
loop = True
@@ -37,34 +34,32 @@ async def handshake(
if "auth" in data and data["auth"] == "CONNECT":
jsonschema.validate(data, ws2p.network.WS2P_CONNECT_MESSAGE_SCHEMA)
- if verbose:
- print("Received a CONNECT message")
+
+ logging.debug("Received a CONNECT message")
remote_connect_document = Connect(
currency, data["pub"], data["challenge"], data["sig"]
)
- if verbose:
- print("Received CONNECT message signature is valid")
+
+ logging.debug("Received CONNECT message signature is valid")
ack_message = Ack(
currency, signing_key.pubkey, remote_connect_document.challenge
).get_signed_json(signing_key)
# Send ACK message
- if verbose:
- print("Send ACK message...")
-
+ logging.debug("Send ACK message...")
await ws.send_str(ack_message)
if "auth" in data and data["auth"] == "ACK":
jsonschema.validate(data, ws2p.network.WS2P_ACK_MESSAGE_SCHEMA)
- if verbose:
- print("Received a ACK message")
+
+ logging.debug("Received an ACK message")
# Create ACK document from ACK response to verify signature
Ack(currency, data["pub"], connect_document.challenge, data["sig"])
- if verbose:
- print("Received ACK message signature is valid")
+
+ logging.debug("Received ACK message signature is valid")
# If ACK response is ok, create OK message
ok_message = Ok(
@@ -72,9 +67,7 @@ async def handshake(
).get_signed_json(signing_key)
# Send OK message
- if verbose:
- print("Send OK message...")
-
+ logging.debug("Send OK message...")
await ws.send_str(ok_message)
if (
@@ -83,8 +76,8 @@ async def handshake(
and data["auth"] == "OK"
):
jsonschema.validate(data, ws2p.network.WS2P_OK_MESSAGE_SCHEMA)
- if verbose:
- print("Received a OK message")
+
+ logging.debug("Received an OK message")
Ok(
currency,
@@ -92,12 +85,11 @@ async def handshake(
connect_document.challenge,
data["sig"],
)
- if verbose:
- print("Received OK message signature is valid")
+
+ logging.debug("Received OK message signature is valid")
# END HANDSHAKE #######################################################
- if verbose:
- print("END OF HANDSHAKE\n")
+ logging.debug("END OF HANDSHAKE\n")
# exit loop
break
diff --git a/examples/listen_ws2p.py b/examples/listen_ws2p.py
index <HASH>..<HASH> 100644
--- a/examples/listen_ws2p.py
+++ b/examples/listen_ws2p.py
@@ -50,7 +50,7 @@ async def main():
try:
# Resolve handshake
print("Handshake...")
- await handshake(ws, signing_key, CURRENCY, True)
+ await handshake(ws, signing_key, CURRENCY)
except ValidationError as exception:
print(exception.message)
print("HANDSHAKE FAILED !")
diff --git a/examples/request_ws2p.py b/examples/request_ws2p.py
index <HASH>..<HASH> 100644
--- a/examples/request_ws2p.py
+++ b/examples/request_ws2p.py
@@ -58,7 +58,7 @@ async def main():
# HANDSHAKE #######################################################
try:
- await handshake(ws, signing_key, CURRENCY, True)
+ await handshake(ws, signing_key, CURRENCY)
except ValidationError as exception:
print(exception.message)
print("HANDSHAKE FAILED !")
|
[enh] #<I> replace print statements by logging.debug() in ws2p handshake
|
duniter_duniter-python-api
|
train
|
c719e8000c93c2177052f1610729cd2f6d068935
|
diff --git a/src/mg/Ding/Autoloader/Ding_Autoloader.php b/src/mg/Ding/Autoloader/Ding_Autoloader.php
index <HASH>..<HASH> 100644
--- a/src/mg/Ding/Autoloader/Ding_Autoloader.php
+++ b/src/mg/Ding/Autoloader/Ding_Autoloader.php
@@ -77,6 +77,13 @@ class Ding_Autoloader
self::$_cache = $cache;
}
+ /**
+ * Resolves a class name to a filesystem entry. False if none found.
+ *
+ * @param string $class Class name.
+ *
+ * @return string
+ */
private static function _resolve($class)
{
$file = realpath(implode(
|
added doc for _resolve in autoloader
|
marcelog_Ding
|
train
|
21c366a4edba087b7e94fb1404504980062e4dea
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -23,12 +23,17 @@ module.exports = function (opt) {
var options = {};
options.outExtension = opt.outExtension || '.html';
options.doubleQuote = opt.doubleQuote || false;
+ options.encodings = opt.encodings || false;
var str = file.contents.toString('utf8');
var args = ['haml'];
if (options.doubleQuote) {
args.push('-q');
}
+ if (options.encodings) {
+ args.push('-E');
+ args.push(options.encodings);
+ }
args.push(file.path);
var cp = spawn(args.shift(), args);
|
added haml encoding option
|
cheshire137_gulp-ruby-haml
|
train
|
191d43041eb42bdf52eab2b7439dbb383c7343cd
|
diff --git a/richtextfx/src/main/java/org/fxmisc/richtext/LineNumberFactory.java b/richtextfx/src/main/java/org/fxmisc/richtext/LineNumberFactory.java
index <HASH>..<HASH> 100644
--- a/richtextfx/src/main/java/org/fxmisc/richtext/LineNumberFactory.java
+++ b/richtextfx/src/main/java/org/fxmisc/richtext/LineNumberFactory.java
@@ -30,7 +30,7 @@ public class LineNumberFactory implements IntFunction<Node> {
new Background(new BackgroundFill(Color.web("#ddd"), null, null));
public static IntFunction<Node> get(GenericStyledArea<?, ?, ?> area) {
- return get(area, digits -> "%0" + digits + "d");
+ return get(area, digits -> "%1$" + digits + "s");
}
public static IntFunction<Node> get(
|
Pad line numbers with spaces instead of zeros by default
|
FXMisc_RichTextFX
|
train
|
86c468de58e1f90e38e6f6df3d65ce1aaf78f13d
|
diff --git a/library.js b/library.js
index <HASH>..<HASH> 100644
--- a/library.js
+++ b/library.js
@@ -112,7 +112,7 @@ function getGroupMemberUids(groupRecipients, callback) {
return callback(err);
}
async.map(groups, function(group, next) {
- Groups.getMembers(group, next);
+ Groups.getMembers(group, 0, -1, next);
}, function(err, results) {
if (err) {
return callback(err);
|
getMembers takes start end now
|
julianlam_nodebb-plugin-mentions
|
train
|
7dfe4b43126b223510e03d7fcc53fdb8780d85d2
|
diff --git a/salt/modules/ssh.py b/salt/modules/ssh.py
index <HASH>..<HASH> 100644
--- a/salt/modules/ssh.py
+++ b/salt/modules/ssh.py
@@ -35,8 +35,6 @@ def _format_auth_line(
return line
-# FIXME: mutable types as default parameter values, NO!
-# http://goo.gl/ToU2z
def _replace_auth_key(
user,
key,
@@ -188,8 +186,6 @@ def rm_auth_key(user, key, config='.ssh/authorized_keys'):
return 'Key not present'
-# FIXME: mutable types as default parameter values, NO!
-# http://goo.gl/ToU2z
def set_auth_key(
user,
key,
@@ -205,7 +201,6 @@ def set_auth_key(
salt '*' ssh.set_auth_key <user> <key> dsa '[]' .ssh/authorized_keys
'''
enc = _refine_enc(enc)
- ret = '' # FIXME: where is ret used?
replace = False
uinfo = __salt__['user.info'](user)
current = auth_keys(user, config)
@@ -236,6 +231,14 @@ def set_auth_key(
options)
fconfig = os.path.join(uinfo['home'], config)
if not os.path.isdir(os.path.dirname(fconfig)):
- os.makedirs(os.path.dirname(fconfig))
- open(fconfig, 'a+').write('\n{0}'.format(auth_line))
+ dpath = os.path.dirname(fconfig)
+ os.makedirs(dpath)
+ os.chown(dpath, uinfo['uid'], uinfo['gid'])
+ os.chmod(dpath, 448)
+
+ if not os.path.isfile(fconfig):
+ open(fconfig, 'a+').write('\n{0}'.format(auth_line))
+ os.chown(fconfig, uinfo['uid'], uinfo['gid'])
+ else:
+ open(fconfig, 'a+').write('\n{0}'.format(auth_line))
return 'new'
|
make new .ssh dirs and authorized keys files have the right perms
|
saltstack_salt
|
train
|
20ccda043990deb1c85ea76b21540ccf8a68fed2
|
diff --git a/src/kg/apc/jmeter/perfmon/AbstractPerformanceMonitoringGui.java b/src/kg/apc/jmeter/perfmon/AbstractPerformanceMonitoringGui.java
index <HASH>..<HASH> 100644
--- a/src/kg/apc/jmeter/perfmon/AbstractPerformanceMonitoringGui.java
+++ b/src/kg/apc/jmeter/perfmon/AbstractPerformanceMonitoringGui.java
@@ -35,7 +35,6 @@ import org.apache.jmeter.visualizers.gui.AbstractListenerGui;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
-import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import kg.apc.jmeter.charting.GraphPanelChart;
import kg.apc.jmeter.charting.ColorsDispatcher;
@@ -133,6 +132,7 @@ public abstract class AbstractPerformanceMonitoringGui extends AbstractListenerG
errorTextArea = new JTextArea();
errorTextArea.setForeground(Color.red);
+ errorTextArea.setBackground(new Color(255,255,153));
errorTextArea.setEditable(false);
//errorTextArea.setText("Error!!!\nError!!!\nError!!!\nError!!!\nError!!!\n");
scrollPan.setViewportView(errorTextArea);
|
Changed background color of error text area
|
undera_jmeter-plugins
|
train
|
e03f0dfd9268e1132f8709c297fdc041778fbf8e
|
diff --git a/src/components/line.js b/src/components/line.js
index <HASH>..<HASH> 100644
--- a/src/components/line.js
+++ b/src/components/line.js
@@ -24,7 +24,7 @@ module.exports.Component = registerComponent('line', {
visible: data.visible
});
geometry = this.geometry = new THREE.BufferGeometry();
- geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
+ geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
this.rendererSystem.applyColorCorrection(material.color);
this.line = new THREE.Line(geometry, material);
|
use setAttribute in line component (#<I>)
|
aframevr_aframe
|
train
|
26bd3e381195ba0901c506e8257e0eb6e5d5c931
|
diff --git a/lib/Doctrine/ORM/EntityManager.php b/lib/Doctrine/ORM/EntityManager.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ORM/EntityManager.php
+++ b/lib/Doctrine/ORM/EntityManager.php
@@ -203,13 +203,18 @@ class EntityManager implements ObjectManager
public function transactional(Closure $func)
{
$this->conn->beginTransaction();
+
try {
- $func($this);
+ $return = $func($this);
+
$this->flush();
$this->conn->commit();
+
+ return $return ?: true;
} catch (Exception $e) {
$this->close();
$this->conn->rollback();
+
throw $e;
}
}
diff --git a/tests/Doctrine/Tests/ORM/EntityManagerTest.php b/tests/Doctrine/Tests/ORM/EntityManagerTest.php
index <HASH>..<HASH> 100644
--- a/tests/Doctrine/Tests/ORM/EntityManagerTest.php
+++ b/tests/Doctrine/Tests/ORM/EntityManagerTest.php
@@ -143,4 +143,16 @@ class EntityManagerTest extends \Doctrine\Tests\OrmTestCase
$this->_em->close();
$this->_em->$methodName(new \stdClass());
}
+
+ /**
+ * @group DDC-1125
+ */
+ public function testTransactionalAcceptsReturn()
+ {
+ $return = $this->_em->transactional(function ($em) {
+ return 'foo';
+ });
+
+ $this->assertEquals('foo', $return);
+ }
}
\ No newline at end of file
|
Implemented support for closure return on EntityManager::transactional. Fixes DDC-<I>
|
doctrine_orm
|
train
|
b556c44c2fc1bf510f91f0f8edfb9db20339cd8d
|
diff --git a/numpy_groupies/__init__.py b/numpy_groupies/__init__.py
index <HASH>..<HASH> 100644
--- a/numpy_groupies/__init__.py
+++ b/numpy_groupies/__init__.py
@@ -42,6 +42,13 @@ else:
aggregate = aggregate_weave
+try:
+ import numba
+except ImportError:
+ aggregate_nb = None
+else:
+ from .aggregate_numba import aggregate as aggregate_nb
+ aggregate = aggregate_nb
def unpack(group_idx, ret, mode='normal'):
""" Take an aggregate packed array and uncompress it to the size of group_idx.
|
register numba aggregate impl as default
|
ml31415_numpy-groupies
|
train
|
2ad6ed721f0e3fd059174c3c2d07f7ea2e5d9d69
|
diff --git a/spec/progne_tapera/enum_list_spec.rb b/spec/progne_tapera/enum_list_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/progne_tapera/enum_list_spec.rb
+++ b/spec/progne_tapera/enum_list_spec.rb
@@ -1,5 +1,4 @@
require 'spec_helper'
-require 'progne_tapera'
describe ProgneTapera::EnumList do
|
1, Improve the Enum List spec.
|
topbitdu_progne_tapera
|
train
|
94607b4036f23917aba5ca007dc6fec605214788
|
diff --git a/code/model/SolrResultSet.php b/code/model/SolrResultSet.php
index <HASH>..<HASH> 100644
--- a/code/model/SolrResultSet.php
+++ b/code/model/SolrResultSet.php
@@ -12,7 +12,7 @@ class SolrResultSet {
/**
* A list of solr field type suffixes to look for and swap out
*/
- static $solr_attrs = array('txt', 'ms', 's', 't', 'i', 'dt', 'f', 'p');
+ static $solr_attrs = array('as', 'ms', 's', 't', 'i', 'dt', 'f', 'p');
/**
* The raw lucene query issued to solr
diff --git a/code/pages/SolrSearchPage.php b/code/pages/SolrSearchPage.php
index <HASH>..<HASH> 100644
--- a/code/pages/SolrSearchPage.php
+++ b/code/pages/SolrSearchPage.php
@@ -411,12 +411,12 @@ class SolrSearchPage extends Page {
if (count($types)) {
$sortBy = $this->solrSearchService->getSortFieldName($sortBy, $types);
- $builder->andWith('ClassNameHierarchy_ms', $types);
+ $builder->addFilter('ClassNameHierarchy_ms', implode(' OR ', $types));
}
if ($this->SearchTrees()->count()) {
$parents = $this->SearchTrees()->column('ID');
- $builder->andWith('ParentsHierarchy_ms', $parents);
+ $builder->addFilter('ParentsHierarchy_ms', implode(' OR ', $parents));
}
if (!$sortBy) {
|
Updated the builder to filter by hierarchy correctly.
|
nyeholt_silverstripe-solr
|
train
|
61ca3ed5efa3b26240207f91606795700362856e
|
diff --git a/src/main/java/org/minimalj/backend/db/DbPersistence.java b/src/main/java/org/minimalj/backend/db/DbPersistence.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/minimalj/backend/db/DbPersistence.java
+++ b/src/main/java/org/minimalj/backend/db/DbPersistence.java
@@ -281,7 +281,7 @@ public class DbPersistence implements Persistence {
return table.read(id);
}
- public <T> T read(Class<T> clazz, Object id, Integer time) {
+ public <T> T readVersion(Class<T> clazz, Object id, Integer time) {
HistorizedTable<T> table = (HistorizedTable<T>) getTable(clazz);
return table.read(id, time);
}
diff --git a/src/main/java/org/minimalj/transaction/persistence/ReadTransaction.java b/src/main/java/org/minimalj/transaction/persistence/ReadTransaction.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/minimalj/transaction/persistence/ReadTransaction.java
+++ b/src/main/java/org/minimalj/transaction/persistence/ReadTransaction.java
@@ -30,7 +30,7 @@ public class ReadTransaction<T> implements Transaction<T> {
} else {
if (persistence instanceof DbPersistence) {
DbPersistence dbPersistence = (DbPersistence) persistence;
- result = dbPersistence.read(clazz, id, time);
+ result = dbPersistence.readVersion(clazz, id, time);
} else {
throw new IllegalStateException(getClass().getSimpleName() + " works only with " + DbBackend.class.getSimpleName());
}
|
Persistence: rename read to readVersion (for read the past)
|
BrunoEberhard_minimal-j
|
train
|
ebf3a0e0fec7ecfde8a4ea723790a80d8d4dab6e
|
diff --git a/tests/unit/states/zk_concurrency_test.py b/tests/unit/states/zk_concurrency_test.py
index <HASH>..<HASH> 100644
--- a/tests/unit/states/zk_concurrency_test.py
+++ b/tests/unit/states/zk_concurrency_test.py
@@ -76,7 +76,7 @@ class ZkConcurrencyTestCase(TestCase):
def test_min_party(self):
'''
- Test to block state execution until you are able to get the lock
+ Test to ensure min party of nodes and the blocking behavior
'''
ret = {'name': 'salt',
'changes': {},
|
Change the comment for test_min_party
|
saltstack_salt
|
train
|
610c3184972da82e990350a8ae0ecfcc9e8f28b6
|
diff --git a/test/test_core.rb b/test/test_core.rb
index <HASH>..<HASH> 100644
--- a/test/test_core.rb
+++ b/test/test_core.rb
@@ -118,6 +118,48 @@ class CoreTest < Minitest::Test
refute self.phase(:TestProjTests).include_filename?(/JLToast.*\.(h|swift)/)
end
+ def test_install_common_before_separated_target
+ seedfile %{
+ github "devxoul/JLToast", "1.2.2", :files => "JLToast/*.{h,swift}"
+
+ target :TestProjTests do
+ github "devxoul/SwipeBack", "1.0.4", :files => "SwipeBack/*.{h,m}"
+ end
+ }
+ @seed.install
+
+ assert\
+ self.phase(:TestProj).include_filename?(/JLToast.*\.(h|swift)/),
+ "TestProj should have JLToast files."
+ assert\
+ self.phase(:TestProjTests).include_filename?(/.*SwipeBack\.(h|m)/),
+ "TestProjTests should have SwipeBack files."
+ assert\
+ self.phase(:TestProjTests).include_filename?(/JLToast.*\.(h|swift)/),
+ "TestProjTests should have JLToast files."
+ end
+
+ def test_install_common_after_separated_target
+ seedfile %{
+ target :TestProjTests do
+ github "devxoul/SwipeBack", "1.0.4", :files => "SwipeBack/*.{h,m}"
+ end
+
+ github "devxoul/JLToast", "1.2.2", :files => "JLToast/*.{h,swift}"
+ }
+ @seed.install
+
+ assert\
+ self.phase(:TestProj).include_filename?(/JLToast.*\.(h|swift)/),
+ "TestProj should have JLToast files."
+ assert\
+ self.phase(:TestProjTests).include_filename?(/.*SwipeBack\.(h|m)/),
+ "TestProjTests should have SwipeBack files."
+ assert\
+ self.phase(:TestProjTests).include_filename?(/JLToast.*\.(h|swift)/),
+ "TestProjTests should have JLToast files."
+ end
+
def test_remove
seedfile %{
github "devxoul/JLToast", "1.2.2", :files => "JLToast/*.{h,swift}"
|
Add tests for common seeds with separated targets.
|
devxoul_CocoaSeeds
|
train
|
bbf92abf50e65c5fd0f6f01c70a8fca79f018724
|
diff --git a/maas/client/bones/__init__.py b/maas/client/bones/__init__.py
index <HASH>..<HASH> 100644
--- a/maas/client/bones/__init__.py
+++ b/maas/client/bones/__init__.py
@@ -15,6 +15,7 @@ from collections import (
namedtuple,
)
import json
+from urllib.parse import urlparse
import aiohttp
@@ -44,6 +45,7 @@ class SessionAPI:
raise SessionError(str(error))
else:
session = cls(description, credentials)
+ session.scheme = urlparse(url).scheme
session.insecure = insecure
return session
@@ -53,7 +55,10 @@ class SessionAPI:
:see: `ProfileStore`.
"""
- return cls(profile.description, profile.credentials)
+ session = cls(profile.description, profile.credentials)
+ session.scheme = urlparse(profile.url).scheme
+ session.insecure = profile.other.get('insecure', False)
+ return session
@classmethod
def fromProfileName(cls, name):
@@ -77,6 +82,7 @@ class SessionAPI:
profile = await helpers.login(
url=url, username=username, password=password, insecure=insecure)
session = cls(profile.description, profile.credentials)
+ session.scheme = urlparse(url).scheme
session.insecure = insecure
return profile, session
@@ -93,10 +99,12 @@ class SessionAPI:
profile = await helpers.connect(
url=url, apikey=apikey, insecure=insecure)
session = cls(profile.description, profile.credentials)
+ session.scheme = urlparse(url).scheme
session.insecure = insecure
return profile, session
# Set these on instances.
+ scheme = 'http'
insecure = False
debug = False
@@ -377,7 +385,10 @@ class CallAPI:
# TODO: this is el-cheapo URI Template
# <http://tools.ietf.org/html/rfc6570> support; use uritemplate-py
# <https://github.com/uri-templates/uritemplate-py> here?
- return self.action.handler.uri.format(**self.__params)
+ uri = urlparse(self.action.handler.uri)
+ if uri.scheme != self.action.handler.session.scheme:
+ uri = uri._replace(scheme=self.action.handler.session.scheme)
+ return uri.geturl().format(**self.__params)
def rebind(self, **params):
"""Rebind the parameters into the URI.
diff --git a/maas/client/bones/helpers.py b/maas/client/bones/helpers.py
index <HASH>..<HASH> 100644
--- a/maas/client/bones/helpers.py
+++ b/maas/client/bones/helpers.py
@@ -124,7 +124,7 @@ async def connect(url, *, apikey=None, insecure=False):
# Return a new (unsaved) profile.
return Profile(
name=url.netloc, url=url.geturl(), credentials=credentials,
- description=description)
+ description=description, insecure=insecure)
class LoginError(Exception):
@@ -219,7 +219,7 @@ async def login(url, *, anonymous=False, username=None, password=None,
# Return a new (unsaved) profile.
return Profile(
name=profile_name, url=url.geturl(), credentials=credentials,
- description=description)
+ description=description, insecure=insecure)
async def authenticate_with_macaroon(url, insecure=False):
diff --git a/maas/client/bones/tests/test.py b/maas/client/bones/tests/test.py
index <HASH>..<HASH> 100644
--- a/maas/client/bones/tests/test.py
+++ b/maas/client/bones/tests/test.py
@@ -58,6 +58,13 @@ class TestSessionAPI(TestCase):
fixture.url, insecure=insecure)
self.assertThat(session.insecure, Is(insecure))
+ async def test__fromURL_sets_scheme_on_session(self):
+ insecure = random.choice((True, False))
+ fixture = self.useFixture(testing.DescriptionServer())
+ session = await bones.SessionAPI.fromURL(
+ fixture.url, insecure=insecure)
+ self.assertThat(session.scheme, Equals('http'))
+
class TestSessionAPI_APIVersions(TestCase):
"""Tests for `SessionAPI` with multiple API versions."""
diff --git a/maas/client/bones/tests/test_helpers.py b/maas/client/bones/tests/test_helpers.py
index <HASH>..<HASH> 100644
--- a/maas/client/bones/tests/test_helpers.py
+++ b/maas/client/bones/tests/test_helpers.py
@@ -154,9 +154,11 @@ class TestConnect(TestCase):
self.assertThat(profile.description, Equals(description))
def test__API_description_is_fetched_insecurely_if_requested(self):
- helpers.connect("http://example.org:5240/MAAS/", insecure=True)
+ profile = helpers.connect(
+ "http://example.org:5240/MAAS/", insecure=True)
helpers.fetch_api_description.assert_called_once_with(
urlparse("http://example.org:5240/MAAS/api/2.0/"), True)
+ self.assertTrue(profile.other['insecure'])
class TestLogin(TestCase):
@@ -260,10 +262,12 @@ class TestLogin(TestCase):
self.assertThat(profile.description, Equals(description))
def test__API_token_is_fetched_insecurely_if_requested(self):
- helpers.login("http://foo:bar@example.org:5240/MAAS/", insecure=True)
+ profile = helpers.login(
+ "http://foo:bar@example.org:5240/MAAS/", insecure=True)
helpers.authenticate.assert_called_once_with(
"http://example.org:5240/MAAS/api/2.0/",
"foo", "bar", insecure=True)
+ self.assertTrue(profile.other['insecure'])
def test__API_description_is_fetched_insecurely_if_requested(self):
helpers.login(
|
Build the URI using the original scheme of the url also store in the connection is insecure in the profile. Fixes #<I>. (#<I>)
|
maas_python-libmaas
|
train
|
22d5528225cfcb8a8e6d60cd46fd977c6cb74e42
|
diff --git a/assert/assertion_format.go b/assert/assertion_format.go
index <HASH>..<HASH> 100644
--- a/assert/assertion_format.go
+++ b/assert/assertion_format.go
@@ -269,7 +269,7 @@ func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, ms
// InDeltaf asserts that the two numerals are within delta of each other.
//
-// assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01)
+// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
diff --git a/assert/assertion_forward.go b/assert/assertion_forward.go
index <HASH>..<HASH> 100644
--- a/assert/assertion_forward.go
+++ b/assert/assertion_forward.go
@@ -525,7 +525,7 @@ func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}
// InDelta asserts that the two numerals are within delta of each other.
//
-// a.InDelta(math.Pi, (22 / 7.0), 0.01)
+// a.InDelta(math.Pi, 22/7.0, 0.01)
func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -567,7 +567,7 @@ func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, del
// InDeltaf asserts that the two numerals are within delta of each other.
//
-// a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01)
+// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) bool {
if h, ok := a.t.(tHelper); ok {
h.Helper()
diff --git a/assert/assertions.go b/assert/assertions.go
index <HASH>..<HASH> 100644
--- a/assert/assertions.go
+++ b/assert/assertions.go
@@ -1076,7 +1076,7 @@ func toFloat(x interface{}) (float64, bool) {
// InDelta asserts that the two numerals are within delta of each other.
//
-// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
+// assert.InDelta(t, math.Pi, 22/7.0, 0.01)
func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
diff --git a/require/require.go b/require/require.go
index <HASH>..<HASH> 100644
--- a/require/require.go
+++ b/require/require.go
@@ -664,7 +664,7 @@ func Implementsf(t TestingT, interfaceObject interface{}, object interface{}, ms
// InDelta asserts that the two numerals are within delta of each other.
//
-// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01)
+// assert.InDelta(t, math.Pi, 22/7.0, 0.01)
func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
@@ -721,7 +721,7 @@ func InDeltaSlicef(t TestingT, expected interface{}, actual interface{}, delta f
// InDeltaf asserts that the two numerals are within delta of each other.
//
-// assert.InDeltaf(t, math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01)
+// assert.InDeltaf(t, math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
func InDeltaf(t TestingT, expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) {
if h, ok := t.(tHelper); ok {
h.Helper()
diff --git a/require/require_forward.go b/require/require_forward.go
index <HASH>..<HASH> 100644
--- a/require/require_forward.go
+++ b/require/require_forward.go
@@ -526,7 +526,7 @@ func (a *Assertions) Implementsf(interfaceObject interface{}, object interface{}
// InDelta asserts that the two numerals are within delta of each other.
//
-// a.InDelta(math.Pi, (22 / 7.0), 0.01)
+// a.InDelta(math.Pi, 22/7.0, 0.01)
func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
@@ -568,7 +568,7 @@ func (a *Assertions) InDeltaSlicef(expected interface{}, actual interface{}, del
// InDeltaf asserts that the two numerals are within delta of each other.
//
-// a.InDeltaf(math.Pi, (22 / 7.0, "error message %s", "formatted"), 0.01)
+// a.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted")
func (a *Assertions) InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{}) {
if h, ok := a.t.(tHelper); ok {
h.Helper()
|
Fix InDelta docstring
* Fixed the docstring for the InDelta function.
|
stretchr_testify
|
train
|
b467027972fc5db080029e81395be73910c089c9
|
diff --git a/website/config.rb b/website/config.rb
index <HASH>..<HASH> 100644
--- a/website/config.rb
+++ b/website/config.rb
@@ -2,7 +2,7 @@ set :base_url, "https://www.packer.io/"
activate :hashicorp do |h|
h.name = "packer"
- h.version = "1.4.4"
+ h.version = "1.4.5"
h.github_slug = "hashicorp/packer"
h.website_root = "website"
end
|
Update config.rb
for <I>
|
hashicorp_packer
|
train
|
cddc6126cc5a27d440ecb162da8cd7c8025f3036
|
diff --git a/bcbio/bam/trim.py b/bcbio/bam/trim.py
index <HASH>..<HASH> 100644
--- a/bcbio/bam/trim.py
+++ b/bcbio/bam/trim.py
@@ -26,7 +26,7 @@ QUALITY_FLAGS = {5: ['"E"', '"&"'],
20: ['"T"', '"5"']}
def trim_adapters(fastq_files, dirs, config):
- QUALITY_CUTOFF = 20
+ QUALITY_CUTOFF = 5
to_trim = _get_sequences_to_trim(config)
resources = config_utils.get_resources("AlienTrimmer", config)
try:
@@ -60,7 +60,7 @@ def trim_adapters(fastq_files, dirs, config):
if all(map(file_exists, [fastq1_out, fastq2_out])):
return [fastq1_out, fastq2_out]
base_cmd += ("-if {fastq1} -ir {fastq2} -of {tx_fastq1_out} "
- "-or {tx_fastq2_out} -c {temp_file}")
+ "-or {tx_fastq2_out} -c {temp_file} {quality_flag}")
message = ("Trimming %s from %s and %s with AlienTrimmer."
% (to_trim, fastq1, fastq2))
with tempfile.NamedTemporaryFile(delete=False) as temp:
|
Change default trimming quality to 5 down from <I>.
I think this is the correct way of looking at this debate:
<URL>
|
bcbio_bcbio-nextgen
|
train
|
5f7875c4661370129943a94eed616ee17089d5ac
|
diff --git a/core/server/src/main/java/alluxio/worker/AlluxioWorker.java b/core/server/src/main/java/alluxio/worker/AlluxioWorker.java
index <HASH>..<HASH> 100644
--- a/core/server/src/main/java/alluxio/worker/AlluxioWorker.java
+++ b/core/server/src/main/java/alluxio/worker/AlluxioWorker.java
@@ -16,6 +16,7 @@ import alluxio.Constants;
import alluxio.Version;
import alluxio.metrics.MetricsSystem;
import alluxio.security.authentication.AuthenticationUtils;
+import alluxio.util.CommonUtils;
import alluxio.util.network.NetworkAddressUtils;
import alluxio.util.network.NetworkAddressUtils.ServiceType;
import alluxio.web.UIWebServer;
@@ -97,6 +98,9 @@ public final class AlluxioWorker {
/** The worker serving file system operations. */
private FileSystemWorker mFileSystemWorker;
+ /** Server for data requests and responses. */
+ private DataServer mDataServer;
+
/** A list of extra workers to launch based on service loader. */
private List<Worker> mAdditionalWorkers;
@@ -171,6 +175,13 @@ public final class AlluxioWorker {
mConfiguration.set(Constants.WORKER_RPC_PORT, Integer.toString(mRPCPort));
mThriftServer = createThriftServer();
+ // Setup Data server
+ mDataServer = DataServer.Factory.create(
+ NetworkAddressUtils.getBindAddress(ServiceType.WORKER_DATA, mConfiguration),
+ mBlockWorker, mConfiguration);
+ // Reset data server port
+ mConfiguration.set(Constants.WORKER_DATA_PORT, Integer.toString(mDataServer.getPort()));
+
mWorkerAddress =
NetworkAddressUtils.getConnectAddress(NetworkAddressUtils.ServiceType.WORKER_RPC,
mConfiguration);
@@ -317,7 +328,8 @@ public final class AlluxioWorker {
mBlockWorker.stop();
}
- private void stopServing() {
+ private void stopServing() throws IOException {
+ mDataServer.close();
mThriftServer.stop();
mThriftServerSocket.close();
mWorkerMetricsSystem.stop();
@@ -327,6 +339,13 @@ public final class AlluxioWorker {
LOG.error("Failed to stop web server", e);
}
mWorkerMetricsSystem.stop();
+
+ // TODO(binfan): investigate why we need to close dataserver again. There used to be a comment
+ // saying the reason to stop and close again is due to some issues in Thrift.
+ while (!mDataServer.isClosed()) {
+ mDataServer.close();
+ CommonUtils.sleepMs(100);
+ }
}
private void registerServices(TMultiplexedProcessor processor, Map<String, TProcessor> services) {
diff --git a/core/server/src/main/java/alluxio/worker/block/BlockWorker.java b/core/server/src/main/java/alluxio/worker/block/BlockWorker.java
index <HASH>..<HASH> 100644
--- a/core/server/src/main/java/alluxio/worker/block/BlockWorker.java
+++ b/core/server/src/main/java/alluxio/worker/block/BlockWorker.java
@@ -81,9 +81,6 @@ public final class BlockWorker extends AbstractWorker {
/** Logic for handling RPC requests. */
private final BlockWorkerClientServiceHandler mServiceHandler;
- /** Server for data requests and responses. */
- private final DataServer mDataServer;
-
/** Client for all block master communication. */
private final BlockMasterClient mBlockMasterClient;
@@ -149,13 +146,6 @@ public final class BlockWorker extends AbstractWorker {
mFileSystemMasterClient = new FileSystemMasterClient(
NetworkAddressUtils.getConnectAddress(ServiceType.MASTER_RPC, mConf), mConf);
- // Setup DataServer
- mDataServer = DataServer.Factory.create(
- NetworkAddressUtils.getBindAddress(ServiceType.WORKER_DATA, mConf),
- this, mConf);
- // Reset data server port
- mConf.set(Constants.WORKER_DATA_PORT, Integer.toString(mDataServer.getPort()));
-
// Setup RPC ServerHandler
mServiceHandler = new BlockWorkerClientServiceHandler(this);
@@ -240,8 +230,6 @@ public final class BlockWorker extends AbstractWorker {
*/
@Override
public void stop() throws IOException {
- mDataServer.close();
-
mSessionCleanerThread.stop();
mBlockMasterClient.close();
if (mSpaceReserver != null) {
@@ -250,13 +238,6 @@ public final class BlockWorker extends AbstractWorker {
mFileSystemMasterClient.close();
// Use shutdownNow because HeartbeatThreads never finish until they are interrupted
getExecutorService().shutdownNow();
-
- // TODO(binfan): investigate why we need to close dataserver again. There used to be a comment
- // saying the reason to stop and close again is due to some issues in Thrift.
- while (!mDataServer.isClosed()) {
- mDataServer.close();
- CommonUtils.sleepMs(100);
- }
}
/**
|
Move data server to Alluxio Worker.
|
Alluxio_alluxio
|
train
|
2e93959475922ad982ecd71bad85e5366f7610da
|
diff --git a/openquake/commonlib/logictree.py b/openquake/commonlib/logictree.py
index <HASH>..<HASH> 100644
--- a/openquake/commonlib/logictree.py
+++ b/openquake/commonlib/logictree.py
@@ -1250,16 +1250,21 @@ class GsimLogicTree(object):
weights.append(weight)
branch_id = branch['branchID']
uncertainty = branch.uncertaintyModel
- gsim_name = uncertainty.text.strip()
- if gsim_name == 'GMPETable':
- # a bit hackish: set the GMPE_DIR equal to the
- # directory where the gsim_logic_tree file is
- GMPETable.GMPE_DIR = os.path.dirname(self.fname)
- try:
- gsim = valid.gsim(gsim_name, **uncertainty.attrib)
- except:
- etype, exc, tb = sys.exc_info()
- raise_(etype, "%s in file %s" % (exc, self.fname), tb)
+ if hasattr(uncertainty.text, 'strip'): # a string
+ gsim_name = uncertainty.text.strip()
+ if gsim_name == 'GMPETable':
+ # a bit hackish: set the GMPE_DIR equal to the
+ # directory where the gsim_logic_tree file is
+ GMPETable.GMPE_DIR = os.path.dirname(self.fname)
+ try:
+ gsim = valid.gsim(gsim_name, **uncertainty.attrib)
+ except:
+ etype, exc, tb = sys.exc_info()
+ raise_(etype, "%s in file %s" % (exc, self.fname),
+ tb)
+ uncertainty.text = gsim
+ else: # already converted GSIM
+ gsim = uncertainty.text
self.values[trt].append(gsim)
bt = BranchTuple(
branchset, branch_id, gsim, weight, effective)
@@ -1282,6 +1287,15 @@ class GsimLogicTree(object):
idx = self.all_trts.index(trt)
return rlz.value[idx]
+ def get_sorted_gsims(self):
+ gsims = set()
+ for vals in self.values.values():
+ gsims.update(vals)
+ gsims = sorted(gsims)
+ for i, gsim in enumerate(gsims):
+ gsim.idx = i
+ return gsims
+
def get_gsims(self, trt, rlzs=None):
"""
:param trt: tectonic region type
|
Avoided multiple validation of GSIMs [skip hazardlib]
|
gem_oq-engine
|
train
|
ce5044eafcd5681a5398350deb3bef785c0b3682
|
diff --git a/src-gwt/org/opencms/gwt/client/ui/CmsListItemWidget.java b/src-gwt/org/opencms/gwt/client/ui/CmsListItemWidget.java
index <HASH>..<HASH> 100644
--- a/src-gwt/org/opencms/gwt/client/ui/CmsListItemWidget.java
+++ b/src-gwt/org/opencms/gwt/client/ui/CmsListItemWidget.java
@@ -36,6 +36,7 @@ import org.opencms.gwt.client.ui.css.I_CmsInputLayoutBundle;
import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle;
import org.opencms.gwt.client.ui.css.I_CmsLayoutBundle.I_CmsListItemWidgetCss;
import org.opencms.gwt.client.ui.input.CmsLabel;
+import org.opencms.gwt.client.util.CmsDebugLog;
import org.opencms.gwt.client.util.CmsDomUtil;
import org.opencms.gwt.client.util.CmsResourceStateUtil;
import org.opencms.gwt.client.util.CmsStyleVariable;
@@ -843,10 +844,15 @@ HasClickHandlers, HasDoubleClickHandlers, HasMouseOverHandlers, I_CmsTruncable {
if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(m_subtitleSuffix.getText())) {
m_subtitleSuffix.getElement().getStyle().clearWidth();
int suffixWidth = m_subtitleSuffix.getOffsetWidth();
+ CmsDebugLog.getInstance().printLine("suffix '" + m_subtitleSuffix.getText() + "' width: " + suffixWidth);
if (suffixWidth <= 0) {
// in case the suffix is not rendered yet and no width is available, use truncation
- m_subtitleSuffix.truncate(textMetricsPrefix + "_STSUFFIX", 100);
suffixWidth = 100;
+ m_subtitleSuffix.truncate(textMetricsPrefix + "_STSUFFIX", suffixWidth);
+ }
+ if (suffixWidth > 200) {
+ suffixWidth = 200;
+ m_subtitleSuffix.truncate(textMetricsPrefix + "_STSUFFIX", suffixWidth);
}
m_subtitle.truncate(textMetricsPrefix + TM_SUBTITLE, width - suffixWidth - 10);
} else {
|
Improving truncation.
|
alkacon_opencms-core
|
train
|
aa2222af6a4a04c7f4f9edfe06ac2fb35967e02f
|
diff --git a/pysos/target.py b/pysos/target.py
index <HASH>..<HASH> 100644
--- a/pysos/target.py
+++ b/pysos/target.py
@@ -24,7 +24,8 @@ import sys
import types
import hashlib
import shutil
-from .utils import env, Error, WorkflowDict
+import fasteners
+from .utils import env, Error, WorkflowDict, short_repr
from .sos_eval import Undetermined
__all__ = ['dynamic', 'executable']
@@ -341,6 +342,15 @@ class RuntimeInfo:
raise RuntimeError('Failed to create runtime directory {}: {}'.format(sig_path, e))
self.proc_info = '{}.exe_info'.format(info_file)
+ self.lock = fasteners.InterProcessLock(self.proc_info)
+ if not self.lock.acquire(blocking=False):
+ env.logger.warning('Waiting for a lock for output files {}'.format(short_repr(self.output_files)))
+ if not self.lock.acquire(blocking=True):
+ raise RuntimeError('Failed to obtain a lock')
+
+ def __del__(self):
+ self.lock.release()
+
def set(self, files, file_type):
# add signature file if input and output files are dynamic
env.logger.trace('Set {} of signature to {}'.format(file_type, files))
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -169,6 +169,8 @@ setup(name = "sos",
cmdclass={'install': InstallWithConfigurations},
install_requires=[
'psutil',
+ # for file lock
+ 'fasteners',
'pyyaml',
'docker-py',
'blessings',
|
Lock signature file to avoid multiple processes working on the same step. #<I>, #<I>
|
vatlab_SoS
|
train
|
8799919f5e07133cbbd1a4c31cab696a66607593
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -2,8 +2,8 @@
"name": "prosemirror-collab",
"version": "1.2.0",
"description": "Collaborative editing for ProseMirror",
- "main": "dist/collab.js",
- "module": "src/collab.js",
+ "main": "dist/index.js",
+ "module": "dist/index.mjs",
"license": "MIT",
"maintainers": [
{
diff --git a/rollup.config.js b/rollup.config.js
index <HASH>..<HASH> 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -1,12 +1,14 @@
-import buble from '@rollup/plugin-buble'
-
-export default {
+module.exports = {
input: './src/collab.js',
- output: {
- dir: 'dist',
+ output: [{
+ file: 'dist/index.js',
format: 'cjs',
sourcemap: true
- },
- plugins: [buble()],
+ }, {
+ file: 'dist/index.mjs',
+ format: 'es',
+ sourcemap: true
+ }],
+ plugins: [require('@rollup/plugin-buble')()],
external(id) { return !/^[\.\/]/.test(id) }
}
diff --git a/test/test-collab.js b/test/test-collab.js
index <HASH>..<HASH> 100644
--- a/test/test-collab.js
+++ b/test/test-collab.js
@@ -3,7 +3,7 @@ const {history, undo, redo, closeHistory} = require("prosemirror-history")
const {schema, eq, doc, p} = require("prosemirror-test-builder")
const ist = require("ist")
-const {collab, receiveTransaction, sendableSteps} = require("../dist/collab")
+const {collab, receiveTransaction, sendableSteps} = require("..")
const histPlugin = history()
diff --git a/test/test-rebase.js b/test/test-rebase.js
index <HASH>..<HASH> 100644
--- a/test/test-rebase.js
+++ b/test/test-rebase.js
@@ -2,7 +2,7 @@ const {Transform} = require("prosemirror-transform")
const ist = require("ist")
const {schema, eq, doc, blockquote, p, li, ul, em} = require("prosemirror-test-builder")
-const {rebaseSteps} = require("../dist/collab")
+const {rebaseSteps} = require("..")
function runRebase(transforms, expected) {
let start = transforms[0].before, full = new Transform(start)
|
Output a bundled, Bublé-ed mjs file in dist/
FIX: The file referred to in the package's `module` field now is
compiled down to ES5.
Issue prosemirror/prosemirror#<I>
|
ProseMirror_prosemirror-collab
|
train
|
2da469bbc6b31006c8b57a8396992e79071bb744
|
diff --git a/test/pack.js b/test/pack.js
index <HASH>..<HASH> 100644
--- a/test/pack.js
+++ b/test/pack.js
@@ -422,8 +422,8 @@ packTest('Performing packing YUV422P10 to 420P',
t.notOk(err, 'no error expected');
},
function (t, packer, done) {
- var width = 8;
- var height = 2;
+ var width = 1280;
+ var height = 720;
var srcTags = makeTags(width, height, 'YUV422P10', 0);
var dstTags = makeTags(width, height, '420P', 0);
var dstBufLen = packer.setInfo(srcTags, dstTags);
|
Undo temp change now packer is fixed
|
Streampunk_codecadon
|
train
|
b1956054c86af9f5f433fbb3113ef798747a8885
|
diff --git a/mangooio-core/src/main/java/io/mangoo/utils/TwoFactorUtils.java b/mangooio-core/src/main/java/io/mangoo/utils/TwoFactorUtils.java
index <HASH>..<HASH> 100644
--- a/mangooio-core/src/main/java/io/mangoo/utils/TwoFactorUtils.java
+++ b/mangooio-core/src/main/java/io/mangoo/utils/TwoFactorUtils.java
@@ -79,6 +79,8 @@ public final class TwoFactorUtils {
* @return The current number to be checked
*/
public static String generateCurrentNumber(String secret) {
+ Objects.requireNonNull(secret, "secret can not be null");
+
return generateCurrentNumber(secret, System.currentTimeMillis());
}
@@ -135,6 +137,9 @@ public final class TwoFactorUtils {
* @return A URL to the Google charts API
*/
public static String getQRCode(String accountName, String secret) {
+ Objects.requireNonNull(accountName, "accountName can not be null");
+ Objects.requireNonNull(secret, "secret can not be null");
+
final StringBuilder buffer = new StringBuilder(128);
buffer.append("https://chart.googleapis.com/chart")
.append("?chs=200x200&cht=qr&chl=200x200&chld=M|0&cht=qr&chl=")
|
added validations to getQRCode and generateCurrentNumber
|
svenkubiak_mangooio
|
train
|
58970a9d2a7fe0e2a663feaf46cc490666affccb
|
diff --git a/go/cmd/vtgate/vtgate.go b/go/cmd/vtgate/vtgate.go
index <HASH>..<HASH> 100644
--- a/go/cmd/vtgate/vtgate.go
+++ b/go/cmd/vtgate/vtgate.go
@@ -27,7 +27,7 @@ var (
connTimeoutPerConn = flag.Duration("conn-timeout-per-conn", 1500*time.Millisecond, "vttablet connection timeout (per connection)")
connLife = flag.Duration("conn-life", 365*24*time.Hour, "average life of vttablet connections")
maxInFlight = flag.Int("max-in-flight", 0, "maximum number of calls to allow simultaneously")
- healthCheckRetryDelay = flag.Duration("healthcheck_retry_delay", 200*time.Millisecond, "health check retry delay")
+ healthCheckRetryDelay = flag.Duration("healthcheck_retry_delay", 5*time.Second, "health check retry delay")
testGateway = flag.String("test_gateway", "", "additional gateway to test health check module")
)
|
Change healthcheck retry delay default to 5s.
|
vitessio_vitess
|
train
|
06e0ee968a8cba1c7e249192c70bc837245c8d8e
|
diff --git a/commons/util/src/main/java/net/automatalib/commons/util/collections/BatchingIterator.java b/commons/util/src/main/java/net/automatalib/commons/util/collections/BatchingIterator.java
index <HASH>..<HASH> 100644
--- a/commons/util/src/main/java/net/automatalib/commons/util/collections/BatchingIterator.java
+++ b/commons/util/src/main/java/net/automatalib/commons/util/collections/BatchingIterator.java
@@ -60,7 +60,7 @@ public class BatchingIterator<T> implements Iterator<List<T>> {
this.batch.clear();
- while (source.hasNext() && batch.size() < batchSize) {
+ while (batch.size() < batchSize && source.hasNext()) {
batch.add(source.next());
}
|
fix order of BatchingIterator check
By checking our internal batch size first and then the source iterator, we can
prevent a call to the source iterator's hasNext() method and therefore save a
potential (on-demand) creation of its next() object.
|
LearnLib_automatalib
|
train
|
d381cf9a0542bfe84e97bd98054abfa101160456
|
diff --git a/libmc/__init__.py b/libmc/__init__.py
index <HASH>..<HASH> 100644
--- a/libmc/__init__.py
+++ b/libmc/__init__.py
@@ -28,10 +28,10 @@ from ._client import (
)
__VERSION__ = "0.5.6"
-__version__ = "v0.5.6-2-g7a965e8"
-__author__ = "mckelvin"
+__version__ = "v0.5.6-4-g0112646"
+__author__ = "PAN, Myautsai"
__email__ = "mckelvin@users.noreply.github.com"
-__date__ = "Wed Nov 4 15:41:18 2015 +0800"
+__date__ = "Thu Feb 4 18:35:05 2016 +0800"
class Client(PyClient):
diff --git a/src/Parser.cpp b/src/Parser.cpp
index <HASH>..<HASH> 100644
--- a/src/Parser.cpp
+++ b/src/Parser.cpp
@@ -256,7 +256,7 @@ int PacketParser::start_state(err_code_t& err) {
}
// log_info("start_state with %c", c1);
-
+#ifndef NDEBUG
#define EXPECT_BYTES(S, N) \
do { \
m_buffer_reader->expectBytes(err, (S), (N)); \
@@ -264,6 +264,15 @@ int PacketParser::start_state(err_code_t& err) {
return 0; \
} \
} while (0)
+#else
+#define EXPECT_BYTES(S, N) \
+ do { \
+ m_buffer_reader->skipBytes(err, (N)); \
+ if (err != RET_OK) { \
+ return 0; \
+ } \
+ } while (0)
+#endif
switch (c1) {
case 'V':
@@ -433,6 +442,8 @@ int PacketParser::start_state(err_code_t& err) {
break;
}
return 0;
+
+#undef EXPECT_BYTES
}
diff --git a/src/version.go b/src/version.go
index <HASH>..<HASH> 100644
--- a/src/version.go
+++ b/src/version.go
@@ -1,9 +1,9 @@
package golibmc
-const _Version = "v0.5.6-2-g7a965e8"
-const _Author = "mckelvin"
+const _Version = "v0.5.6-4-g0112646"
+const _Author = "PAN, Myautsai"
const _Email = "mckelvin@users.noreply.github.com"
-const _Date = "Wed Nov 4 15:41:18 2015 +0800"
+const _Date = "Thu Feb 4 18:35:05 2016 +0800"
// Version of the package
const Version = _Version
|
PacketParser::start_state: skipBytes after checking first few bytes
Both the memcached protocol and the libmc software
are stable now. Code snippets where
`expectBytes` is used are more like assertions.
We don't need to check all of bytes in production
so let's just skip them using `skipBytes`.
|
douban_libmc
|
train
|
ae72998db764c05854f13c92fc9b0e23cdde2467
|
diff --git a/ext_tables.php b/ext_tables.php
index <HASH>..<HASH> 100755
--- a/ext_tables.php
+++ b/ext_tables.php
@@ -16,6 +16,7 @@ $TCA['tx_gridelements_backend_layout'] = array(
'origUid' => 't3_origuid',
'sortby' => 'sorting',
'delete' => 'deleted',
+ 'rootLevel' => -1,
'thumbnail' => 'resources',
'dividers2tabs' => TRUE,
'selicon_field' => 'icon',
|
[FEATURE] Enable creation of Gridelements on root level
Resolves #<I>
Change-Id: Iada<I>ce<I>a<I>c6d<I>d0c<I>d4a
Reviewed-on: <URL>
|
TYPO3-extensions_gridelements
|
train
|
530cd13ef57b9267d3e07fba8b0b9e35a2cc24d8
|
diff --git a/app/check.php b/app/check.php
index <HASH>..<HASH> 100644
--- a/app/check.php
+++ b/app/check.php
@@ -64,13 +64,14 @@ if (class_exists('Locale')) {
}
$accelerator =
- ((version_compare(phpversion('apc'), '3.0.17', '>=') && ini_get('apc.enabled'))
+ (function_exists('apc_store') && ini_get('apc.enabled'))
||
function_exists('eaccelerator_put') && ini_get('eaccelerator.enable')
||
function_exists('xcache_set')
;
check($accelerator, 'Checking that a PHP accelerator is installed', 'Install a PHP accelerator like APC (highly recommended)', false);
+check(function_exists('apc_store') && ini_get('apc.enabled') && version_compare(phpversion('apc'), '3.0.17', '>='), 'Checking that the APC version is at least 3.0.17', 'Upgrade your intl extension with a newer ICU version (4+)', true);
check(!ini_get('short_open_tag'), 'Checking that php.ini has short_open_tag set to off', 'Set short_open_tag to off in php.ini', false);
check(!ini_get('magic_quotes_gpc'), 'Checking that php.ini has magic_quotes_gpc set to off', 'Set magic_quotes_gpc to off in php.ini', false);
|
Check APC version after for app/check
|
symfony_symfony-standard
|
train
|
1dc43e6f4bc92a7997d6893fc13a8047cbb76edf
|
diff --git a/babelsdk/babel/lexer.py b/babelsdk/babel/lexer.py
index <HASH>..<HASH> 100644
--- a/babelsdk/babel/lexer.py
+++ b/babelsdk/babel/lexer.py
@@ -180,7 +180,7 @@ class BabelLexer(object):
return token
def t_NULL(self, token):
- r'\bnull\b'
+ r'\bNull\b'
token.value = BabelNull
return token
diff --git a/babelsdk/babel/parser.py b/babelsdk/babel/parser.py
index <HASH>..<HASH> 100644
--- a/babelsdk/babel/parser.py
+++ b/babelsdk/babel/parser.py
@@ -134,6 +134,16 @@ class BabelField(object):
self.data_type_attrs,
)
+class BabelSegment(object):
+ def __init__(self, data_type_name, name):
+ self.data_type_name = data_type_name
+ self.name = name
+ def __repr__(self):
+ return 'BabelSegment({!r}, {!r})'.format(
+ self.data_type_name,
+ self.name,
+ )
+
class BabelParser(object):
"""
Due to how ply.yacc works, the docstring of each parser method is a BNF
@@ -261,12 +271,31 @@ class BabelParser(object):
for label, text, example in p[8]:
p[0].add_example(label, text, example)
+ def p_segment(self, p):
+ """segment : ID ID NEWLINE
+ | ID NEWLINE"""
+ if p[2].strip() == '':
+ p[0] = BabelSegment(p[1], None)
+ else:
+ p[0] = BabelSegment(p[2], p[1])
+
+ def p_segment_list_create(self, p):
+ """segment_list : segment
+ | empty"""
+ if p[1] is not None:
+ p[0] = [p[1]]
+
+ def p_segment_list_extend(self, p):
+ 'segment_list : segment_list segment'
+ p[0] = p[1]
+ p[0].append(p[2])
+
def p_statement_request_section(self, p):
- """reqsection : REQUEST NEWLINE INDENT field_list DEDENT"""
+ """reqsection : REQUEST NEWLINE INDENT segment_list DEDENT"""
p[0] = p[4]
def p_statement_response_section(self, p):
- """respsection : RESPONSE NEWLINE INDENT field_list DEDENT"""
+ """respsection : RESPONSE NEWLINE INDENT segment_list DEDENT"""
p[0] = p[4]
def p_statement_error_section(self, p):
diff --git a/babelsdk/babel/tower.py b/babelsdk/babel/tower.py
index <HASH>..<HASH> 100644
--- a/babelsdk/babel/tower.py
+++ b/babelsdk/babel/tower.py
@@ -306,7 +306,4 @@ class TowerOfBabel(object):
raise Exception('Symbol %r is undefined' % data_type_name)
data_type = env.get(data_type_name)
- if not isinstance(data_type, Union):
- raise Exception('%r must be a Union data type' % data_type_name)
-
return data_type
diff --git a/babelsdk/generator/generator.py b/babelsdk/generator/generator.py
index <HASH>..<HASH> 100644
--- a/babelsdk/generator/generator.py
+++ b/babelsdk/generator/generator.py
@@ -127,7 +127,7 @@ class CodeGenerator(object):
raise NotImplemented
-class CodeGeneratorMonoLingual(CodeGenerator):
+class CodeGeneratorMonolingual(CodeGenerator):
"""Identical to CodeGenerator, except that an additional attribute `lang`
exists."""
@@ -136,4 +136,4 @@ class CodeGeneratorMonoLingual(CodeGenerator):
def __init__(self, api, target_folder_path):
assert self.lang, 'Language must be specified'
- super(CodeGeneratorMonoLingual, self).__init__(api, target_folder_path)
+ super(CodeGeneratorMonolingual, self).__init__(api, target_folder_path)
diff --git a/babelsdk/segmentation.py b/babelsdk/segmentation.py
index <HASH>..<HASH> 100644
--- a/babelsdk/segmentation.py
+++ b/babelsdk/segmentation.py
@@ -12,7 +12,7 @@ from babelsdk.data_type import (
class Segment(object):
"""
- One part of a segmentation.
+ One segment of a segmentation.
"""
def __init__(self, name, data_type):
"""
|
1. Errors don't have to be unions.
2. null -> Null
3. Segments no longer need to be named.
|
dropbox_stone
|
train
|
4505b50e3cc12da15ce88d457794f174b0c11396
|
diff --git a/pyecharts/charts/bar.py b/pyecharts/charts/bar.py
index <HASH>..<HASH> 100644
--- a/pyecharts/charts/bar.py
+++ b/pyecharts/charts/bar.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python
# coding=utf-8
from pyecharts.chart import Chart
diff --git a/pyecharts/charts/effectscatter.py b/pyecharts/charts/effectscatter.py
index <HASH>..<HASH> 100644
--- a/pyecharts/charts/effectscatter.py
+++ b/pyecharts/charts/effectscatter.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python
# coding=utf-8
from pyecharts.charts.scatter import Scatter
diff --git a/pyecharts/charts/graph.py b/pyecharts/charts/graph.py
index <HASH>..<HASH> 100644
--- a/pyecharts/charts/graph.py
+++ b/pyecharts/charts/graph.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python
# coding=utf-8
from pyecharts.chart import Chart
diff --git a/pyecharts/charts/line.py b/pyecharts/charts/line.py
index <HASH>..<HASH> 100644
--- a/pyecharts/charts/line.py
+++ b/pyecharts/charts/line.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python
# coding=utf-8
from pyecharts.chart import Chart
diff --git a/pyecharts/charts/polar.py b/pyecharts/charts/polar.py
index <HASH>..<HASH> 100644
--- a/pyecharts/charts/polar.py
+++ b/pyecharts/charts/polar.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python
# coding=utf-8
from pyecharts.chart import Chart
diff --git a/pyecharts/charts/scatter.py b/pyecharts/charts/scatter.py
index <HASH>..<HASH> 100644
--- a/pyecharts/charts/scatter.py
+++ b/pyecharts/charts/scatter.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python
# coding=utf-8
from PIL import Image
diff --git a/pyecharts/option.py b/pyecharts/option.py
index <HASH>..<HASH> 100644
--- a/pyecharts/option.py
+++ b/pyecharts/option.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python
# coding=utf-8
from __future__ import unicode_literals
|
:fire: uselesss lines for python library
|
pyecharts_pyecharts
|
train
|
f113b4522b2e7c055b4490c63d0d25f08af7b0c6
|
diff --git a/src/Bonnier/WP/Cxense/Settings/Partials/CustomTaxonomiesSettings.php b/src/Bonnier/WP/Cxense/Settings/Partials/CustomTaxonomiesSettings.php
index <HASH>..<HASH> 100644
--- a/src/Bonnier/WP/Cxense/Settings/Partials/CustomTaxonomiesSettings.php
+++ b/src/Bonnier/WP/Cxense/Settings/Partials/CustomTaxonomiesSettings.php
@@ -67,6 +67,7 @@ class CustomTaxonomiesSettings
}
private static function get_enabled_taxonomies() {
- return array_diff(get_taxonomies(), static::DISABLED_TAXONOMIES);
+ // return array values to get a numbered array rather than associative ie. ['category' => 'category']
+ return array_values(array_diff(get_taxonomies(), static::DISABLED_TAXONOMIES));
}
}
|
Small update to the logic of ordering search facets
|
BenjaminMedia_wp-cxense
|
train
|
9514ecda5cc2bd2a362e1848c96f41806d5c86df
|
diff --git a/src/main/org/codehaus/groovy/vmplugin/v7/IndyInterface.java b/src/main/org/codehaus/groovy/vmplugin/v7/IndyInterface.java
index <HASH>..<HASH> 100644
--- a/src/main/org/codehaus/groovy/vmplugin/v7/IndyInterface.java
+++ b/src/main/org/codehaus/groovy/vmplugin/v7/IndyInterface.java
@@ -72,13 +72,20 @@ public class IndyInterface {
/** boolean to indicate if logging for indy is enabled */
protected static final boolean LOG_ENABLED;
static {
+ boolean enableLogger = false;
+
LOG = Logger.getLogger(IndyInterface.class.getName());
- if (System.getProperty("groovy.indy.logging")!=null) {
- LOG.setLevel(Level.ALL);
- LOG_ENABLED = true;
- } else {
- LOG_ENABLED = false;
+
+ try {
+ if (System.getProperty("groovy.indy.logging")!=null) {
+ LOG.setLevel(Level.ALL);
+ enableLogger = true;
+ }
+ } catch (SecurityException e) {
+ // Allow security managers to prevent system property access
}
+
+ LOG_ENABLED = enableLogger;
}
/** LOOKUP constant used for for example unreflect calls */
public static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
|
GROOVY-<I>: Allow security managers to prevent system property access for Indy (closes #<I>)
|
apache_groovy
|
train
|
97431838ff66604c94c487113ca5345f86d45bb6
|
diff --git a/indra/sources/bel/api.py b/indra/sources/bel/api.py
index <HASH>..<HASH> 100644
--- a/indra/sources/bel/api.py
+++ b/indra/sources/bel/api.py
@@ -238,13 +238,13 @@ def process_json_file(file_name):
return process_pybel_graph(pybel_graph)
-def process_jgif_file(file_name):
- """Return a PybelProcessor by processing a JGIF JSON file.
+def process_cbn_jgif_file(file_name):
+ """Return a PybelProcessor by processing a CBN JGIF JSON file.
Parameters
----------
file_name : str
- The path to a JGIF JSON file.
+ The path to a CBN JGIF JSON file.
Returns
-------
|
More specific function name and docstring
|
sorgerlab_indra
|
train
|
87396de55daa7321110384e2391f3216474c87db
|
diff --git a/core/src/elements/ons-splitter-side.js b/core/src/elements/ons-splitter-side.js
index <HASH>..<HASH> 100644
--- a/core/src/elements/ons-splitter-side.js
+++ b/core/src/elements/ons-splitter-side.js
@@ -693,10 +693,6 @@ class SplitterSideElement extends BaseElement {
this._page = null;
this._isAttached = false;
- if (!this.hasAttribute('side')) {
- this.setAttribute('side', 'left');
- }
-
this._collapseStrategy = new CollapseDetection();
this._animatorFactory = new AnimatorFactory({
animators: window.OnsSplitterElement._animatorDict,
@@ -716,7 +712,7 @@ class SplitterSideElement extends BaseElement {
this._updateForAnimationAttribute();
this._updateForWidthAttribute();
- this._updateForSideAttribute();
+ this.hasAttribute('side') ? this._updateForSideAttribute() : this.setAttribute('side', 'left');
this._updateForCollapseAttribute();
this._updateForSwipeableAttribute();
this._updateForSwipeTargetWidthAttribute();
@@ -775,7 +771,7 @@ class SplitterSideElement extends BaseElement {
const collapse = ('' + this.getAttribute('collapse')).trim();
- if (collapse === '' || collapse === 'true') {
+ if (collapse === '') {
this._updateCollapseStrategy(new StaticCollapseDetection());
} else if (collapse === 'portrait' || collapse === 'landscape') {
this._updateCollapseStrategy(new OrientationCollapseDetection(collapse));
|
fix(ons-spliter-side): Delay some functionality.
|
OnsenUI_OnsenUI
|
train
|
1dc21f08efd52ed9a31ab401e64c8913f400f845
|
diff --git a/src/DebugBar/DebugBar.php b/src/DebugBar/DebugBar.php
index <HASH>..<HASH> 100644
--- a/src/DebugBar/DebugBar.php
+++ b/src/DebugBar/DebugBar.php
@@ -316,7 +316,11 @@ class DebugBar implements ArrayAccess
*/
public function hasStackedData()
{
- $http = $this->initStackSession();
+ try {
+ $http = $this->initStackSession();
+ } catch (DebugBarException $e) {
+ return false;
+ }
return count($http->getSessionValue($this->stackSessionNamespace)) > 0;
}
|
added try/catch block to catch unused session is hasStackedData()
|
maximebf_php-debugbar
|
train
|
8067bb1fe6d5767d59000ce3c0195447a4e190f4
|
diff --git a/tests/test_appengine.py b/tests/test_appengine.py
index <HASH>..<HASH> 100644
--- a/tests/test_appengine.py
+++ b/tests/test_appengine.py
@@ -497,9 +497,9 @@ class DecoratorTests(unittest.TestCase):
class TestRequiredHandler(webapp2.RequestHandler):
@decorator.oauth_required
def get(self):
- if decorator.has_credentials():
- parent.had_credentials = True
- parent.found_credentials = decorator.credentials
+ parent.assertTrue(decorator.has_credentials())
+ parent.had_credentials = True
+ parent.found_credentials = decorator.credentials
if parent.should_raise:
raise Exception('')
|
Fix App Engine test branch miss.
In an App Engine / webapp2.RequestHandler method that has
been decorated with @decorator.oauth_required, a redirect
will occur if decorator.has_credentials() is False, so the
branch "if decorator.has_credentials()" always occurs and the
other one never will.
|
googleapis_oauth2client
|
train
|
ce39ab1a8d0b2fda9469a074082366dd4710029f
|
diff --git a/spyder_notebook/notebookplugin.py b/spyder_notebook/notebookplugin.py
index <HASH>..<HASH> 100644
--- a/spyder_notebook/notebookplugin.py
+++ b/spyder_notebook/notebookplugin.py
@@ -15,6 +15,7 @@ import sys
from qtpy import PYQT4, PYSIDE
from qtpy.compat import getsavefilename, getopenfilenames
from qtpy.QtCore import Qt, QEventLoop, QTimer, Signal
+from qtpy.QtGui import QIcon
from qtpy.QtWidgets import QApplication, QMessageBox, QVBoxLayout, QMenu
# Third-party imports
@@ -27,6 +28,7 @@ from spyder.utils import icon_manager as ima
from spyder.utils.programs import get_temp_dir
from spyder.utils.qthelpers import (create_action, create_toolbutton,
add_actions, MENU_SEPARATOR)
+from spyder.utils.switcher import shorten_paths
from spyder.widgets.tabs import Tabs
@@ -180,10 +182,13 @@ class NotebookPlugin(SpyderPluginWidget):
self.focus_changed.connect(self.main.plugin_focus_changed)
self.ipyconsole = self.main.ipyconsole
self.create_new_client(give_focus=False)
- # TODO Convert to new Switcher
- # icon_path = os.path.join(PACKAGE_PATH, 'images', 'icon.svg')
- # self.main.add_to_fileswitcher(self, self.tabwidget, self.clients,
- # QIcon(icon_path))
+
+ # Connect to switcher
+ self.switcher = self.main.switcher
+ self.switcher.sig_mode_selected.connect(self.handle_switcher_modes)
+ self.switcher.sig_item_selected.connect(
+ self.handle_switcher_selection)
+
self.recent_notebook_menu.aboutToShow.connect(self.setup_menu_actions)
def check_compatibility(self):
@@ -456,11 +461,45 @@ class NotebookPlugin(SpyderPluginWidget):
self.clients.insert(index_to, client)
# ------ Public API (for FileSwitcher) ------------------------------------
- def set_stack_index(self, index, instance):
- """Set the index of the current notebook."""
- if instance == self:
- self.tabwidget.setCurrentIndex(index)
-
- def get_current_tab_manager(self):
- """Get the widget with the TabWidget attribute."""
- return self
+ def handle_switcher_modes(self, mode):
+ """
+ Populate switcher with opened notebooks.
+
+ List the file names of the opened notebooks with their directories in
+ the switcher. Only handle file mode, where `mode` is empty string.
+ """
+ if mode != '':
+ return
+
+ paths = [client.get_filename() for client in self.clients]
+ is_unsaved = [False for client in self.clients]
+ short_paths = shorten_paths(paths, is_unsaved)
+ icon = QIcon(os.path.join(PACKAGE_PATH, 'images', 'icon.svg'))
+ section = self.get_plugin_title()
+
+ for path, short_path, client in zip(paths, short_paths, self.clients):
+ title = osp.basename(path)
+ description = osp.dirname(path)
+ if len(path) > 75:
+ description = short_path
+ is_last_item = (client == self.clients[-1])
+ self.switcher.add_item(
+ title=title, description=description, icon=icon,
+ section=section, data=client, last_item=is_last_item)
+
+ def handle_switcher_selection(self, item, mode, search_text):
+ """
+ Handle user selecting item in switcher.
+
+ If the selected item is not in the section of the switcher that
+ corresponds to this plugin, then ignore it. Otherwise, switch to
+ selected item in notebook plugin and hide the switcher.
+ """
+ if item.get_section() != self.get_plugin_title():
+ return
+
+ client = item.get_data()
+ index = self.clients.index(client)
+ self.tabwidget.setCurrentIndex(index)
+ self.switch_to_plugin()
+ self.switcher.hide()
|
Interface to new Switcher introduced in Spyder 4
List all opened notebooks in the switcher, and switch to them if selected by
the user.
|
spyder-ide_spyder-notebook
|
train
|
95e828096e06bcfbf1ad0f63a6f34196f51c2753
|
diff --git a/src/css_composer/index.js b/src/css_composer/index.js
index <HASH>..<HASH> 100644
--- a/src/css_composer/index.js
+++ b/src/css_composer/index.js
@@ -27,7 +27,7 @@
* @module CssComposer
*/
-import { isArray } from 'underscore';
+import { isArray, isUndefined } from 'underscore';
import defaults from './config/config';
import CssRule from './model/CssRule';
import CssRules from './model/CssRules';
@@ -457,6 +457,21 @@ export default () => {
return selector && this.get(selector, state, media);
},
+ getComponentRules(cmp, opts = {}) {
+ let { state, mediaText, current } = opts;
+ if (current) {
+ state = em.get('state') || '';
+ mediaText = em.getCurrentMedia();
+ }
+ const id = cmp.getId();
+ const rules = this.getAll().filter(r => {
+ if (!isUndefined(state) && r.get('state') !== state) return;
+ if (!isUndefined(mediaText) && r.get('mediaText') !== mediaText) return;
+ return r.getSelectorsString() === `#${id}`;
+ });
+ return rules;
+ },
+
/**
* Render the block of CSS rules
* @return {HTMLElement}
|
Add getComponentRules to CssComposer
|
artf_grapesjs
|
train
|
c74fc81cc6b8152e8fedce6edead55b420fa5541
|
diff --git a/EntityService/TimespanService.php b/EntityService/TimespanService.php
index <HASH>..<HASH> 100755
--- a/EntityService/TimespanService.php
+++ b/EntityService/TimespanService.php
@@ -10,6 +10,7 @@
namespace CampaignChain\Hook\TimespanBundle\EntityService;
+use CampaignChain\CoreBundle\Entity\Hook;
use CampaignChain\CoreBundle\EntityService\HookServiceTriggerInterface;
use CampaignChain\Hook\TimespanBundle\Entity\Timespan;
use Doctrine\ORM\EntityManager;
@@ -27,7 +28,7 @@ class TimespanService implements HookServiceTriggerInterface
$this->em = $em;
}
- public function getHook($entity){
+ public function getHook($entity, $mode = Hook::MODE_DEFAULT){
$hook = new Timespan();
if(is_object($entity) && $entity->getId() !== null){
@@ -41,7 +42,6 @@ class TimespanService implements HookServiceTriggerInterface
}
public function processHook($entity, $hook){
- // TODO: Remove this hack to fix validation issue.
if(!$entity->getStartDate()){
$now = new \DateTime('now', new \DateTimeZone($hook->getTimezone()));
$entity->setStartDate($now);
|
CE-<I> Repeating campaign
|
CampaignChain_hook-timespan
|
train
|
37ffb17640c1774bb8eccd0b27812f92a2217eaf
|
diff --git a/src/document/DocumentCommandHandlers.js b/src/document/DocumentCommandHandlers.js
index <HASH>..<HASH> 100644
--- a/src/document/DocumentCommandHandlers.js
+++ b/src/document/DocumentCommandHandlers.js
@@ -1150,7 +1150,37 @@ define(function (require, exports, module) {
function handleFileDelete() {
var entry = ProjectManager.getSelectedItem();
- ProjectManager.deleteItem(entry);
+ if (entry.isDirectory) {
+ Dialogs.showModalDialog(
+ DefaultDialogs.DIALOG_ID_EXT_DELETED,
+ Strings.CONFIRM_FOLDER_DELETE_TITLE,
+ StringUtils.format(
+ Strings.CONFIRM_FOLDER_DELETE,
+ StringUtils.breakableUrl(entry.name)
+ ),
+ [
+ {
+ className : Dialogs.DIALOG_BTN_CLASS_NORMAL,
+ id : Dialogs.DIALOG_BTN_CANCEL,
+ text : Strings.CANCEL
+ },
+ {
+ className : Dialogs.DIALOG_BTN_CLASS_PRIMARY,
+ id : Dialogs.DIALOG_BTN_OK,
+ text : Strings.OK
+ }
+ ]
+ )
+ .done(function (id) {
+ if (id === Dialogs.DIALOG_BTN_CANCEL) {
+ return;
+ } else if (id === Dialogs.DIALOG_BTN_OK) {
+ ProjectManager.deleteItem(entry);
+ }
+ });
+ } else {
+ ProjectManager.deleteItem(entry);
+ }
}
/** Show the selected sidebar (tree or working set) item in Finder/Explorer */
|
Confirm folder delete modal fixes #<I>
|
adobe_brackets
|
train
|
0034862d8d4bce29bcc5442b4352659dd12566ac
|
diff --git a/angr/artifacts/function.py b/angr/artifacts/function.py
index <HASH>..<HASH> 100644
--- a/angr/artifacts/function.py
+++ b/angr/artifacts/function.py
@@ -85,7 +85,8 @@ class Function(object):
self.prepared_registers = set()
self.prepared_stack_variables = set()
self.registers_read_afterwards = set()
- self.blocks = { self._project.factory.block(addr) }
+ self.startpoint = self._project.factory.block(addr)
+ self.blocks = { self.startpoint }
def _add_block_by_addr(self, addr):
snippet = self._project.factory.snippet(addr)
@@ -186,11 +187,11 @@ class Function(object):
"""
constants = set()
- if not self._project.loader.main_bin.contains_addr(self.startpoint):
+ if not self._project.loader.main_bin.contains_addr(self._addr):
return constants
# reanalyze function with a new initial state (use persistent registers)
- initial_state = self._function_manager._cfg.get_any_irsb(self.startpoint).initial_state
+ initial_state = self._function_manager._cfg.get_any_irsb(self._addr).initial_state
fresh_state = self._project.factory.blank_state(mode="fastpath")
for reg in initial_state.arch.persistent_regs + ['ip']:
fresh_state.registers.store(reg, initial_state.registers.load(reg))
@@ -295,10 +296,6 @@ class Function(object):
return '<Function %s (%#x)>' % (self.name, self._addr)
@property
- def startpoint(self):
- return self._addr
-
- @property
def endpoints(self):
return list(self._ret_sites)
@@ -377,7 +374,7 @@ class Function(object):
@param return_site_addr The address of the basic block ending with a return
'''
- self._ret_sites.add(return_site_addr)
+ self._ret_sites.add(self._project.factory.block(return_site_addr))
def _add_call_site(self, call_site_addr, call_target_addr, retn_addr):
'''
@@ -467,7 +464,7 @@ class Function(object):
node_b = "%#08x" % to_block.addr
if node_b in self._ret_sites:
node_b += "[Ret]"
- if node_a in self._call_sites:
+ if node_a.addr in self._call_sites:
node_a += "[Call]"
tmp_graph.add_edge(node_a, node_b)
pos = networkx.graphviz_layout(tmp_graph, prog='fdp')
|
Make function startpoint and endpoints blocks
|
angr_angr
|
train
|
77bca129d6031571b4da1edf63b9f5ae93fc6ee2
|
diff --git a/lib/database_cleaner/active_record/truncation.rb b/lib/database_cleaner/active_record/truncation.rb
index <HASH>..<HASH> 100755
--- a/lib/database_cleaner/active_record/truncation.rb
+++ b/lib/database_cleaner/active_record/truncation.rb
@@ -24,6 +24,7 @@ module DatabaseCleaner
def database_cleaner_view_cache
@views ||= select_values("select table_name from information_schema.views where table_schema = '#{current_database}'") rescue []
end
+
def database_cleaner_table_cache
# the adapters don't do caching (#130) but we make the assumption that the list stays the same in tests
@database_cleaner_tables ||= tables
@@ -155,6 +156,15 @@ module DatabaseCleaner
truncate_tables(tables.select(&filter))
end
+ def database_cleaner_table_cache
+ # AR returns a list of tables without schema but then returns a
+ # migrations table with the schema. There are other problems, too,
+ # with using the base list. If a table exists in multiple schemas
+ # within the search path, truncation without the schema name could
+ # result in confusing, if not unexpected results.
+ @database_cleaner_tables ||= tables_with_schema
+ end
+
private
# Returns a boolean indicating if the given table has an auto-inc number higher than 0.
@@ -169,6 +179,15 @@ module DatabaseCleaner
def has_rows?(table)
select_value("SELECT true FROM #{table} LIMIT 1;")
end
+
+ def tables_with_schema
+ rows = select_rows <<-_SQL
+ SELECT schemaname || '.' || tablename
+ FROM pg_tables
+ WHERE tablename !~ '_prt_' AND schemaname = ANY (current_schemas(false))
+ _SQL
+ rows.collect { |result| result.first }
+ end
end
end
end
diff --git a/spec/database_cleaner/active_record/truncation/postgresql_spec.rb b/spec/database_cleaner/active_record/truncation/postgresql_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/database_cleaner/active_record/truncation/postgresql_spec.rb
+++ b/spec/database_cleaner/active_record/truncation/postgresql_spec.rb
@@ -35,6 +35,12 @@ module ActiveRecord
end
end
+ describe '#database_cleaner_table_cache' do
+ it 'should default to the list of tables with their schema' do
+ connection.database_cleaner_table_cache.first.should match(/^public\./)
+ end
+ end
+
it_behaves_like "an adapter with pre-count truncation" do
let(:connection) { active_record_pg_connection }
end
|
always return Postgres table names with schema to avoid awfulness
- without the schema, the migrations table gets truncated since the default AR method returns ‘public.schema_migrations’
- also a possibility is truncation of tables other than desired once since without the schema, Postgres has no way of knowing which table to truncate if two schemas have the same table
|
DatabaseCleaner_database_cleaner
|
train
|
5d8c4f6b039c13a26520f43f48010afb648dab7b
|
diff --git a/cmd/gb-vendor/main.go b/cmd/gb-vendor/main.go
index <HASH>..<HASH> 100644
--- a/cmd/gb-vendor/main.go
+++ b/cmd/gb-vendor/main.go
@@ -18,10 +18,7 @@ var (
)
func init() {
- fs.Usage = func() {
- printUsage(os.Stderr)
- os.Exit(2)
- }
+ fs.Usage = usage
}
var commands = []*cmd.Command{
@@ -43,8 +40,8 @@ func main() {
switch {
case len(args) < 1, args[0] == "-h", args[0] == "-help":
- fs.Usage()
- os.Exit(1)
+ printUsage(os.Stdout)
+ os.Exit(0)
case args[0] == "help":
help(args[1:])
return
diff --git a/cmd/gb/main.go b/cmd/gb/main.go
index <HASH>..<HASH> 100644
--- a/cmd/gb/main.go
+++ b/cmd/gb/main.go
@@ -63,9 +63,6 @@ func main() {
}
command = &cmd.Command{
Run: func(ctx *gb.Context, args []string) error {
- if len(args) < 1 {
- return fmt.Errorf("plugin: no command supplied")
- }
args = append([]string{plugin}, args...)
env := cmd.MergeEnv(os.Environ(), map[string]string{
|
Show vendor plugin help when no command is given
Fixes #<I>
|
constabulary_gb
|
train
|
c68ea67213765ce61c08f9da7bc3df01dc237234
|
diff --git a/discord/ui/view.py b/discord/ui/view.py
index <HASH>..<HASH> 100644
--- a/discord/ui/view.py
+++ b/discord/ui/view.py
@@ -158,16 +158,16 @@ class View:
__view_children_items__: ClassVar[List[ItemCallbackType[Any, Any]]] = []
def __init_subclass__(cls) -> None:
- children: List[ItemCallbackType[Any, Any]] = []
+ children: Dict[str, ItemCallbackType[Any, Any]] = {}
for base in reversed(cls.__mro__):
- for member in base.__dict__.values():
+ for name, member in base.__dict__.items():
if hasattr(member, '__discord_ui_model_type__'):
- children.append(member)
+ children[name] = member
if len(children) > 25:
raise TypeError('View cannot have more than 25 children')
- cls.__view_children_items__ = children
+ cls.__view_children_items__ = list(children.values())
def _init_children(self) -> List[Item[Self]]:
children = []
|
Properly handle inheritance overriding in View subclasses
|
Rapptz_discord.py
|
train
|
e73c98803912fd4b0e956b189dcb278dbbc73c7a
|
diff --git a/tests/VCR/LibraryHooks/CurlHookTest.php b/tests/VCR/LibraryHooks/CurlHookTest.php
index <HASH>..<HASH> 100644
--- a/tests/VCR/LibraryHooks/CurlHookTest.php
+++ b/tests/VCR/LibraryHooks/CurlHookTest.php
@@ -294,7 +294,8 @@ class CurlHookTest extends TestCase
curl_multi_add_handle($curlMultiHandle, $curlHandle1);
curl_multi_add_handle($curlMultiHandle, $curlHandle2);
- $mh = curl_multi_exec($curlMultiHandle);
+ $stillRunning = null;
+ $mh = curl_multi_exec($curlMultiHandle, $stillRunning);
$lastInfo = curl_multi_info_read($mh);
$secondLastInfo = curl_multi_info_read($mh);
@@ -337,9 +338,10 @@ class CurlHookTest extends TestCase
$curlHandle = curl_init('http://example.com');
+ $stillRunning = null;
$curlMultiHandle = curl_multi_init();
curl_multi_add_handle($curlMultiHandle, $curlHandle);
- curl_multi_exec($curlMultiHandle);
+ curl_multi_exec($curlMultiHandle, $stillRunning);
curl_multi_remove_handle($curlMultiHandle, $curlHandle);
curl_multi_close($curlMultiHandle);
}
|
U-Tests: LibraryHooks: CurlHookTest: pass second param to curl_multi_exec
|
php-vcr_php-vcr
|
train
|
2bbfc3a971f884ba2492771cfe85eaeac1d94f65
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -34,7 +34,7 @@ extras_require = {
],
'dev': [
"bumpversion",
- "flaky>=3.3.0",
+ "flaky>=3.7.0,<4",
"hypothesis>=3.31.2,<6",
"pytest>=4.4.0,<5.0.0",
"pytest-asyncio>=0.10.0,<0.11",
|
flaky was updated to work with pytest and python <I>. Prior to this, running single tests using pytest would error out on earlier versions of flaky.
|
ethereum_web3.py
|
train
|
bc003b2efdd3ae2025152b3291c80071a6b57ec3
|
diff --git a/lib/mincer/engines/jade_engine.js b/lib/mincer/engines/jade_engine.js
index <HASH>..<HASH> 100644
--- a/lib/mincer/engines/jade_engine.js
+++ b/lib/mincer/engines/jade_engine.js
@@ -27,6 +27,7 @@
// 3rd-party
+var path = require('path');
var _ = require('underscore');
var Jade; // initialized later
@@ -86,9 +87,10 @@ JadeEngine.setOptions = function (value) {
// Render data
JadeEngine.prototype.evaluate = function (context, locals, callback) {
try {
+ var jade_path = path.resolve(context.rootPath, context.pathname);
var result = Jade.compile(this.data, _.extend({}, options, {
client: true,
- filename: context.logicalPath
+ filename: jade_path
}));
callback(null, result.toString());
|
Modified Jade engine to support Jade include directives.
|
nodeca_mincer
|
train
|
006738e0c9a973bc70d944798f07b7205bc1dd13
|
diff --git a/core/src/main/java/io/neba/core/util/NodeUtil.java b/core/src/main/java/io/neba/core/util/NodeUtil.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/io/neba/core/util/NodeUtil.java
+++ b/core/src/main/java/io/neba/core/util/NodeUtil.java
@@ -31,8 +31,8 @@ public class NodeUtil {
private static final String JCR_MIXIN_TYPES = "jcr:mixinTypes";
/**
- * @param node must not ne <code>null</code>.
- * @return the primary type name of the given node, never <code>null</code>.
+ * @param node must not be <code>null</code>.
+ * @return the <code>primary type</code> name of the given node, never <code>null</code>.
* @throws RepositoryException if accessing the node fails due to an unrecoverable repository error.
*/
public static @Nonnull
@@ -43,7 +43,7 @@ public class NodeUtil {
}
/**
- * @param node must not ne <code>null</code>.
+ * @param node must not be <code>null</code>.
* @return a String with the comma separated mixin type names assigned to the given node, or <code>null</code> if the node has no mixin types.
* @throws RepositoryException if accessing the node fails due to an unrecoverable repository error.
*/
|
Review: Corrected javadoc
|
unic_neba
|
train
|
102d41a88fe3b45640efdfe64feafae7749f7117
|
diff --git a/objectstore/deltablock.go b/objectstore/deltablock.go
index <HASH>..<HASH> 100644
--- a/objectstore/deltablock.go
+++ b/objectstore/deltablock.go
@@ -124,10 +124,13 @@ func CreateDeltaBlockBackup(volume *Volume, snapshot *Snapshot, destURL string,
return "", err
}
defer deltaOps.CloseSnapshot(snapshot.UUID, volume.UUID)
- for _, d := range delta.Mappings {
+ mCounts := len(delta.Mappings)
+ for m, d := range delta.Mappings {
block := make([]byte, DEFAULT_BLOCK_SIZE)
- for i := int64(0); i < d.Size/delta.BlockSize; i++ {
+ blkCounts := d.Size / delta.BlockSize
+ for i := int64(0); i < blkCounts; i++ {
offset := d.Offset + i*delta.BlockSize
+ log.Debugf("Backup for %v: segment %v/%v, blocks %v/%v", snapshot.UUID, m+1, mCounts, i+1, blkCounts)
err := deltaOps.ReadSnapshot(snapshot.UUID, volume.UUID, offset, block)
if err != nil {
return "", err
|
backup: Add progress info in log for backup
|
rancher_convoy
|
train
|
e33a1e50bc81ab43627ee9238c4fc88e4ed8c794
|
diff --git a/lib/assistant/index.js b/lib/assistant/index.js
index <HASH>..<HASH> 100644
--- a/lib/assistant/index.js
+++ b/lib/assistant/index.js
@@ -3,6 +3,8 @@ const GoogleAssistant = require("./google-assistant");
const app = module.exports = Express();
const assistant = new GoogleAssistant();
+app.use('/assistant/setup', Express.static(__dirname + '/setup'));
+
app.get('/assistant', function (req, res) {
res.json(assistant.status());
});
|
Fixed: cannot get /assistant/setup
|
vervallsweg_cast-web-api
|
train
|
7f6796d5da0abf4f68d2246b600760cb46338a79
|
diff --git a/src/main/java/com/teklabs/gwt/i18n/server/MessagesExporter.java b/src/main/java/com/teklabs/gwt/i18n/server/MessagesExporter.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/teklabs/gwt/i18n/server/MessagesExporter.java
+++ b/src/main/java/com/teklabs/gwt/i18n/server/MessagesExporter.java
@@ -1,5 +1,6 @@
package com.teklabs.gwt.i18n.server;
+import org.apache.commons.lang.LocaleUtils;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
@@ -11,6 +12,9 @@ import java.util.Map;
public class MessagesExporter {
public static void main(String[] args) throws Exception {
Class cls = Class.forName(args[0]);
+ if (args.length > 1) {
+ LocaleProxy.setLocale(LocaleUtils.toLocale(args[1]));
+ }
MessagesProxy proxy = new MessagesProxy(cls, LoggerFactory.getLogger(MessagesExporter.class));
for (Method method : cls.getDeclaredMethods()) {
MessagesProxy.MessageDescriptor descriptor = proxy.getDescriptor(method);
@@ -20,11 +24,13 @@ public class MessagesExporter {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : descriptor.defaults.entrySet()) {
builder.setLength(0);
- builder.append(descriptor.key);
+ String key = descriptor.key;
if (!entry.getKey().isEmpty()) {
- builder.append('[').append(entry.getKey()).append(']');
+ key += '[' + entry.getKey() + ']';
}
- String value = entry.getValue()
+ builder.append(key);
+
+ String value = proxy.getProperties().getProperty(key, entry.getValue())
.replaceAll("\\\\", "\\\\\\\\")
.replaceAll("\\n", "\\\\n")
.replaceAll("\\r", "\\\\r")
|
Allow MessagesExporter to merge existing localization
|
lightoze_gwt-i18n-server
|
train
|
12b8a133d2f1a48610f458fa8f1a2c3aa2aa229f
|
diff --git a/aws/data_source_aws_redshift_service_account.go b/aws/data_source_aws_redshift_service_account.go
index <HASH>..<HASH> 100644
--- a/aws/data_source_aws_redshift_service_account.go
+++ b/aws/data_source_aws_redshift_service_account.go
@@ -13,6 +13,7 @@ var redshiftServiceAccountPerRegionMap = map[string]string{
"us-east-2": "391106570357",
"us-west-1": "262260360010",
"us-west-2": "902366379725",
+ "ap-east-1": "313564881002",
"ap-south-1": "865932855811",
"ap-northeast-2": "760740231472",
"ap-southeast-1": "361669875840",
|
redshift is in ap-east-1
|
terraform-providers_terraform-provider-aws
|
train
|
6774a73878a453ad51eb61cbe2f74fef5bce9491
|
diff --git a/storage/local/persistence.go b/storage/local/persistence.go
index <HASH>..<HASH> 100644
--- a/storage/local/persistence.go
+++ b/storage/local/persistence.go
@@ -540,15 +540,19 @@ func (p *persistence) checkpointSeriesMapAndHeads(fingerprintToSeries *seriesMap
begin := time.Now()
f, err := os.OpenFile(p.headsTempFileName(), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0640)
if err != nil {
- return
+ return err
}
defer func() {
- f.Sync()
+ syncErr := f.Sync()
closeErr := f.Close()
if err != nil {
return
}
+ err = syncErr
+ if err != nil {
+ return
+ }
err = closeErr
if err != nil {
return
@@ -562,18 +566,18 @@ func (p *persistence) checkpointSeriesMapAndHeads(fingerprintToSeries *seriesMap
w := bufio.NewWriterSize(f, fileBufSize)
if _, err = w.WriteString(headsMagicString); err != nil {
- return
+ return err
}
var numberOfSeriesOffset int
if numberOfSeriesOffset, err = codable.EncodeVarint(w, headsFormatVersion); err != nil {
- return
+ return err
}
numberOfSeriesOffset += len(headsMagicString)
numberOfSeriesInHeader := uint64(fingerprintToSeries.length())
// We have to write the number of series as uint64 because we might need
// to overwrite it later, and a varint might change byte width then.
if err = codable.EncodeUint64(w, numberOfSeriesInHeader); err != nil {
- return
+ return err
}
iter := fingerprintToSeries.iter()
@@ -606,7 +610,9 @@ func (p *persistence) checkpointSeriesMapAndHeads(fingerprintToSeries *seriesMap
if err != nil {
return
}
- w.Write(buf)
+ if _, err = w.Write(buf); err != nil {
+ return
+ }
if _, err = codable.EncodeVarint(w, int64(m.series.persistWatermark)); err != nil {
return
}
@@ -646,27 +652,33 @@ func (p *persistence) checkpointSeriesMapAndHeads(fingerprintToSeries *seriesMap
}
}
}
- // Series is checkpointed now, so declare it clean.
+ // Series is checkpointed now, so declare it clean. In case the entire
+ // checkpoint fails later on, this is fine, as the storage's series
+ // maintenance will mark these series newly dirty again, continuously
+ // increasing the total number of dirty series as seen by the storage.
+ // This has the effect of triggering a new checkpoint attempt even
+ // earlier than if we hadn't incorrectly set "dirty" to "false" here
+ // already.
m.series.dirty = false
}()
if err != nil {
- return
+ return err
}
}
if err = w.Flush(); err != nil {
- return
+ return err
}
if realNumberOfSeries != numberOfSeriesInHeader {
// The number of series has changed in the meantime.
// Rewrite it in the header.
if _, err = f.Seek(int64(numberOfSeriesOffset), os.SEEK_SET); err != nil {
- return
+ return err
}
if err = codable.EncodeUint64(f, realNumberOfSeries); err != nil {
- return
+ return err
}
}
- return
+ return err
}
// loadSeriesMapAndHeads loads the fingerprint to memory-series mapping and all
diff --git a/storage/local/storage.go b/storage/local/storage.go
index <HASH>..<HASH> 100644
--- a/storage/local/storage.go
+++ b/storage/local/storage.go
@@ -875,8 +875,12 @@ loop:
case <-s.loopStopping:
break loop
case <-checkpointTimer.C:
- s.persistence.checkpointSeriesMapAndHeads(s.fpToSeries, s.fpLocker)
- dirtySeriesCount = 0
+ err := s.persistence.checkpointSeriesMapAndHeads(s.fpToSeries, s.fpLocker)
+ if err != nil {
+ log.Errorln("Error while checkpointing:", err)
+ } else {
+ dirtySeriesCount = 0
+ }
checkpointTimer.Reset(s.checkpointInterval)
case fp := <-memoryFingerprints:
if s.maintainMemorySeries(fp, model.Now().Add(-s.dropAfter)) {
|
Fix error checking and logging around checkpointing.
|
prometheus_prometheus
|
train
|
bde0aa03e0dd2762d5ab8540fbd6d483729bbb56
|
diff --git a/azure-webapp-maven-plugin/src/main/java/com/microsoft/azure/maven/webapp/AbstractWebAppMojo.java b/azure-webapp-maven-plugin/src/main/java/com/microsoft/azure/maven/webapp/AbstractWebAppMojo.java
index <HASH>..<HASH> 100644
--- a/azure-webapp-maven-plugin/src/main/java/com/microsoft/azure/maven/webapp/AbstractWebAppMojo.java
+++ b/azure-webapp-maven-plugin/src/main/java/com/microsoft/azure/maven/webapp/AbstractWebAppMojo.java
@@ -189,8 +189,9 @@ public abstract class AbstractWebAppMojo extends AbstractAppServiceMojo {
* Schema version, which will be used to indicate the version of settings schema to use.
* @since 2.0.0
*/
- @Parameter(property = "schemaVersion", defaultValue = "v1")
- protected String schemaVersion;
+ // disable the entry for schemaVersion for the feature is not completely ready
+ // @Parameter(property = "schemaVersion", defaultValue = "v1")
+ protected String schemaVersion = "v1";
/**
* Runtime setting
|
Disable the schemaversion configuration until the implementation complete (#<I>)
|
Microsoft_azure-maven-plugins
|
train
|
de48a83a9536cbf229e87206c9a712db37c59e8b
|
diff --git a/src/python/dxpy/__init__.py b/src/python/dxpy/__init__.py
index <HASH>..<HASH> 100644
--- a/src/python/dxpy/__init__.py
+++ b/src/python/dxpy/__init__.py
@@ -156,7 +156,7 @@ def DXHTTPRequest(resource, data, method='POST', headers={}, auth=True, timeout=
if _DEBUG:
from repr import Repr
- print >>sys.stderr, method, url, Repr().repr(data)
+ print >>sys.stderr, method, url, "=>", Repr().repr(data)
if auth is True:
auth = AUTH_HELPER
@@ -187,6 +187,9 @@ def DXHTTPRequest(resource, data, method='POST', headers={}, auth=True, timeout=
response = requests.request(method, url, data=data, headers=headers, timeout=timeout,
auth=auth, config=config, **kwargs)
+ if _DEBUG:
+ print >>sys.stderr, method, url, "<=", response.status_code, Repr().repr(response.content)
+
# If HTTP code that is not 200 (OK) is received and the content is
# JSON, parse it and throw the appropriate error. Otherwise,
# raise the usual exception.
|
more debug info when _DX_DEBUG is set
|
dnanexus_dx-toolkit
|
train
|
c1556f2bb830a5e0996d045fd1b6d4016572a2f2
|
diff --git a/src/Modal/__tests__/ModalContents-test.js b/src/Modal/__tests__/ModalContents-test.js
index <HASH>..<HASH> 100644
--- a/src/Modal/__tests__/ModalContents-test.js
+++ b/src/Modal/__tests__/ModalContents-test.js
@@ -149,5 +149,20 @@ describe('ModalContents', function () {
expect(calculatedHeight.innerHeight)
.toEqual(calculatedHeight.height - heightInfo.outerHeight);
});
+
+ it('should return originalHeight if smaller than maxHeight', function () {
+ var heightInfo = {
+ innerHeight: 500,
+ originalHeight: 600,
+ outerHeight: 100,
+ maxHeight: 1000,
+ totalContentHeight: 800
+ };
+
+ var calculatedHeight = this.instance.calculateModalHeight(heightInfo);
+
+ expect(calculatedHeight.height).toEqual(heightInfo.originalHeight);
+ expect(calculatedHeight.innerHeight).toEqual(heightInfo.innerHeight);
+ });
});
});
|
Add a test for when original height is smaller than max height
|
mesosphere_reactjs-components
|
train
|
cf21e93b5db23e1a7171dafeb72ea9d629584826
|
diff --git a/server/Publish.rb b/server/Publish.rb
index <HASH>..<HASH> 100644
--- a/server/Publish.rb
+++ b/server/Publish.rb
@@ -148,7 +148,7 @@ class Dbus_Plugin < DBus::Object
dbus_method :register, " out id:i" do
@plugin_count += 1
- trace "Plugin count : #{@plugin_count}"
+ $global.trace "Plugin count : #{@plugin_count}"
return @plugin_count
end
diff --git a/server/config_with_VirtualPlacos_and_RoR.yaml b/server/config_with_VirtualPlacos_and_RoR.yaml
index <HASH>..<HASH> 100644
--- a/server/config_with_VirtualPlacos_and_RoR.yaml
+++ b/server/config_with_VirtualPlacos_and_RoR.yaml
@@ -40,7 +40,6 @@ objects:
card:
- name: VirtualPlacos
exec: ../drivers/VirtualPlacos/VirtualPlacos.rb
- method: debug
config: config.yaml
timeout: 2
plug:
diff --git a/server/globals.rb b/server/globals.rb
index <HASH>..<HASH> 100644
--- a/server/globals.rb
+++ b/server/globals.rb
@@ -22,7 +22,7 @@ class Global
# Print trace when debug env var defined
def trace(string_)
- if ENV['DEBUG_OPOS'] != nil
+ if ENV['VERBOSE_OPOS'] != nil
puts string_
end
end
|
change trace to VERBOSE_OPOS env variable
|
openplacos_openplacos
|
train
|
e33e573d9d9603ac9c50d3c8479a9a82657ee156
|
diff --git a/src/lib/svg-optimizer.js b/src/lib/svg-optimizer.js
index <HASH>..<HASH> 100644
--- a/src/lib/svg-optimizer.js
+++ b/src/lib/svg-optimizer.js
@@ -1,6 +1,9 @@
const SVGO = require('svgo');
const svgo = new SVGO({
- plugins: [{removeStyleElement: {}}]
+ plugins: [
+ {removeStyleElement: {}},
+ {removeTitle: true}
+ ]
});
const optimizeAsync = svgContent => {
|
fix(svgo): remove `<title>` elements
svgo version below <I> does not enable `removeTitle` plugin by default
`<title>`s make unexpected OS tooltip to show up
upgrading svgo to <I> requires more changes
|
wix_svg2react-icon
|
train
|
02750e78892d5682b88d077dd373ccb84882bebb
|
diff --git a/src/vis/drawing-controller.js b/src/vis/drawing-controller.js
index <HASH>..<HASH> 100644
--- a/src/vis/drawing-controller.js
+++ b/src/vis/drawing-controller.js
@@ -4,6 +4,8 @@ var DrawingController = function (mapView, map) {
};
DrawingController.prototype.enableDrawing = function (geometry) {
+ this.disableDrawing();
+
this._geometry = geometry;
this._map.addGeometry(this._geometry);
diff --git a/src/vis/edition-controller.js b/src/vis/edition-controller.js
index <HASH>..<HASH> 100644
--- a/src/vis/edition-controller.js
+++ b/src/vis/edition-controller.js
@@ -4,10 +4,13 @@ var EditionController = function (mapView, map) {
};
EditionController.prototype.enableEdition = function (geometry) {
+ this.disableEdition();
+
this._geometry = geometry;
this._map.addGeometry(this._geometry);
- this._map.disableInteractivity();
+ this._werePopupsEnabled = this._map.arePopupsEnabled();
+ this._map.disablePopups();
};
EditionController.prototype.disableEdition = function () {
@@ -16,7 +19,8 @@ EditionController.prototype.disableEdition = function () {
this._map.removeGeometry(this._geometry);
delete this._geometry;
- this._map.enableInteractivity();
+ // TODO: What if they were disabled?
+ this._map.enablePopups();
}
};
@@ -24,4 +28,12 @@ EditionController.prototype._isEditionEnabled = function () {
return !!this._geometry;
};
+EditionController.prototype._reEnableOrDisablePopups = function () {
+ if (this._werePopupsEnabled) {
+ this._map.enablePopups();
+ } else {
+ this._map.disablePopups();
+ }
+};
+
module.exports = EditionController;
diff --git a/src/vis/vis.js b/src/vis/vis.js
index <HASH>..<HASH> 100644
--- a/src/vis/vis.js
+++ b/src/vis/vis.js
@@ -352,6 +352,11 @@ var VisModel = Backbone.Model.extend({
})
.flatten()
.value();
+ },
+
+ addCustomOverlay: function (overlayView) {
+ this.overlaysCollection.add(overlayView);
+ return overlayView;
}
});
|
Disable drawing/edition mode when trying to re-enable those modes. Only disable popups while editing a feature
|
CartoDB_carto.js
|
train
|
f0ebdd6926c1ab5f7e78f24fd558339f2fcdca55
|
diff --git a/core-bundle/contao/classes/DataContainer.php b/core-bundle/contao/classes/DataContainer.php
index <HASH>..<HASH> 100644
--- a/core-bundle/contao/classes/DataContainer.php
+++ b/core-bundle/contao/classes/DataContainer.php
@@ -484,7 +484,24 @@ class DataContainer extends \Backend
</fieldset>';
}
- return '
+ $strPreview = '';
+
+ // Show a preview image (see #4948)
+ if ($this->strTable == 'tl_files' && $this->strField == 'name' && $this->objActiveRecord !== null && $this->objActiveRecord->type == 'file')
+ {
+ $objFile = new \File($this->objActiveRecord->path);
+
+ if ($objFile->isGdImage)
+ {
+ $strPreview = '
+
+<div class="tl_edit_preview">
+' . \Image::getHtml(\Image::get($objFile->path, 700, 150, 'box')) . '
+</div>';
+ }
+ }
+
+ return $strPreview . '
<div' . ($arrData['eval']['tl_class'] ? ' class="' . $arrData['eval']['tl_class'] . '"' : '') . '>' . $objWidget->parse() . $updateMode . (!$objWidget->hasErrors() ? $this->help($strHelpClass) : '') . '
</div>';
}
diff --git a/core-bundle/contao/drivers/DC_Folder.php b/core-bundle/contao/drivers/DC_Folder.php
index <HASH>..<HASH> 100644
--- a/core-bundle/contao/drivers/DC_Folder.php
+++ b/core-bundle/contao/drivers/DC_Folder.php
@@ -1195,23 +1195,6 @@ class DC_Folder extends \DataContainer implements \listable, \editable
$version = '';
}
- $strPreview = '';
-
- // Show a preview image (see #4948)
- if ($this->objActiveRecord !== null && $this->objActiveRecord->type == 'file')
- {
- $objFile = new \File($this->objActiveRecord->path);
-
- if ($objFile->isGdImage)
- {
- $strPreview = '
-
-<div class="tl_edit_preview">
-' . \Image::getHtml(\Image::get($objFile->path, 700, 150, 'box')) . '
-</div>';
- }
- }
-
// Submit buttons
$arrButtons = array();
$arrButtons['save'] = '<input type="submit" name="save" id="save" class="tl_submit" accesskey="s" value="'.specialchars($GLOBALS['TL_LANG']['MSC']['save']).'">';
@@ -1260,7 +1243,7 @@ class DC_Folder extends \DataContainer implements \listable, \editable
</div>
<h2 class="sub_headline">'.$GLOBALS['TL_LANG']['tl_files']['editFF'].'</h2>
-'.\Message::generate().$strPreview.'
+'.\Message::generate().'
<form action="'.ampersand(\Environment::get('request'), true).'" id="'.$this->strTable.'" class="tl_form" method="post"'.(!empty($this->onsubmit) ? ' onsubmit="'.implode(' ', $this->onsubmit).'"' : '').'>
<div class="tl_formbody_edit">
<input type="hidden" name="FORM_SUBMIT" value="'.specialchars($this->strTable).'">
|
[Core] Also show the preview image when editing multiple files (see #<I>)
|
contao_contao
|
train
|
a16cc7c0320a8626d44c3698c23b9a91f78d2dee
|
diff --git a/lib/zxcvbn.rb b/lib/zxcvbn.rb
index <HASH>..<HASH> 100644
--- a/lib/zxcvbn.rb
+++ b/lib/zxcvbn.rb
@@ -16,7 +16,6 @@ require 'zxcvbn/crack_time'
require 'zxcvbn/score'
require 'zxcvbn/scorer'
require 'zxcvbn/password_strength'
-require 'pathname'
module Zxcvbn
def self.included(base)
diff --git a/lib/zxcvbn/omnimatch.rb b/lib/zxcvbn/omnimatch.rb
index <HASH>..<HASH> 100644
--- a/lib/zxcvbn/omnimatch.rb
+++ b/lib/zxcvbn/omnimatch.rb
@@ -1,4 +1,6 @@
require 'json'
+require 'yaml'
+require 'pathname'
module Zxcvbn
class Omnimatch
|
Add yaml and pathname to omnimatch class
|
envato_zxcvbn-ruby
|
train
|
b079b401426f4c4a79361b6432f251d6ae552831
|
diff --git a/notedown/main.py b/notedown/main.py
index <HASH>..<HASH> 100644
--- a/notedown/main.py
+++ b/notedown/main.py
@@ -217,7 +217,8 @@ def main(args, help=''):
readers = {'notebook': nbformat,
'markdown': MarkdownReader(precode='\n'.join(args.precode),
magic=args.magic,
- match=args.match)
+ match=args.match,
+ caption_comments=args.render)
}
writers = {'notebook': nbformat,
diff --git a/notedown/notedown.py b/notedown/notedown.py
index <HASH>..<HASH> 100644
--- a/notedown/notedown.py
+++ b/notedown/notedown.py
@@ -92,7 +92,8 @@ class MarkdownReader(NotebookReader):
|\n[ \t]*) # or another blank line
"""
- def __init__(self, code_regex=None, precode='', magic=True, match='all'):
+ def __init__(self, code_regex=None, precode='', magic=True,
+ match='all', caption_comments=False):
"""
code_regex - Either 'fenced' or 'indented' or
a regular expression that matches code blocks in
@@ -112,6 +113,9 @@ class MarkdownReader(NotebookReader):
match - one of 'all', 'fenced' or 'strict' or a specific
language name
+
+ caption_comments - whether to derive a caption and id from the
+ cell contents
"""
if not code_regex:
self.code_regex = r"({}|{})".format(self.fenced_regex,
@@ -132,6 +136,8 @@ class MarkdownReader(NotebookReader):
self.match = match
+ self.caption_comments = caption_comments
+
def new_code_block(self, **kwargs):
"""Create a new code block."""
proto = {'content': '',
@@ -210,6 +216,13 @@ class MarkdownReader(NotebookReader):
else:
block['IO'] = 'input'
+ if self.caption_comments:
+ id, caption = get_caption_comments(block['content'])
+ if id:
+ attr.id = id
+ if caption:
+ attr['caption'] = caption
+
block['language'] = language
block['attributes'] = attr
@@ -618,3 +631,37 @@ class Knitr(object):
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
+
+
+def get_caption_comments(content):
+ """Retrieve an id and a caption from a code cell.
+
+ If the code cell content begins with a commented
+ block that looks like
+
+ ## fig:id
+ # multi-line or single-line
+ # caption
+
+ then the 'fig:id' and the caption will be returned.
+ The '#' are stripped.
+ """
+
+ if not content.startswith('## fig:'):
+ return None, None
+
+ content = content.splitlines()
+
+ id = content[0].strip('## ')
+
+ caption = []
+ for line in content[1:]:
+ if not line.startswith('# '):
+ break
+ else:
+ caption.append(line.lstrip('# ').rstrip())
+
+ # add " around the caption. TODO: consider doing this upstream
+ # in pandoc-attributes
+ caption = '"' + ' '.join(caption) + '"'
+ return id, caption
|
new feature: set caption / id in code comments
|
aaren_notedown
|
train
|
e1477b41f6500d59d59fc00a0d7cfabb00bfc3f6
|
diff --git a/test/stubs/jekyll.rb b/test/stubs/jekyll.rb
index <HASH>..<HASH> 100644
--- a/test/stubs/jekyll.rb
+++ b/test/stubs/jekyll.rb
@@ -9,13 +9,14 @@ module JekyllStub
@pdata = picture_data_stub
@jekyll_env = 'development'
+ @site_dest = '/tmp/jpt'
@jconfig = { 'picture' => @pconfig,
'keep_files' => [],
+ 'destination' => @site_dest,
'url' => 'example.com' }
@data = { 'picture' => @pdata }
@page = { 'ext' => 'html' }
@site_source = TestHelper::TEST_DIR
- @site_dest = '/tmp/jpt'
end
def build_context_stub
|
Update test stubs for correct configuration location
|
robwierzbowski_jekyll-picture-tag
|
train
|
eecdf6899d36e57b72c4096ecae98b20e91aa97c
|
diff --git a/graceful/graceful.go b/graceful/graceful.go
index <HASH>..<HASH> 100644
--- a/graceful/graceful.go
+++ b/graceful/graceful.go
@@ -37,9 +37,11 @@ Since I couldn't come up with a better idea, I just copy-and-pasted both
ListenAndServe and ListenAndServeTLS here more-or-less verbatim. "Oh well!"
*/
-type server http.Server
+// Type Server is exactly the same as an http.Server, but provides more graceful
+// implementations of its methods.
+type Server http.Server
-func (srv *server) Serve(l net.Listener) (err error) {
+func (srv *Server) Serve(l net.Listener) (err error) {
go func() {
<-kill
l.Close()
@@ -71,7 +73,7 @@ func (srv *server) Serve(l net.Listener) (err error) {
// About 200 years, also known as "forever"
const forever time.Duration = 200 * 365 * 24 * time.Hour
-func (srv *server) ListenAndServe() error {
+func (srv *Server) ListenAndServe() error {
addr := srv.Addr
if addr == "" {
addr = ":http"
@@ -83,7 +85,7 @@ func (srv *server) ListenAndServe() error {
return srv.Serve(l)
}
-func (srv *server) ListenAndServeTLS(certFile, keyFile string) error {
+func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
addr := srv.Addr
if addr == "" {
addr = ":https"
@@ -114,18 +116,18 @@ func (srv *server) ListenAndServeTLS(certFile, keyFile string) error {
// ListenAndServe behaves exactly like the net/http function of the same name.
func ListenAndServe(addr string, handler http.Handler) error {
- server := &server{Addr: addr, Handler: handler}
+ server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServe()
}
// ListenAndServeTLS behaves exactly like the net/http function of the same name.
func ListenAndServeTLS(addr, certfile, keyfile string, handler http.Handler) error {
- server := &server{Addr: addr, Handler: handler}
+ server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServeTLS(certfile, keyfile)
}
// Serve behaves exactly like the net/http function of the same name.
func Serve(l net.Listener, handler http.Handler) error {
- server := &server{Handler: handler}
+ server := &Server{Handler: handler}
return server.Serve(l)
}
|
Make graceful.Server public again
graceful.Server was made private in <I>c2ca7e, but I think the increased
flexibility you get with being able to provide your own TLS options
(etc.) outweighs the API complexity of an additional type.
|
zenazn_goji
|
train
|
ff52ba1699cefccb99dc729ad65b89b8f46aef45
|
diff --git a/src/matrix/dataset_util.js b/src/matrix/dataset_util.js
index <HASH>..<HASH> 100644
--- a/src/matrix/dataset_util.js
+++ b/src/matrix/dataset_util.js
@@ -635,16 +635,18 @@ morpheus.DatasetUtil.autocompleteValues = function(dataset) {
});
});
- fields.forEach(function(field) {
- if (regex.test(field)) {
- matches.push({
- value : field + ':',
- label : '<span style="font-weight:300;">' + field
- + ':</span>',
- show : true
- });
- }
- });
+ if (field == null) {
+ fields.forEach(function(field) {
+ if (regex.test(field)) {
+ matches.push({
+ value : field + ':',
+ label : '<span style="font-weight:300;">' + field
+ + ':</span>',
+ show : true
+ });
+ }
+ });
+ }
cb(matches);
};
|
check for null field in autocomplete
|
cmap_morpheus.js
|
train
|
536d340dafeffd2f5d354d9eec3a1507a4e86146
|
diff --git a/EulerPy/tests.py b/EulerPy/tests.py
index <HASH>..<HASH> 100644
--- a/EulerPy/tests.py
+++ b/EulerPy/tests.py
@@ -1,8 +1,10 @@
# -*- coding: utf-8 -*-
import os
-import unittest
+import shutil
+import tempfile
import textwrap
+import unittest
from click.testing import CliRunner
@@ -10,14 +12,84 @@ from EulerPy import euler
from EulerPy.problem import Problem
class Tests(unittest.TestCase):
- def test_program_flow(self):
+ def setUp(self):
+ os.chdir(tempfile.mkdtemp())
+
+ # Copy problem and solution files to temporary directory
+ eulerDir = os.path.dirname(os.path.realpath(__file__))
+ tempEuler = os.path.join(os.getcwd(), 'EulerPy')
+ shutil.copytree(eulerDir, tempEuler)
+
+
+ def tearDown(self):
+ shutil.rmtree(os.getcwd())
+
+
+ def test_fresh_install(self):
"""Check that EulerPy executes properly from fresh install"""
- runner = CliRunner()
- with runner.isolated_filesystem():
- # Test "N" as file generation prompt input
- result = runner.invoke(euler.main, input='N\n')
- self.assertEqual(result.exit_code, 1)
- self.assertFalse(os.path.isfile('001.py'))
+ # Test "N" as file generation prompt input
+ result = CliRunner().invoke(euler.main, input='N\n')
+ self.assertEqual(result.exit_code, 1)
+ self.assertFalse(os.path.isfile('001.py'))
+
+ # Test "Y" as file generation prompt input
+ result = CliRunner().invoke(euler.main, input='Y\n')
+ self.assertEqual(result.exit_code, None)
+ self.assertTrue(os.path.isfile('001.py'))
+ os.remove('001.py')
+
+ # Test "\n" as file generation prompt input
+ result = CliRunner().invoke(euler.main, input='\n')
+ self.assertEqual(result.exit_code, None)
+ self.assertTrue(os.path.isfile('001.py'))
+
+
+ def test_cheat_option(self):
+ result = CliRunner().invoke(euler.main, ['-c'], input='\n')
+ self.assertEqual(result.exit_code, 1)
+
+ result = CliRunner().invoke(euler.main, ['-c'], input='Y\n')
+ self.assertEqual(result.exit_code, None)
+
+ result = CliRunner().invoke(euler.main, ['--cheat'], input='Y\n')
+ self.assertEqual(result.exit_code, None)
+
+ result = CliRunner().invoke(euler.main, ['-c', '2'], input='Y\n')
+ self.assertTrue('problem 2' in result.output)
+
+
+ def test_generate_option(self):
+ result = CliRunner().invoke(euler.main, ['-g'], input='\n')
+ self.assertEqual(result.exit_code, None)
+ self.assertTrue(os.path.isfile('001.py'))
+ os.remove('001.py')
+
+ result = CliRunner().invoke(euler.main, ['--generate'], input='\n')
+ self.assertEqual(result.exit_code, None)
+ self.assertTrue(os.path.isfile('001.py'))
+ os.remove('001.py')
+
+ result = CliRunner().invoke(euler.main, ['-g', '2'], input='\n')
+ self.assertEqual(result.exit_code, None)
+ self.assertTrue(os.path.isfile('002.py'))
+ os.remove('002.py')
+
+
+ def test_generate_overwrite(self):
+ """Ensure that --generate will overwrite a file appropriately"""
+ # Default behaviour should be to not overwrite the file
+ open('001.py', 'a').close()
+ result = CliRunner().invoke(euler.main, ['-g', '1'], input='\n\n')
+ self.assertEqual(result.exit_code, 1)
+ with open('001.py') as file:
+ self.assertTrue(file.readlines() == [])
+
+ # This should overwrite the file ("001.py" will not be empty anymore)
+ open('001.py', 'a').close()
+ result = CliRunner().invoke(euler.main, ['-g', '1'], input='\nY\n')
+ self.assertEqual(result.exit_code, None)
+ with open('001.py') as file:
+ self.assertFalse(file.readlines() == [])
def test_problem_format(self):
|
Added rudimentary tests using CLIRunner()
Tests now automatically copy the EulerPy directory so that after
changing directories to a temporary one, the test file still has access
to problems.txt and solutions.txt.
|
iKevinY_EulerPy
|
train
|
59ce923559f50641d0380a97ba90974f6154e985
|
diff --git a/plexapi/base.py b/plexapi/base.py
index <HASH>..<HASH> 100644
--- a/plexapi/base.py
+++ b/plexapi/base.py
@@ -421,9 +421,13 @@ class PlexPartialObject(PlexObject):
'havnt allowed items to be deleted' % self.key)
raise
- def history(self):
- """ Get Play History for a media item. """
- return self._server.history(ratingKey=self.ratingKey)
+ def history(self, maxresults=9999999, mindate=None):
+ """ Get Play History for a media item.
+ Parameters:
+ maxresults (int): Only return the specified number of results (optional).
+ mindate (datetime): Min datetime to return results from.
+ """
+ return self._server.history(maxresults=maxresults, mindate=mindate, ratingKey=self.ratingKey)
# The photo tag cant be built atm. TODO
diff --git a/plexapi/library.py b/plexapi/library.py
index <HASH>..<HASH> 100644
--- a/plexapi/library.py
+++ b/plexapi/library.py
@@ -294,11 +294,15 @@ class Library(PlexObject):
part += urlencode(kwargs)
return self._server.query(part, method=self._server._session.post)
- def history(self):
- """ Get Play History for all library Sections for the owner. """
+ def history(self, maxresults=9999999, mindate=None):
+ """ Get Play History for all library Sections for the owner.
+ Parameters:
+ maxresults (int): Only return the specified number of results (optional).
+ mindate (datetime): Min datetime to return results from.
+ """
hist = []
for section in self.sections():
- hist.extend(section.history())
+ hist.extend(section.history(maxresults=maxresults, mindate=mindate))
return hist
@@ -640,9 +644,13 @@ class LibrarySection(PlexObject):
return myplex.sync(client=client, clientId=clientId, sync_item=sync_item)
- def history(self):
- """ Get Play History for this library Section for the owner. """
- return self._server.history(librarySectionID=self.key, accountID=1)
+ def history(self, maxresults=9999999, mindate=None):
+ """ Get Play History for this library Section for the owner.
+ Parameters:
+ maxresults (int): Only return the specified number of results (optional).
+ mindate (datetime): Min datetime to return results from.
+ """
+ return self._server.history(maxresults=maxresults, mindate=mindate, librarySectionID=self.key, accountID=1)
class MovieSection(LibrarySection):
diff --git a/plexapi/myplex.py b/plexapi/myplex.py
index <HASH>..<HASH> 100644
--- a/plexapi/myplex.py
+++ b/plexapi/myplex.py
@@ -600,13 +600,17 @@ class MyPlexAccount(PlexObject):
raise BadRequest('(%s) %s %s; %s' % (response.status_code, codename, response.url, errtext))
return response.json()['token']
- def history(self):
- """ Get Play History for all library sections on all servers for the owner. """
+ def history(self, maxresults=9999999, mindate=None):
+ """ Get Play History for all library sections on all servers for the owner.
+ Parameters:
+ maxresults (int): Only return the specified number of results (optional).
+ mindate (datetime): Min datetime to return results from.
+ """
servers = [x for x in self.resources() if x.provides == 'server' and x.owned]
hist = []
for server in servers:
conn = server.connect()
- hist.extend(conn.history(accountID=1))
+ hist.extend(conn.history(maxresults=maxresults, mindate=mindate, accountID=1))
return hist
@@ -686,11 +690,15 @@ class MyPlexUser(PlexObject):
raise NotFound('Unable to find server %s' % name)
- def history(self):
- """ Get all Play History for a user in all shared servers. """
+ def history(self, maxresults=9999999, mindate=None):
+ """ Get all Play History for a user in all shared servers.
+ Parameters:
+ maxresults (int): Only return the specified number of results (optional).
+ mindate (datetime): Min datetime to return results from.
+ """
hist = []
for server in self.servers:
- hist.extend(server.history())
+ hist.extend(server.history(maxresults=maxresults, mindate=mindate))
return hist
@@ -719,10 +727,15 @@ class Section(PlexObject):
self.type = data.attrib.get('type')
self.shared = utils.cast(bool, data.attrib.get('shared'))
- def history(self):
- """ Get all Play History for a user for this section in this shared server. """
+ def history(self, maxresults=9999999, mindate=None):
+ """ Get all Play History for a user for this section in this shared server.
+ Parameters:
+ maxresults (int): Only return the specified number of results (optional).
+ mindate (datetime): Min datetime to return results from.
+ """
server = self._server._server.resource(self._server.name).connect()
- return server.history(accountID=self._server.accountID, librarySectionID=self.sectionKey)
+ return server.history(maxresults=maxresults, mindate=mindate,
+ accountID=self._server.accountID, librarySectionID=self.sectionKey)
class MyPlexServerShare(PlexObject):
@@ -781,10 +794,14 @@ class MyPlexServerShare(PlexObject):
return sections
- def history(self):
- """ Get all Play History for a user in this shared server. """
+ def history(self, maxresults=9999999, mindate=None):
+ """ Get all Play History for a user in this shared server.
+ Parameters:
+ maxresults (int): Only return the specified number of results (optional).
+ mindate (datetime): Min datetime to return results from.
+ """
server = self._server.resource(self.name).connect()
- return server.history(accountID=self.accountID)
+ return server.history(maxresults=maxresults, mindate=mindate, accountID=self.accountID)
class MyPlexResource(PlexObject):
|
Add maxResults and mindate to all history methods
|
pkkid_python-plexapi
|
train
|
1a685a2c5171b75bf530381da57fe0b4cd5c2450
|
diff --git a/build.gradle b/build.gradle
index <HASH>..<HASH> 100644
--- a/build.gradle
+++ b/build.gradle
@@ -17,15 +17,15 @@ configure(allprojects) {
sourceCompatibility=1.5
targetCompatibility=1.5
- h2Version = '1.3.163'
+ h2Version = '1.3.166'
hamcrestVersion = '1.2.1'
- httpComponentsVersion = '4.1.2'
- jacksonVersion = '1.9.3'
+ httpComponentsVersion = '4.1.3'
+ jacksonVersion = '1.9.6'
javaxInjectVersion = '1'
junitVersion = '4.10'
mockitoVersion = '1.9.0'
servletApiVersion = '2.5'
- springVersion = '3.1.0.RELEASE'
+ springVersion = '3.1.1.RELEASE'
springSecurityCryptoVersion = '3.1.0.RELEASE'
springTestMvcVersion = "1.0.0.BUILD-SNAPSHOT"
jspApiVersion = '2.2.1'
diff --git a/spring-social-core/src/main/java/org/springframework/social/support/BufferingClientHttpResponse.java b/spring-social-core/src/main/java/org/springframework/social/support/BufferingClientHttpResponse.java
index <HASH>..<HASH> 100644
--- a/spring-social-core/src/main/java/org/springframework/social/support/BufferingClientHttpResponse.java
+++ b/spring-social-core/src/main/java/org/springframework/social/support/BufferingClientHttpResponse.java
@@ -49,6 +49,10 @@ class BufferingClientHttpResponse implements ClientHttpResponse {
return response.getStatusText();
}
+ public int getRawStatusCode() throws IOException {
+ return response.getRawStatusCode();
+ }
+
public HttpHeaders getHeaders() {
return response.getHeaders();
}
diff --git a/spring-social-core/src/main/java/org/springframework/social/support/HttpComponentsClientHttpResponse.java b/spring-social-core/src/main/java/org/springframework/social/support/HttpComponentsClientHttpResponse.java
index <HASH>..<HASH> 100644
--- a/spring-social-core/src/main/java/org/springframework/social/support/HttpComponentsClientHttpResponse.java
+++ b/spring-social-core/src/main/java/org/springframework/social/support/HttpComponentsClientHttpResponse.java
@@ -59,6 +59,10 @@ final class HttpComponentsClientHttpResponse implements ClientHttpResponse {
return httpResponse.getStatusLine().getReasonPhrase();
}
+ public int getRawStatusCode() throws IOException {
+ return httpResponse.getStatusLine().getStatusCode();
+ }
+
public HttpHeaders getHeaders() {
if (headers == null) {
headers = new HttpHeaders();
|
Updated dependencies; Spring <I>'s ClientHttpResponse has a new getRawStatusCode() method that must be implemented.
|
spring-projects_spring-social
|
train
|
a00cd8cdf3eb673a74316c0341b57fcf7eb04031
|
diff --git a/addok/core.py b/addok/core.py
index <HASH>..<HASH> 100644
--- a/addok/core.py
+++ b/addok/core.py
@@ -398,6 +398,11 @@ class Search(BaseHelper):
self.new_bucket(self.keys)
def step_autocomplete(self):
+ if self.bucket_overflow:
+ return
+ if not self._autocomplete:
+ self.debug('Autocomplete not active. Abort.')
+ return
self.autocomplete(self.meaningful)
def step_fuzzy(self):
@@ -459,9 +464,6 @@ class Search(BaseHelper):
token.search()
def autocomplete(self, tokens, skip_commons=False):
- if not self._autocomplete:
- self.debug('Autocomplete not active. Abort.')
- return
self.debug('Autocompleting %s', self.last_token)
# self.last_token.autocomplete()
keys = [t.db_key for t in tokens if not t.is_last]
|
Do not compute autocomplete candidate if bucket already overflown
|
addok_addok
|
train
|
eac3d066c6b594395329e33d65b2ea76e7b7e6fe
|
diff --git a/generators/server/templates/src/test/java/package/security/_OAuth2TokenMockUtil.java b/generators/server/templates/src/test/java/package/security/_OAuth2TokenMockUtil.java
index <HASH>..<HASH> 100644
--- a/generators/server/templates/src/test/java/package/security/_OAuth2TokenMockUtil.java
+++ b/generators/server/templates/src/test/java/package/security/_OAuth2TokenMockUtil.java
@@ -23,9 +23,7 @@ import java.util.stream.Collectors;
import static org.mockito.BDDMockito.given;
/**
- * A bean providing simple mocking of OAuth2 access tokens for security integration tests
- *
- * @author David Steiman
+ * A bean providing simple mocking of OAuth2 access tokens for security integration tests.
*/
@Component
public class OAuth2TokenMockUtil {
@@ -83,4 +81,3 @@ public class OAuth2TokenMockUtil {
}
}
}
-
|
removed author information in the template, as this shouldn't go into the end-users application
|
jhipster_generator-jhipster
|
train
|
b48b0cb2994e3267360fa5f7f259a51b5594b3e9
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,7 @@
## 0.5.1 (unreleased)
+ - Fixed NFS erroring when NFS wasn't even enabled if `/etc/exports` doesn't
+ exist. [GH-126]
- Fixed `vagrant resume` to properly resume a suspended VM. [GH-122]
- Fixed `halt`, `destroy`, `reload` to where they failed if the VM was
in a saved state. [GH-123]
diff --git a/lib/vagrant/hosts/bsd.rb b/lib/vagrant/hosts/bsd.rb
index <HASH>..<HASH> 100644
--- a/lib/vagrant/hosts/bsd.rb
+++ b/lib/vagrant/hosts/bsd.rb
@@ -40,6 +40,7 @@ module Vagrant
end
def nfs_cleanup
+ return if !File.exist?("/etc/exports")
system("cat /etc/exports | grep 'VAGRANT-BEGIN: #{env.vm.uuid}' > /dev/null 2>&1")
if $?.to_i == 0
diff --git a/lib/vagrant/hosts/linux.rb b/lib/vagrant/hosts/linux.rb
index <HASH>..<HASH> 100644
--- a/lib/vagrant/hosts/linux.rb
+++ b/lib/vagrant/hosts/linux.rb
@@ -39,6 +39,7 @@ module Vagrant
end
def nfs_cleanup
+ return if !File.exist?("/etc/exports")
system("cat /etc/exports | grep 'VAGRANT-BEGIN: #{env.vm.uuid}' > /dev/null 2>&1")
if $?.to_i == 0
|
NFS cleanup no longer errors if /etc/exports doesn't exist. [closes GH-<I>]
|
hashicorp_vagrant
|
train
|
624bcb1606882d6c1267c23d1699f915f3bc4cee
|
diff --git a/mod/scorm/lang/en/scorm.php b/mod/scorm/lang/en/scorm.php
index <HASH>..<HASH> 100644
--- a/mod/scorm/lang/en/scorm.php
+++ b/mod/scorm/lang/en/scorm.php
@@ -179,7 +179,7 @@ $string['onchanges'] = 'Whenever it changes';
$string['optallstudents'] = 'all users';
$string['optattemptsonly'] = 'users with attempts only';
$string['optnoattemptsonly'] = 'users with no attempts only';
-$string['options'] = 'Options';
+$string['options'] = 'Options (Prevented by some browsers)';
$string['organization'] = 'Organization';
$string['organizations'] = 'Organizations';
$string['othersettings'] = 'Additional settings';
|
SCORM MDL-<I> improved english string to state that some browsers may prevent these settings.
|
moodle_moodle
|
train
|
c9efdd096aec3ea280494ec57302223e253dcbea
|
diff --git a/spec/models/no_cms/blocks/duplicating_slots_spec.rb b/spec/models/no_cms/blocks/duplicating_slots_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/no_cms/blocks/duplicating_slots_spec.rb
+++ b/spec/models/no_cms/blocks/duplicating_slots_spec.rb
@@ -46,6 +46,10 @@ describe NoCms::Blocks::BlockSlot do
subject { dupped_slot.children.first }
+ it "should save" do
+ expect(subject.save).to be_truthy
+ end
+
it "should have different slot" do
expect(subject).to_not eq nested_slot
end
@@ -82,6 +86,10 @@ describe NoCms::Blocks::BlockSlot do
subject { dupped_slot.children.first }
+ it "should save" do
+ expect(subject.save).to be_truthy
+ end
+
it "should have different slot" do
expect(subject).to_not eq nested_slot
end
|
Add spec for save dipped slot
|
simplelogica_nocms-blocks
|
train
|
d3e9530dc370756d093bf64f2b5fe3b74dc399d5
|
diff --git a/openquake/server/views.py b/openquake/server/views.py
index <HASH>..<HASH> 100644
--- a/openquake/server/views.py
+++ b/openquake/server/views.py
@@ -18,6 +18,7 @@
import shutil
import json
+import string
import logging
import os
import tempfile
|
Added forgotten import [ci skip]
|
gem_oq-engine
|
train
|
73007b1fe22af1733395a88c74e65fb26fa1d69f
|
diff --git a/src/Validations/index.js b/src/Validations/index.js
index <HASH>..<HASH> 100644
--- a/src/Validations/index.js
+++ b/src/Validations/index.js
@@ -982,7 +982,7 @@ Validations.equals = function (data, field, message, args, get) {
return
}
- if (targetedValue === fieldValue) {
+ if (targetedValue == fieldValue) {
resolve('validation passed')
return
}
diff --git a/test/validations.spec.js b/test/validations.spec.js
index <HASH>..<HASH> 100644
--- a/test/validations.spec.js
+++ b/test/validations.spec.js
@@ -1160,6 +1160,19 @@ describe('Validations', function() {
const passes = yield Validations.equals(data, field, message, args, get)
expect(passes).to.equal('validation passed')
})
+
+ ///////////////////
+ // test suite 82 //
+ ///////////////////
+ it('should work fine when then under validation is a number', function * () {
+ const data = {age:18}
+ const field = 'age'
+ const message = 'age should be 18'
+ const get = _.get
+ const args = ['18']
+ const passes = yield Validations.equals(data, field, message, args, get)
+ expect(passes).to.equal('validation passed')
+ })
})
context('notEquals', function () {
|
fix(rules:equals): perform loose comparison
since rules can be string and their values can be a number a loose == comparison is required
Closes #<I>
|
poppinss_indicative
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.