hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
10bfd3fbfee69be3ac81b27f3d1f7c59ef3ebbe5
|
diff --git a/modules/text/text.js b/modules/text/text.js
index <HASH>..<HASH> 100644
--- a/modules/text/text.js
+++ b/modules/text/text.js
@@ -17,9 +17,11 @@ export default class Text extends Component {
*/
constructor (position, text, options) {
super(position, options);
+
/**
- * @type {String}
+ * @type {Array<String>}
*/
+ this.lines = [];
this.text = text;
/**
* @type {Object}
@@ -29,13 +31,35 @@ export default class Text extends Component {
}
/**
+ * Returns the text
+ * @return {String}
+ */
+ get text () {
+ return this.lines.join("\n");
+ }
+
+ /**
+ * Change the text
+ * @param {String|Array<String>} lines - New text value
+ * @example this.text = "Single line text";
+ * @example this.text = "Multi\nLine text";
+ * @example this.text = ["Multi", "Line text"];
+ * @example this.text = ["Multi", "Line\ntext"];
+ */
+ set text (lines) {
+ const separator = "\n";
+ this.lines = Array.isArray(lines) ?
+ lines.reduce((acc, line) => acc.concat(line.split(separator)), []) :
+ lines.split(separator);
+ }
+
+ /**
* Draw the text into a drawing context
* @param {CanvasRenderingContext2D} ctx - Drawing context
* @return {Text} Itself
*/
trace (ctx) {
- const text = this.text.toString();
- if (text.length) {
+ if (this.lines.length) {
const opts = this.options;
ctx.font = `${opts.bold ? "bold " : ""}${opts.italic ? "italic " : ""}${opts.fontSize}px ${opts.font}`;
ctx.textAlign = opts.align;
@@ -43,14 +67,23 @@ export default class Text extends Component {
if (opts.fill) {
ctx.fillStyle = opts.fill;
- ctx.fillText(text, 0, 0);
}
-
if (opts.stroke) {
ctx.strokeStyle = opts.stroke;
ctx.lineWidth = opts.strokeWidth;
- ctx.strokeText(text, 0, 0);
}
+
+ const lineHeight = this.height / this.lines.length; // TODO: could be user defined
+
+ this.lines.forEach((line, index) => {
+ const y = index * lineHeight;
+ if (opts.fill) {
+ ctx.fillText(line, 0, y);
+ }
+ if (opts.stroke) {
+ ctx.strokeText(line, 0, y);
+ }
+ });
}
return this;
}
@@ -106,11 +139,11 @@ export default class Text extends Component {
const scene = this.hasScene();
if (scene) {
scene.ctx.font = `${this.options.fontSize}px ${this.options.font}`;
- const { width } = scene.ctx.measureText(this.text);
+ const maxLineWidth = Math.max(...this.lines.map(line => scene.ctx.measureText(line).width));
// Hack to get the em box's height
- const height = scene.ctx.measureText("M").width;
+ const height = scene.ctx.measureText("M").width * this.lines.length * 1.5;
const measured = {
- width,
+ width: maxLineWidth,
height,
};
this._cachedMeasures = {
diff --git a/modules/text/text.test.js b/modules/text/text.test.js
index <HASH>..<HASH> 100644
--- a/modules/text/text.test.js
+++ b/modules/text/text.test.js
@@ -4,7 +4,7 @@ import Position from "@pencil.js/position";
import Component from "@pencil.js/component";
import Text from "./text";
-const str = "Hello world";
+const str = ["Hello\nworld"];
let text;
beforeAll(() => {
text = new Text(new Position(55, 22.5), str);
@@ -20,17 +20,16 @@ test("Text render", () => {
};
text.trace(ctx);
- expect(ctx.fillText.mock.calls.length).toBe(1);
+ expect(ctx.fillText.mock.calls.length).toBe(2);
expect(ctx.font).toBe(`${Text.defaultOptions.fontSize}px ${Text.defaultOptions.font}`);
expect(ctx.textAlign).toBe(Text.defaultOptions.align);
expect(ctx.textBaseline).toBe("top");
expect(ctx.fillStyle).toBe(Component.defaultOptions.fill);
- expect(ctx.fillText.mock.calls[0]).toEqual([str, 0, 0]);
});
test("Text isHover", () => {
// Text is without root therefore can't be hovered
- expect(text.isHover(new Position(0, 0))).toBe(false);
+ expect(text.isHover(text.position)).toBe(false);
// TODO: test with root
});
@@ -44,6 +43,7 @@ test("Text measures", () => {
expect(text.height).toBe(0);
// TODO: test with root
+ // Text measures returns cache
// eslint-disable-next-line no-underscore-dangle, mess with cache on purpose
text._cachedMeasures[text.hash] = {
width: 42,
|
Allow for multi-line text
fix #9
|
pencil-js_pencil.js
|
train
|
1fb7286776f57bcc2d8f56ad26a9ae9c1f2330e1
|
diff --git a/src/org/opencms/validation/CmsHtmlLinkValidator.java b/src/org/opencms/validation/CmsHtmlLinkValidator.java
index <HASH>..<HASH> 100644
--- a/src/org/opencms/validation/CmsHtmlLinkValidator.java
+++ b/src/org/opencms/validation/CmsHtmlLinkValidator.java
@@ -1,7 +1,7 @@
/*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/validation/Attic/CmsHtmlLinkValidator.java,v $
- * Date : $Date: 2004/01/23 14:30:04 $
- * Version: $Revision: 1.6 $
+ * Date : $Date: 2004/01/23 14:59:01 $
+ * Version: $Revision: 1.7 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
@@ -59,7 +59,7 @@ import java.util.Map;
* Objects using the CmsHtmlLinkValidator are responsible to handle detected broken links.<p>
*
* @author Thomas Weckert (t.weckert@alkacon.com)
- * @version $Revision: 1.6 $ $Date: 2004/01/23 14:30:04 $
+ * @version $Revision: 1.7 $ $Date: 2004/01/23 14:59:01 $
* @since 5.3.0
*/
public class CmsHtmlLinkValidator extends Object {
@@ -144,7 +144,7 @@ public class CmsHtmlLinkValidator extends Object {
for (i = 0; i < offlineResources.size(); i++) {
resource = (CmsResource) offlineResources.get(i);
offlineFilesLookup.put(resource.getRootPath(), resource);
-
+
try {
if ((resourceType = cms.getResourceType(resource.getType())) instanceof I_CmsHtmlLinkValidatable) {
validatableResources.add(resource);
@@ -158,41 +158,48 @@ public class CmsHtmlLinkValidator extends Object {
foundBrokenLinks = false;
for (i = 0, j = validatableResources.size(); i < j; i++) {
- brokenLinks = null;
- resource = (CmsResource) validatableResources.get(i);
- resourceName = resource.getRootPath();
+ try {
+ brokenLinks = null;
+ resource = (CmsResource) validatableResources.get(i);
+ resourceName = resource.getRootPath();
+ resourceType = cms.getResourceType(resource.getType());
- report.print("( " + (i + 1) + " / " + j + " ) ");
- report.print(report.key("report.htmllink_validator.validating"), I_CmsReport.C_FORMAT_NOTE);
- report.print(resourceName);
- report.print(report.key("report.dots"));
+ report.print("( " + (i + 1) + " / " + j + " ) ");
+ report.print(report.key("report.htmllink_validator.validating"), I_CmsReport.C_FORMAT_NOTE);
+ report.print(resourceName);
+ report.print(report.key("report.dots"));
- links = ((I_CmsHtmlLinkValidatable) resourceType).findLinks(cms, resource);
+ links = ((I_CmsHtmlLinkValidatable) resourceType).findLinks(cms, resource);
- if (links.size() > 0) {
- brokenLinks = validateLinks(links, offlineFilesLookup);
- }
+ if (links.size() > 0) {
+ brokenLinks = validateLinks(links, offlineFilesLookup);
+ }
- if (brokenLinks != null && brokenLinks.size() > 0) {
- // the resource contains broken links
- invalidResources.put(resourceName, brokenLinks);
- foundBrokenLinks = true;
- report.println(report.key("report.htmllink_validator.found_broken_links"), I_CmsReport.C_FORMAT_WARNING);
- } else {
- // the resource contains *NO* broken links
- report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
+ if (brokenLinks != null && brokenLinks.size() > 0) {
+ // the resource contains broken links
+ invalidResources.put(resourceName, brokenLinks);
+ foundBrokenLinks = true;
+ report.println(report.key("report.htmllink_validator.found_broken_links"), I_CmsReport.C_FORMAT_WARNING);
+ } else {
+ // the resource contains *NO* broken links
+ report.println(report.key("report.ok"), I_CmsReport.C_FORMAT_OK);
+ }
+ } catch (CmsException e) {
+ if (OpenCms.getLog(this).isErrorEnabled()) {
+ OpenCms.getLog(this).error("Error finding links in " + resourceName, e);
+ }
}
}
if (foundBrokenLinks) {
// print a summary if we found broken links in the validated resources
report.println(report.key("report.htmllink_validator.summary.begin"), I_CmsReport.C_FORMAT_HEADLINE);
-
+
Iterator outer = invalidResources.keySet().iterator();
while (outer.hasNext()) {
resourceName = (String) outer.next();
brokenLinks = (List) invalidResources.get(resourceName);
-
+
report.print(report.key("report.htmllink_validator.summary.broken_links_in"), I_CmsReport.C_FORMAT_NOTE);
report.print(resourceName);
report.println("\u0020:");
@@ -201,11 +208,11 @@ public class CmsHtmlLinkValidator extends Object {
report.println("\u0020" + (String) inner.next(), I_CmsReport.C_FORMAT_WARNING);
}
}
-
- report.println(report.key("report.htmllink_validator.summary.end"), I_CmsReport.C_FORMAT_HEADLINE);
+
+ report.println(report.key("report.htmllink_validator.summary.end"), I_CmsReport.C_FORMAT_HEADLINE);
report.println(report.key("report.htmllink_validator.error"), I_CmsReport.C_FORMAT_ERROR);
}
-
+
report.println(report.key("report.htmllink_validator.end"), I_CmsReport.C_FORMAT_HEADLINE);
return invalidResources;
|
Bugfix for the correct resource type detection to invoke the findLinks method on resource types implementing the I_CmsHtmlLinkValidatable interface.
|
alkacon_opencms-core
|
train
|
8b086fb2fa66104b7133160b90ddacad787f2c84
|
diff --git a/apiserver/uniter/uniter.go b/apiserver/uniter/uniter.go
index <HASH>..<HASH> 100644
--- a/apiserver/uniter/uniter.go
+++ b/apiserver/uniter/uniter.go
@@ -1585,7 +1585,7 @@ func (u *UniterAPIV3) getOneNetworkConfig(canAccess common.AuthFunc, unitTagArg,
)
privateAddress, err := machine.PrivateAddress()
- if err != nil && !network.IsNoAddressError(err) {
+ if err != nil {
return nil, errors.Annotatef(err, "getting machine %q preferred private address", machineID)
}
@@ -1613,13 +1613,13 @@ func (u *UniterAPIV3) getOneNetworkConfig(canAccess common.AuthFunc, unitTagArg,
for _, addr := range addresses {
subnet, err := addr.Subnet()
- if err != nil {
- return nil, errors.Annotatef(err, "cannot get subnet for address %q", addr)
- }
- if subnet == nil {
- logger.Debugf("skipping %s: not linked to a known subnet", addr)
+ if errors.IsNotFound(err) {
+ logger.Debugf("skipping %s: not linked to a known subnet (%v)", addr, err)
continue
+ } else if err != nil {
+ return nil, errors.Annotatef(err, "cannot get subnet for address %q", addr)
}
+
if space := subnet.SpaceName(); space != boundSpace {
logger.Debugf("skipping %s: want bound to space %q, got space %q", addr, boundSpace, space)
continue
|
apiserver/uniter: Drive-by fix for network-get
|
juju_juju
|
train
|
d646868238e2ece52c339d08c9b702b65066aee1
|
diff --git a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/VariantAnnotationCommandExecutor.java b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/VariantAnnotationCommandExecutor.java
index <HASH>..<HASH> 100644
--- a/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/VariantAnnotationCommandExecutor.java
+++ b/cellbase-app/src/main/java/org/opencb/cellbase/app/cli/VariantAnnotationCommandExecutor.java
@@ -154,7 +154,7 @@ public class VariantAnnotationCommandExecutor extends CommandExecutor {
// parallel parsing of these lines
if (input != null) {
DataReader dataReader = new StringDataReader(input);
- List<ParallelTaskRunner.Task<String, Variant>> variantAnnotatorTaskList = getStringTaskList();
+ List<ParallelTaskRunner.Task<String, Variant>> variantAnnotatorTaskList = getStringTaskList(false);
DataWriter dataWriter = getDataWriter(output.toString());
ParallelTaskRunner.Config config = new ParallelTaskRunner.Config(numThreads, batchSize, QUEUE_CAPACITY, false);
@@ -230,10 +230,10 @@ public class VariantAnnotationCommandExecutor extends CommandExecutor {
return dataWriter;
}
- private List<ParallelTaskRunner.Task<String, Variant>> getStringTaskList() throws IOException {
+ private List<ParallelTaskRunner.Task<String, Variant>> getStringTaskList(boolean normalize) throws IOException {
List<ParallelTaskRunner.Task<String, Variant>> variantAnnotatorTaskList = new ArrayList<>(numThreads);
for (int i = 0; i < numThreads; i++) {
- List<VariantAnnotator> variantAnnotatorList = createAnnotators();
+ List<VariantAnnotator> variantAnnotatorList = createAnnotators(normalize);
switch (inputFormat) {
case VCF:
logger.info("Using HTSJDK to read variants.");
@@ -256,10 +256,6 @@ public class VariantAnnotationCommandExecutor extends CommandExecutor {
return variantAnnotatorTaskList;
}
- private List<ParallelTaskRunner.Task<Variant, Variant>> getVariantTaskList() throws IOException {
- return this.getVariantTaskList(true);
- }
-
private List<ParallelTaskRunner.Task<Variant, Variant>> getVariantTaskList(boolean normalize) throws IOException {
List<ParallelTaskRunner.Task<Variant, Variant>> variantAnnotatorTaskList = new ArrayList<>(numThreads);
for (int i = 0; i < numThreads; i++) {
diff --git a/cellbase-core/src/main/java/org/opencb/cellbase/core/variant/annotation/VariantAnnotationCalculator.java b/cellbase-core/src/main/java/org/opencb/cellbase/core/variant/annotation/VariantAnnotationCalculator.java
index <HASH>..<HASH> 100644
--- a/cellbase-core/src/main/java/org/opencb/cellbase/core/variant/annotation/VariantAnnotationCalculator.java
+++ b/cellbase-core/src/main/java/org/opencb/cellbase/core/variant/annotation/VariantAnnotationCalculator.java
@@ -129,6 +129,8 @@ public class VariantAnnotationCalculator { //extends MongoDBAdaptor implements V
public List<QueryResult<VariantAnnotation>> getAnnotationByVariantList(List<Variant> variantList, QueryOptions queryOptions) {
+ logger.info("Annotating batch");
+
if (variantList == null || variantList.isEmpty()) {
return new ArrayList<>();
}
|
develop: bug solved. VariantNormalizer is no longer called two times when annotating with the CLI from a vcf file
|
opencb_cellbase
|
train
|
a8697746d0c7e81c6b5256b83650610669b0a0b8
|
diff --git a/pypot/dynamixel/motor.py b/pypot/dynamixel/motor.py
index <HASH>..<HASH> 100644
--- a/pypot/dynamixel/motor.py
+++ b/pypot/dynamixel/motor.py
@@ -88,7 +88,7 @@ class DxlMotor(Motor):
present_load = DxlOrientedRegister()
torque_limit = DxlRegister(rw=True)
- angle_limit = DxlRegister()
+ _angle_limit = DxlRegister()
present_voltage = DxlRegister()
present_temperature = DxlRegister()
@@ -102,6 +102,8 @@ class DxlMotor(Motor):
self.__dict__['model'] = model
self.__dict__['direct'] = direct
self.__dict__['offset'] = offset
+ self.__dict__['angle_limit'] = (numpy.asarray(self._angle_limit) if direct
+ else -1 * numpy.asarray(self._angle_limit)) - offset
self.__dict__['compliant'] = True
|
take "direct" and "offset" data into account for the angle_limit attribute.
|
poppy-project_pypot
|
train
|
39e2c9f484af47ecc8e110e6e1d9c8b2dc10d37b
|
diff --git a/driver-compat/src/test/com/mongodb/DBCursorOldTest.java b/driver-compat/src/test/com/mongodb/DBCursorOldTest.java
index <HASH>..<HASH> 100644
--- a/driver-compat/src/test/com/mongodb/DBCursorOldTest.java
+++ b/driver-compat/src/test/com/mongodb/DBCursorOldTest.java
@@ -153,7 +153,7 @@ public class DBCursorOldTest extends DatabaseTestCase {
}).start();
- Thread.sleep(5000);
+ Thread.sleep(500);
// this doc should unblock thread
c.save(new BasicDBObject("x", 10));
latch.await();
|
Decreasing sleep in test to try to make it faster.
|
mongodb_mongo-java-driver
|
train
|
6e3b167d93c3bf570f9ff8f75cb11f973d4a7852
|
diff --git a/zappa/core.py b/zappa/core.py
index <HASH>..<HASH> 100644
--- a/zappa/core.py
+++ b/zappa/core.py
@@ -2742,7 +2742,7 @@ class Zappa(object):
Remove the DynamoDB Table used for async return values
"""
- topic_name = get_topic_name(lambda_name)
+ topic_name = get_topic_name(table_name)
removed_arns = []
for sub in self.sns_client.list_subscriptions()['Subscriptions']:
if topic_name in sub['TopicArn']:
|
Undefined name: lambda_name --> table_name
|
Miserlou_Zappa
|
train
|
4d77630c9bb61b3ad7468418cc2ea9c676cbad9e
|
diff --git a/src/LarametricsLogServiceProvider.php b/src/LarametricsLogServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/LarametricsLogServiceProvider.php
+++ b/src/LarametricsLogServiceProvider.php
@@ -34,13 +34,15 @@ class LarametricsLogServiceProvider extends ServiceProvider {
LarametricsLog::destroy($expiredLogs);
}
- $larametricsLog = LarametricsLog::create([
- 'level' => $e->level,
- 'message' => $e->message,
- 'user_id' => count($e->context) ? $e->context['userId'] : null,
- 'email' => count($e->context) ? $e->context['email'] : null,
- 'trace' => count($e->context) ? json_encode($e->context['exception']->getTrace()) : '[]'
- ]);
+ if (config('larametrics.logsWatched')) {
+ $larametricsLog = LarametricsLog::create([
+ 'level' => $e->level,
+ 'message' => $e->message,
+ 'user_id' => count($e->context) ? $e->context['userId'] : null,
+ 'email' => count($e->context) ? $e->context['email'] : null,
+ 'trace' => count($e->context) ? json_encode($e->context['exception']->getTrace()) : '[]'
+ ]);
+ }
$logLevel = 'notice';
$notificationLevels = array(
|
Added config check around log creator.
Prevents logs from persisting to database if disabled in config.
|
aschmelyun_larametrics
|
train
|
09ece6f5307a894b3c37dfcefc7542c1d45ecc8f
|
diff --git a/tests/Commands/CheckUpdateTest.php b/tests/Commands/CheckUpdateTest.php
index <HASH>..<HASH> 100644
--- a/tests/Commands/CheckUpdateTest.php
+++ b/tests/Commands/CheckUpdateTest.php
@@ -3,6 +3,8 @@
namespace Codedge\Updater\Tests\Commands;
use Codedge\Updater\Commands\CheckForUpdate;
+use Codedge\Updater\SourceRepositoryTypes\GithubRepositoryType;
+use Codedge\Updater\SourceRepositoryTypes\GithubRepositoryTypes\GithubTagType;
use Codedge\Updater\Tests\TestCase;
final class CheckUpdateTest extends TestCase
@@ -20,6 +22,10 @@ final class CheckUpdateTest extends TestCase
/** @test */
public function it_can_run_check_update_command_with_new_version_available(): void
{
+ /** @var GithubTagType $github */
+ $github = (resolve(GithubRepositoryType::class))->create();
+ $github->setVersionFile('v3.5');
+
config(['self-update.version_installed' => 'v1.0']);
$this->artisan(CheckForUpdate::class)
|
Set version file before checking for new update
|
codedge_laravel-selfupdater
|
train
|
c80e380e112ceecca1439dda6ff33436ae4ba83e
|
diff --git a/build.js b/build.js
index <HASH>..<HASH> 100755
--- a/build.js
+++ b/build.js
@@ -4,7 +4,15 @@
var fs = require('fs');
var util = require('util');
-var EXPRESSION = /^\.\n([\s\S]*?)^\.\n([\s\S]*?)^\.$|^#{1,6} *(.*)$/gm;
+if (process.env.VERSION < 0.24) {
+ throw new Error(
+ 'This version of `commonmark.json` cannot extract specs ' +
+ 'lower than 0.24.\nUse an older version of `commonmark.json` ' +
+ 'instead'
+ );
+}
+
+var EXPRESSION = /^`{32} example\n([\s\S]*?)\n`{32}$|^#{1,6} *(.*)$/gm;
function rewrite(data) {
var examples = [];
@@ -14,15 +22,17 @@ function rewrite(data) {
data.replace(/\r\n?/g, '\n')
.replace(/→/g, '\t')
.replace(/^<!-- END TESTS -->(.|[\n])*/m, '')
- .replace(EXPRESSION, function($0, $1, $2, $3) {
- if ($3) {
- section = $3;
+ .replace(EXPRESSION, function($0, $1, $2) {
+ var example;
+ if ($2) {
+ section = $2;
} else {
index++;
+ example = $1.split(/\n\.(?:\n|$)/);
examples.push({
- 'markdown': $1,
- 'html': $2,
+ 'markdown': example[0] + '\n',
+ 'html': example[1] ? example[1] + '\n' : '',
'section': section
});
}
|
Update `build.js` for <I>
|
wooorm_commonmark.json
|
train
|
355709d3efd3dab9df326a130476d9f6f8d3325c
|
diff --git a/php/WP_CLI/AutoloadSplitter.php b/php/WP_CLI/AutoloadSplitter.php
index <HASH>..<HASH> 100644
--- a/php/WP_CLI/AutoloadSplitter.php
+++ b/php/WP_CLI/AutoloadSplitter.php
@@ -27,7 +27,7 @@ class AutoloadSplitter {
* @return bool Whether to split out the class into a separate autoloader.
*/
public function __invoke( $class, $code ) {
- return 1 === preg_match( '/.*\/wp-cli\/\w*(?:-\w*)*-command\/.*/', $code )
- || 1 === preg_match( '/.*\/php\/commands\/src\/.*/', $code );
+ return 1 === preg_match( '/\/wp-cli\/\w*(?:-\w*)*-command\//', $code )
+ || 1 === preg_match( '/\/php\/commands\/src\//', $code );
}
}
|
Regex: Remove leading and trailing .*
With no pinning of the pattern to the start or end of a string, the leading and trailing `.*` are redundant.
|
wp-cli_wp-cli
|
train
|
1b91f534ce91ff5d0a4d39d96a8f19b58022d403
|
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -22,7 +22,7 @@ module ActiveRecord
params << record.send(:id)
end
- finder_class.with_exclusive_scope do
+ finder_class.send(:with_exclusive_scope) do
if finder_class.exists?([sql, *params])
record.errors.add(attribute, :taken, :default => options[:message], :value => value)
end
|
Fix uniqueness validation: with_exclusive_scope is not public
|
rails_rails
|
train
|
1fdba6b0500f3d6182c98a44d28021a4a15ffeff
|
diff --git a/pyoos/parsers/awc.py b/pyoos/parsers/awc.py
index <HASH>..<HASH> 100644
--- a/pyoos/parsers/awc.py
+++ b/pyoos/parsers/awc.py
@@ -1,5 +1,4 @@
from __future__ import (absolute_import, division, print_function)
-from six import string_types
import pytz
from owslib.etree import etree
@@ -15,16 +14,7 @@ from datetime import datetime
class AwcToPaegan(object):
def __init__(self, awc_list):
for awc_data in awc_list:
- if isinstance(awc_data, string_types):
- try:
- # FIXME: Ideally we would pass bytes here rather than encoding.
- # to be consistent with the rest of the code and ditch the hack below.
- self._root = etree.fromstring(str(awc_data).encode())
- except ValueError:
- # Strip out the XML header due to UTF8 encoding declaration
- self._root = etree.fromstring(awc_data[56:])
- else:
- raise ValueError("Cannot parse response into ElementTree xml object")
+ self._root = etree.fromstring(awc_data.encode())
'''Code to get station iterator goes here.'''
stations = []
diff --git a/pyoos/parsers/waterml.py b/pyoos/parsers/waterml.py
index <HASH>..<HASH> 100644
--- a/pyoos/parsers/waterml.py
+++ b/pyoos/parsers/waterml.py
@@ -1,8 +1,7 @@
from __future__ import (absolute_import, division, print_function)
-from six import text_type
import pytz
-from owslib.etree import etree
+from owslib.etree import ElementType, etree
from owslib.waterml.wml11 import WaterML_1_1
from shapely.geometry import Point as sPoint
@@ -15,16 +14,10 @@ from paegan.cdm.dsg.member import Member
class WaterML11ToPaegan(object):
def __init__(self, waterml_data):
- if isinstance(waterml_data, text_type):
- try:
- # FIXME: Ideally we would pass bytes here rather than encoding.
- # to be consistent with the rest of the code and ditch the hack below.
- self._root = etree.fromstring(str(waterml_data).encode())
- except ValueError:
- # Strip out the XML header due to UTF8 encoding declaration
- self._root = etree.fromstring(waterml_data[56:])
- else:
+ if isinstance(waterml_data, ElementType):
self._root = waterml_data
+ else:
+ self._root = etree.fromstring(waterml_data.encode())
response = WaterML_1_1(self._root).response
|
Test passing bytes when unicode is expected.
|
ioos_pyoos
|
train
|
cde853709f35c1d7c45f416bb9d4a874d82945b4
|
diff --git a/certbot/tests/test_server.py b/certbot/tests/test_server.py
index <HASH>..<HASH> 100644
--- a/certbot/tests/test_server.py
+++ b/certbot/tests/test_server.py
@@ -4,7 +4,7 @@ import treq
from twisted.internet.defer import inlineCallbacks
from twisted.protocols.loopback import _LoopbackAddress
from twisted.trial.unittest import TestCase
-from twisted.web.client import ProxyAgent
+from twisted.web.client import ProxyAgent, URI
from twisted.web.server import Site
from txfake import FakeServer
@@ -14,6 +14,19 @@ from uritools import uricompose
from certbot.server import MarathonEventServer, Health
+class FakeServerAgent(ProxyAgent):
+ """
+ ProxyAgent uses the entire URI as the request path, which is the correct
+ thing to do when talking to a proxy but not for non-proxy servers.
+ """
+ def request(self, method, uri, headers=None, bodyProducer=None):
+ key = ("http-proxy", self._proxyEndpoint)
+ parsedURI = URI.fromBytes(uri)
+ return self._requestWithEndpoint(
+ key, self._proxyEndpoint, method, parsedURI, headers,
+ bodyProducer, parsedURI.originForm)
+
+
class MarathonEventServerTest(TestCase):
def setUp(self):
@@ -26,7 +39,7 @@ class MarathonEventServerTest(TestCase):
_LoopbackAddress.port = 7000
fake_server = FakeServer(Site(self.event_server.app.resource()))
- self.agent = ProxyAgent(fake_server.endpoint)
+ self.agent = FakeServerAgent(fake_server.endpoint)
def request(self, method, path, query=None, json_data=None):
url = uricompose('http', 'www.example.com', path, query)
|
Use our own proxy agent to avoid getting the full URI in the request path.
|
praekeltfoundation_marathon-acme
|
train
|
69416316e8ba086dfba7c55ff99a8fb305acb1b3
|
diff --git a/ipywidgets/static/widgets/js/manager.js b/ipywidgets/static/widgets/js/manager.js
index <HASH>..<HASH> 100644
--- a/ipywidgets/static/widgets/js/manager.js
+++ b/ipywidgets/static/widgets/js/manager.js
@@ -433,8 +433,7 @@ define([
model_module: state[model_id].model_module,
}).then(function(model) {
model.set_comm_live(false);
- var deserialized = model._deserialize_state(state[model.id].state);
- return utils.resolve_promises_dict(deserialized).then(function(state) {
+ return model._deserialize_state(state[model.id].state).then(function(state) {
model.set_state(state);
return model.request_state().then(function() {
model.set_comm_live(true);
diff --git a/ipywidgets/static/widgets/js/widget.js b/ipywidgets/static/widgets/js/widget.js
index <HASH>..<HASH> 100644
--- a/ipywidgets/static/widgets/js/widget.js
+++ b/ipywidgets/static/widgets/js/widget.js
@@ -176,10 +176,10 @@ define(["nbextensions/widgets/widgets/js/manager",
deserialized[k] = state[k];
}
}
- return deserialized;
} else {
- return state;
+ deserialized = state;
}
+ return utils.resolve_promises_dict(deserialized);
},
_handle_comm_msg: function (msg) {
/**
@@ -198,8 +198,7 @@ define(["nbextensions/widgets/widgets/js/manager",
for (var i=0; i<buffer_keys.length; i++) {
state[buffer_keys[i]] = buffers[i];
}
- state = that._deserialize_state(state);
- return utils.resolve_promises_dict(state);
+ return that._deserialize_state(state);
}).then(function(state) {
return that.set_state(state);
}).catch(utils.reject("Couldn't process update msg for model id '" + String(that.id) + "'", true))
|
remove calls to resolve_promise_dict
|
jupyter-widgets_ipywidgets
|
train
|
b4c252717ee47cf6e66b9b3377fb179a81f38f0a
|
diff --git a/pymc3/step_methods/arraystep.py b/pymc3/step_methods/arraystep.py
index <HASH>..<HASH> 100644
--- a/pymc3/step_methods/arraystep.py
+++ b/pymc3/step_methods/arraystep.py
@@ -156,8 +156,10 @@ class Constant(ArrayStep):
self.model = model
+ vars = inputvars(vars)
+
super(Constant, self).__init__(vars, [model.fastlogp], **kwargs)
def astep(self, q0, logp):
- return q0
\ No newline at end of file
+ return q0
|
Add var cleanup to Constant step method
|
pymc-devs_pymc
|
train
|
503b136c92dd52a2f2a920d7243b1de5c955127d
|
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -86,6 +86,12 @@ module Specs
next if thread.backtrace.empty?
next if thread.backtrace.first =~ /rubysl\/timeout\/timeout.rb/
end
+
+ if RUBY_ENGINE == "ruby"
+ # Sometimes stays
+ next if thread.backtrace.first =~ /\/timeout\.rb/
+ end
+
thread
end.compact
end
|
ignore MRI timer threads in specs
|
celluloid_celluloid
|
train
|
b67ecd8d9d9729937dafccfaa38af6944610e0b6
|
diff --git a/buildbot/scripts/tryclient.py b/buildbot/scripts/tryclient.py
index <HASH>..<HASH> 100644
--- a/buildbot/scripts/tryclient.py
+++ b/buildbot/scripts/tryclient.py
@@ -187,7 +187,7 @@ class MercurialExtractor(SourceStampExtractor):
class PerforceExtractor(SourceStampExtractor):
- patchlevel = 1
+ patchlevel = 0
vcexe = "p4"
def getBaseRevision(self):
d = self.dovc(["changes", "-m1", "..."])
@@ -209,19 +209,19 @@ class PerforceExtractor(SourceStampExtractor):
#
# extract the actual patch from "res"
#
+ assert self.branch, "you must specify a branch"
mpatch = ""
- branch = "main"
+ found = False
for line in res.split("\n"):
- m = re.search(r'==== //depot/([\w\_\-]+)/([\w\/\.\d\-\_]+)#(\d+) -',line)
+ m = re.search('==== //depot/' + self.branch + r'/([\w\/\.\d\-\_]+)#(\d+) -',line)
if m:
- mpatch += "--- /%s#%s\n" % (m.group(2), m.group(3) )
- mpatch += "+++ /%s\n" % (m.group(2) )
- branch = m.group(1)
- pass
+ mpatch += "--- %s#%s\n" % (m.group(1), m.group(2) )
+ mpatch += "+++ %s\n" % (m.group(1) )
+ found = True
else:
mpatch += line
mpatch += "\n"
- self.branch = branch
+ assert found, "could not parse patch file"
self.patch = (patchlevel, mpatch)
def getPatch(self, res):
d = self.dovc(["diff", "-du"])
|
PerforceExtractor: require that the user specify a branch
|
buildbot_buildbot
|
train
|
2da0bfba95096d12187faf522e32a360bf14e6eb
|
diff --git a/lease/auto_refreshing_read_lease.go b/lease/auto_refreshing_read_lease.go
index <HASH>..<HASH> 100644
--- a/lease/auto_refreshing_read_lease.go
+++ b/lease/auto_refreshing_read_lease.go
@@ -23,9 +23,11 @@ import "io"
// first time and whenever the supplied file leaser decides to expire the
// temporary copy thus obtained. It must return the same contents every time,
// and the contents must be of the given size.
+//
+// This magic is not preserved after the lease is upgraded.
func NewAutoRefreshingReadLease(
fl FileLeaser,
size int64,
- f func() (io.Reader, error)) (rl ReadLease) {
+ f func() (io.ReadCloser, error)) (rl ReadLease) {
panic("TODO")
}
|
Specified upgrade behavior, and guaranteed closing.
|
jacobsa_ratelimit
|
train
|
6e9cf2d068807d71ac137ce6989094b1d2d0e0d5
|
diff --git a/externs/w3c_css.js b/externs/w3c_css.js
index <HASH>..<HASH> 100644
--- a/externs/w3c_css.js
+++ b/externs/w3c_css.js
@@ -1171,6 +1171,42 @@ CSSProperties.prototype.borderTopLeftRadius;
CSSProperties.prototype.borderTopRightRadius;
/**
+ * @type {string}
+ * @see http://www.w3.org/TR/css3-background/#the-border-image-source
+ */
+CSSProperties.prototype.borderImageSource;
+
+/**
+ * @type {string|number}
+ * @see http://www.w3.org/TR/css3-background/#the-border-image-slice
+ */
+CSSProperties.prototype.borderImageSlice;
+
+/**
+ * @type {string|number}
+ * @see http://www.w3.org/TR/css3-background/#the-border-image-width
+ */
+CSSProperties.prototype.borderImageWidth;
+
+/**
+ * @type {string|number}
+ * @see http://www.w3.org/TR/css3-background/#the-border-image-outset
+ */
+CSSProperties.prototype.borderImageOutset;
+
+/**
+ * @type {string}
+ * @see http://www.w3.org/TR/css3-background/#the-border-image-repeat
+ */
+CSSProperties.prototype.borderImageRepeat;
+
+/**
+ * @type {string}
+ * @see http://www.w3.org/TR/css3-background/#the-border-image
+ */
+CSSProperties.prototype.borderImage;
+
+/**
* @type {string|number}
* @see http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSProperties-bottom
*/
|
Add "borderImage" and related properties to CSSProperties extern.
|
google_closure-compiler
|
train
|
74d2356f5fa39e79fc02ca1099c161d3ef555f77
|
diff --git a/src/main/java/com/github/davidmoten/rx/internal/operators/OperatorBufferToFile.java b/src/main/java/com/github/davidmoten/rx/internal/operators/OperatorBufferToFile.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/github/davidmoten/rx/internal/operators/OperatorBufferToFile.java
+++ b/src/main/java/com/github/davidmoten/rx/internal/operators/OperatorBufferToFile.java
@@ -97,9 +97,10 @@ public final class OperatorBufferToFile<T> implements Operator<T, T> {
private final DB db;
private final Queue<T> queue;
+ private final AtomicBoolean closing = new AtomicBoolean(false);
private final AtomicBoolean closed = new AtomicBoolean(false);
- // ensures close doesn't occur until outstanding peek(),offer(), poll(),
+ // ensures db.close() doesn't occur until outstanding peek(),offer(), poll(),
// isEmpty() calls have finished
private final AtomicInteger currentCalls = new AtomicInteger(0);
@@ -112,13 +113,14 @@ public final class OperatorBufferToFile<T> implements Operator<T, T> {
public T peek() {
try {
currentCalls.incrementAndGet();
- if (closed.get()) {
+ if (closing.get()) {
return null;
} else {
return queue.peek();
}
} finally {
currentCalls.decrementAndGet();
+ checkClosed();
}
}
@@ -126,13 +128,14 @@ public final class OperatorBufferToFile<T> implements Operator<T, T> {
public T poll() {
try {
currentCalls.incrementAndGet();
- if (closed.get()) {
+ if (closing.get()) {
return null;
} else {
return queue.poll();
}
} finally {
currentCalls.decrementAndGet();
+ checkClosed();
}
}
@@ -140,13 +143,14 @@ public final class OperatorBufferToFile<T> implements Operator<T, T> {
public boolean offer(T t) {
try {
currentCalls.incrementAndGet();
- if (closed.get()) {
+ if (closing.get()) {
return true;
} else {
return queue.offer(t);
}
} finally {
currentCalls.decrementAndGet();
+ checkClosed();
}
}
@@ -154,27 +158,27 @@ public final class OperatorBufferToFile<T> implements Operator<T, T> {
public boolean isEmpty() {
try {
currentCalls.incrementAndGet();
- if (closed.get()) {
+ if (closing.get()) {
return true;
} else {
return queue.isEmpty();
}
} finally {
currentCalls.decrementAndGet();
+ checkClosed();
}
}
@Override
public void close() {
- if (closed.compareAndSet(false, true)) {
- while (true) {
- // spins to find chance to close
- if (currentCalls.get() == 0) {
- db.close();
- return;
- }
- //TODO investigate if should sleep here
- }
+ if (closing.compareAndSet(false, true)) {
+ checkClosed();
+ }
+ }
+
+ private void checkClosed() {
+ if (closing.get() && currentCalls.get() == 0 && closed.compareAndSet(false, true)) {
+ db.close();
}
}
diff --git a/src/test/java/com/github/davidmoten/rx/internal/operators/OperatorBufferToFileTest.java b/src/test/java/com/github/davidmoten/rx/internal/operators/OperatorBufferToFileTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/github/davidmoten/rx/internal/operators/OperatorBufferToFileTest.java
+++ b/src/test/java/com/github/davidmoten/rx/internal/operators/OperatorBufferToFileTest.java
@@ -342,7 +342,7 @@ public final class OperatorBufferToFileTest {
public void checkRateForSmallMessages() {
Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(1));
DataSerializer<Integer> serializer = DataSerializers.integer();
- int max = 100000;
+ int max = 1000;
long t = System.currentTimeMillis();
int last = Observable.range(1, max)
//
|
spin used to close db in Queue2 could take non-trivial time so use non-blocking method by checking for close condition at end of each method call in Queue2
|
davidmoten_rxjava-extras
|
train
|
b0ac608884d3d350f37791c3040655f08c8f60b5
|
diff --git a/ruby_event_store/lib/ruby_event_store/in_memory_repository.rb b/ruby_event_store/lib/ruby_event_store/in_memory_repository.rb
index <HASH>..<HASH> 100644
--- a/ruby_event_store/lib/ruby_event_store/in_memory_repository.rb
+++ b/ruby_event_store/lib/ruby_event_store/in_memory_repository.rb
@@ -24,20 +24,23 @@ module RubyEventStore
attr_accessor :record
end
- def initialize(serializer: NULL)
+ def initialize(serializer: NULL, verify_incorrect_any_usage: false)
@serializer = serializer
@streams = Hash.new { |h, k| h[k] = Array.new }
@mutex = Mutex.new
@storage = Hash.new
@next_global_position = 1
+ @verify_incorrect_any_usage = verify_incorrect_any_usage
end
def append_to_stream(records, stream, expected_version)
serialized_records = records.map { |record| record.serialize(serializer) }
with_synchronize(expected_version, stream) do |resolved_version|
- raise UnsupportedVersionAnyUsage if resolved_version.nil? && !streams.fetch(stream.name, Array.new).map(&:position).compact.empty?
- raise UnsupportedVersionAnyUsage if !resolved_version.nil? && streams.fetch(stream.name, Array.new).map(&:position).include?(nil)
+ if @verify_incorrect_any_usage
+ raise UnsupportedVersionAnyUsage if resolved_version.nil? && !streams.fetch(stream.name, Array.new).map(&:position).compact.empty?
+ raise UnsupportedVersionAnyUsage if !resolved_version.nil? && streams.fetch(stream.name, Array.new).map(&:position).include?(nil)
+ end
raise WrongExpectedEventVersion unless resolved_version.nil? || last_stream_version(stream).equal?(resolved_version)
serialized_records.each_with_index do |serialized_record, index|
@@ -177,12 +180,7 @@ module RubyEventStore
end
def last_stream_version(stream)
- events_in_stream = streams.fetch(stream.name, Array.new)
- if events_in_stream.empty?
- ExpectedVersion::POSITION_DEFAULT
- else
- events_in_stream.last.position
- end
+ streams.fetch(stream.name, Array.new).size - 1
end
def with_synchronize(expected_version, stream, &block)
diff --git a/ruby_event_store/spec/in_memory_repository_spec.rb b/ruby_event_store/spec/in_memory_repository_spec.rb
index <HASH>..<HASH> 100644
--- a/ruby_event_store/spec/in_memory_repository_spec.rb
+++ b/ruby_event_store/spec/in_memory_repository_spec.rb
@@ -72,6 +72,7 @@ module RubyEventStore
end
it 'publishing with any position to stream with specific position raise an error' do
+ repository = InMemoryRepository.new(verify_incorrect_any_usage: true)
repository.append_to_stream([
event0 = SRecord.new,
], stream, version_auto)
@@ -84,6 +85,7 @@ module RubyEventStore
end
it 'publishing with specific position to stream with any position raise an error' do
+ repository = InMemoryRepository.new(verify_incorrect_any_usage: true)
repository.append_to_stream([
event0 = SRecord.new,
], stream, version_any)
@@ -94,5 +96,33 @@ module RubyEventStore
], stream, version_auto)
end.to raise_error(RubyEventStore::InMemoryRepository::UnsupportedVersionAnyUsage)
end
+
+ # This test only documents the 2.x behavior
+ it 'publishing with any position to stream with specific position' do
+ repository = InMemoryRepository.new(verify_incorrect_any_usage: false)
+ repository.append_to_stream([
+ event0 = SRecord.new,
+ ], stream, version_auto)
+
+ expect do
+ repository.append_to_stream([
+ event1 = SRecord.new,
+ ], stream, version_any)
+ end.not_to raise_error
+ end
+
+ # This test only documents the 2.x behavior
+ it 'publishing with specific position to stream with any position' do
+ repository = InMemoryRepository.new(verify_incorrect_any_usage: false)
+ repository.append_to_stream([
+ event0 = SRecord.new,
+ ], stream, version_any)
+
+ expect do
+ repository.append_to_stream([
+ event1 = SRecord.new,
+ ], stream, version_auto)
+ end.not_to raise_error
+ end
end
end
|
Do not verify incorrect any usage by default
And make the event resolver so all tests pass
|
RailsEventStore_rails_event_store
|
train
|
1bd639ce18482637455b82228effbc80e01b5f9d
|
diff --git a/bqplot/interacts.py b/bqplot/interacts.py
index <HASH>..<HASH> 100644
--- a/bqplot/interacts.py
+++ b/bqplot/interacts.py
@@ -546,10 +546,16 @@ class LassoSelector(TwoDSelector):
encompass any mark data will be automatically deleted
The user can select(de-select) by clicking on lassos and can delete them
- (and their associsted data) by pressing 'Delete' button
+ (and their associated data) by pressing the 'Delete' button
+
+ Attributes
+ ----------
+ color: string
+ color of the lasso
"""
marks = List(Instance(Lines) | Instance(Scatter), sync=True)
+ color = Unicode(default_value='orange', sync=True)
def __init__(self, marks=None, **kwargs):
_marks = []
diff --git a/bqplot/nbextension/LassoSelector.js b/bqplot/nbextension/LassoSelector.js
index <HASH>..<HASH> 100644
--- a/bqplot/nbextension/LassoSelector.js
+++ b/bqplot/nbextension/LassoSelector.js
@@ -48,18 +48,27 @@ define(["d3", "./Selector", "./utils", "./lasso_test"], function(d3, Selectors,
self.create_listeners();
});
},
+ create_listeners: function() {
+ LassoSelector.__super__.create_listeners.apply(this);
+ this.model.on("change:color", this.change_color, this);
+ },
+ change_color: function(model, color) {
+ this.el.selectAll("path").attr("stroke", color);
+ },
drag_start: function() {
+ var self = this;
this.lasso_vertices = [];
this.el.append("path")
.attr("id", "l" + ++this.lasso_counter)
.attr("fill", "none")
- .attr("stroke", "orange")
+ .attr("stroke", this.model.get("color"))
.attr("stroke-width", 4)
.on("click", function() {
+ //toggle the opacity of lassos
var lasso = d3.select(this);
var selected = lasso.classed("selected");
lasso.classed("selected", !selected)
- .attr("stroke", !selected ? "red" : "orange"); });
+ .attr("opacity", !selected ? 0.4 : 1.0); });
},
drag_move: function() {
this.lasso_vertices.push(d3.mouse(this.background.node()));
|
Added color attribute for lasso selector
|
bloomberg_bqplot
|
train
|
a03690bd70afed74b8d514928092b652da7f2ee9
|
diff --git a/lib/datasource/rubygems/retriable.js b/lib/datasource/rubygems/retriable.js
index <HASH>..<HASH> 100644
--- a/lib/datasource/rubygems/retriable.js
+++ b/lib/datasource/rubygems/retriable.js
@@ -13,8 +13,9 @@ const NUMBER_OF_RETRIES = 5;
const getDelayStep = () =>
parseInt(process.env.RENOVATE_RUBYGEMS_RETRY_DELAY_STEP || '1000', 10);
-const toMs = value => parseInt(value, 10) * getDelayStep();
-const getBannedDelay = retryAfter => (retryAfter || RETRY_AFTER) + 1;
+const toMs = value => value * getDelayStep();
+const getBannedDelay = retryAfter =>
+ (parseInt(retryAfter, 10) || RETRY_AFTER) + 1;
const getDefaultDelay = count => (NUMBER_OF_RETRIES * getDelayStep()) / count;
const getDelayMessage = delay => `Retry in ${delay} seconds.`;
|
fix(rubygems): fix delay parsing (#<I>)
fix(rubygems): fix delay parsing
|
renovatebot_renovate
|
train
|
57d4fb1bf87d95b8da3ce55345e1633a267c8cc6
|
diff --git a/src/Translator.php b/src/Translator.php
index <HASH>..<HASH> 100644
--- a/src/Translator.php
+++ b/src/Translator.php
@@ -90,7 +90,8 @@ class Translator implements TranslatorInterface
*/
protected function getMessage($key)
{
- if ($message = ($this->package->getMessage($key))) {
+ $message = $this->package->getMessage($key);
+ if ($message) {
return $message;
}
|
Readability, separating assignment and if statement
|
auraphp_Aura.Intl
|
train
|
46b4ee6386fad32f1f8638d84a969680908c5860
|
diff --git a/hibernate-validation-service/src/main/java/org/wisdom/validation/hibernate/HibernateValidatorModule.java b/hibernate-validation-service/src/main/java/org/wisdom/validation/hibernate/HibernateValidatorModule.java
index <HASH>..<HASH> 100644
--- a/hibernate-validation-service/src/main/java/org/wisdom/validation/hibernate/HibernateValidatorModule.java
+++ b/hibernate-validation-service/src/main/java/org/wisdom/validation/hibernate/HibernateValidatorModule.java
@@ -35,7 +35,7 @@ public class HibernateValidatorModule {
repository.unregister(module);
}
- public Version version() {
+ public final Version version() {
return new Version(bundle.getVersion().getMajor(), bundle.getVersion().getMinor(),
bundle.getVersion().getMicro(), null, null, null);
}
|
[TD] major
* Overridable method 'version' called during object construction
|
wisdom-framework_wisdom
|
train
|
693da1390cc57e971553547340d68796d62ce24f
|
diff --git a/CalendarIOS.js b/CalendarIOS.js
index <HASH>..<HASH> 100644
--- a/CalendarIOS.js
+++ b/CalendarIOS.js
@@ -110,7 +110,7 @@ let Calendar = React.createClass({
renderHeading() {
return (
<View style={this.styles.calendarHeading}>
- {this.props.dayHeadings.map((day, i) => { return (<Text style={i == 0 || i == 6 ? this.styles.weekendHeading : this.styles.dayHeading}>{day}</Text>) })}
+ {this.props.dayHeadings.map((day, i) => { return (<Text key={i} style={i == 0 || i == 6 ? this.styles.weekendHeading : this.styles.dayHeading}>{day}</Text>) })}
</View>
)
},
@@ -128,7 +128,7 @@ let Calendar = React.createClass({
var days = [];
for (var j = 0; j < MAX_ROWS; j++) {
if (preFiller < offset) {
- days.push(<TouchableWithoutFeedback><View style={this.styles.dayButtonFiller}><Text style={this.styles.day}></Text></View></TouchableWithoutFeedback>);
+ days.push(<TouchableWithoutFeedback key={`${i},${j}`}><View style={this.styles.dayButtonFiller}><Text style={this.styles.day}></Text></View></TouchableWithoutFeedback>);
} else {
if(currentDay < daysInMonth) {
var newDay = moment(dayStart).set('date', currentDay + 1);
@@ -144,6 +144,7 @@ let Calendar = React.createClass({
days.push((
<TouchableOpacity
+ key={`${i},${j}`}
style={this.styles.touchableOpacity}
onPress={this._selectDate.bind(this, newDay)}>
<View style={this.styles.dayButton}>
@@ -166,7 +167,7 @@ let Calendar = React.createClass({
if(days.length > 0 && days.length < 7) {
for (var x = days.length; x < 7; x++) {
days.push(
- <TouchableWithoutFeedback>
+ <TouchableWithoutFeedback key={x}>
<View style={this.styles.dayButtonFiller}>
<Text style={this.styles.day}></Text>
</View>
|
Fixing the key prop error for arrays of objects
|
christopherdro_react-native-calendar
|
train
|
9275dabe7370c384de6c119a3450ea4d59d7a025
|
diff --git a/lib/era_ja/conversion.rb b/lib/era_ja/conversion.rb
index <HASH>..<HASH> 100644
--- a/lib/era_ja/conversion.rb
+++ b/lib/era_ja/conversion.rb
@@ -30,7 +30,7 @@ module EraJa
@era_format = format.gsub(/%J/, "%J%")
str_time = strftime(@era_format)
- if @era_format =~ /%([EOo]|1O)/
+ if @era_format =~ /%(-?E|[Oo]|1O)/
case
when self.to_time < ::Time.mktime(1912,7,30)
str_time = era_year(year - 1867, :meiji, era_names)
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -26,6 +26,10 @@ RSpec.shared_examples "should equal '令和01年07月02日'" do
context "with '%O%J%-E年%m月%d日'" do
it { expect(subject.to_era("%O%J%-E年%m月%d日")).to eq "令和元年07月02日" }
end
+
+ context "with '%-E年%-m月%-d日'" do
+ it { expect(subject.to_era("%-E年%-m月%-d日")).to eq "1年7月2日" }
+ end
end
RSpec.shared_examples "should equal 'R01.05.01'" do
|
Fix conversion '%-E' to single digit era year
|
tomiacannondale_era_ja
|
train
|
9045b7055fa936272e3bee0444a4ebf408bba0d3
|
diff --git a/src/entry.js b/src/entry.js
index <HASH>..<HASH> 100644
--- a/src/entry.js
+++ b/src/entry.js
@@ -25,8 +25,6 @@ exports.create = function createEntry(kind, value, options) {
}
entry._gr = [options.owner];
- util.promisifySave(entry);
-
return entry;
};
diff --git a/src/kind.js b/src/kind.js
index <HASH>..<HASH> 100644
--- a/src/kind.js
+++ b/src/kind.js
@@ -183,8 +183,6 @@ function createChild(kind, value) {
child._newChild = true;
child._parent = self;
- util.promisifySave(child);
-
return child;
}
diff --git a/src/util.js b/src/util.js
index <HASH>..<HASH> 100644
--- a/src/util.js
+++ b/src/util.js
@@ -1,19 +1,4 @@
'use strict';
-var Promise = require('native-or-bluebird');
-
exports.noop = function noop() {
};
-
-exports.promisifySave = function (entry) {
- // TODO check mongoose updates
- // This is an addition to allow save to behave like a Promise
- var save = entry.save;
- entry.save = function () {
- return new Promise(function (resolve, reject) {
- save.call(entry, function (err) {
- err ? reject(err) : resolve();
- });
- });
- };
-};
|
remove util.promisifySave
not needed anymore, mongoose supports it
|
cheminfo_hds
|
train
|
87cf4e9e96c8e201e2458e1d1142b434538a815b
|
diff --git a/lib/runner.js b/lib/runner.js
index <HASH>..<HASH> 100644
--- a/lib/runner.js
+++ b/lib/runner.js
@@ -17,7 +17,7 @@ const fork = require('child_process').fork;
const debug = require('debug')('artillery:runner');
const L = require('lodash');
-const stats = require('../../artillery-core').stats;
+const stats = require('artillery-core').stats;
const distribute = require('./dist');
module.exports = createRunner;
@@ -47,7 +47,7 @@ Runner.prototype.run = function run() {
//
// Create worker scripts (distribute the work):
//
- let numWorkers = process.env.ARTILLERY_WORKERS || os.cpus().length;
+ let numWorkers = 1; // process.env.ARTILLERY_WORKERS || os.cpus().length;
let workerScripts = divideWork(this._script, numWorkers);
// Overwrite statsInterval for workers:
L.each(workerScripts, function(s) {
|
Spawn exactly one worker for now
|
artilleryio_artillery
|
train
|
30098a2c1a396db9a3234a37a8875b6b2af725ec
|
diff --git a/tests/unit/test_doc.py b/tests/unit/test_doc.py
index <HASH>..<HASH> 100644
--- a/tests/unit/test_doc.py
+++ b/tests/unit/test_doc.py
@@ -8,6 +8,7 @@
from __future__ import absolute_import
import os
import re
+import logging
# Import Salt Testing libs
from tests.support.paths import CODE_DIR
@@ -18,6 +19,9 @@ import salt.modules.cmdmod
import salt.utils.platform
+log = logging.getLogger(__name__)
+
+
class DocTestCase(TestCase):
'''
Unit test case for testing doc files and strings.
@@ -37,15 +41,20 @@ class DocTestCase(TestCase):
salt_dir = CODE_DIR
if salt.utils.platform.is_windows():
- # No grep in Windows, use findstr
- # findstr in windows doesn't prepend 'Binary` to binary files, so
- # use the '/P' switch to skip files with unprintable characters
- cmd = 'findstr /C:":doc:" /S /P {0}\\*'.format(salt_dir)
+ if salt.utils.path.which('bash'):
+ # Use grep from git-bash when it exists.
+ cmd = 'bash -c \'grep -r :doc: ./salt/'.format(salt_dir)
+ grep_call = salt.modules.cmdmod.run_stdout(cmd=cmd, cwd=salt_dir).split(os.linesep)
+ else:
+ # No grep in Windows, use findstr
+ # findstr in windows doesn't prepend 'Binary` to binary files, so
+ # use the '/P' switch to skip files with unprintable characters
+ cmd = 'findstr /C:":doc:" /S /P {0}\\*'.format(salt_dir)
+ grep_call = salt.modules.cmdmod.run_stdout(cmd=cmd).split(os.linesep)
else:
salt_dir += '/'
cmd = 'grep -r :doc: ' + salt_dir
-
- grep_call = salt.modules.cmdmod.run_stdout(cmd=cmd).split(os.linesep)
+ grep_call = salt.modules.cmdmod.run_stdout(cmd=cmd).split(os.linesep)
test_ret = {}
for line in grep_call:
@@ -56,7 +65,11 @@ class DocTestCase(TestCase):
# Only split on colons not followed by a '\' as is the case with
# Windows Drives
regex = re.compile(r':(?!\\)')
- key, val = regex.split(line, 1)
+ try:
+ key, val = regex.split(line, 1)
+ except ValueError:
+ log.error("Could not split line: %s", line)
+ continue
# Don't test man pages, this file, the tox or nox virtualenv files,
# the page that documents to not use ":doc:", the doc/conf.py file
|
Fix test_doc on windows by using grep yay!
|
saltstack_salt
|
train
|
89c0fc25723097ff76d2e056947f31df40b7f7f7
|
diff --git a/blockstack/lib/config.py b/blockstack/lib/config.py
index <HASH>..<HASH> 100644
--- a/blockstack/lib/config.py
+++ b/blockstack/lib/config.py
@@ -510,6 +510,7 @@ def default_blockstack_opts( config_file=None ):
zonefile_storage_drivers = "disk"
profile_storage_drivers = ""
server_version = None
+ atlas_enabled = True
if parser.has_section('blockstack'):
@@ -578,6 +579,12 @@ def default_blockstack_opts( config_file=None ):
if parser.has_option('blockstack', 'server_version'):
server_version = parser.get('blockstack', 'server_version')
+ if parser.has_option('blockstack', 'atlas'):
+ atlas_enabled = parser.get('blockstack', 'atlas')
+ if atlas_enabled.lower() in ['true', '1', 'enabled', 'enabled', 'on']:
+ atlas_enabled = True
+ else:
+ atlas_enabled = False
if os.path.exists( announce_path ):
# load announcement list
@@ -614,7 +621,8 @@ def default_blockstack_opts( config_file=None ):
'profile_storage_drivers': profile_storage_drivers,
'zonefiles': zonefile_dir,
'analytics_key': analytics_key,
- 'server_version': server_version
+ 'server_version': server_version,
+ 'atlas': atlas_enabled
}
# strip Nones
|
support `atlas = [True|False]` under `[blockstack]`
|
blockstack_blockstack-core
|
train
|
5d05eb2b344b2233135c45f1fd0281c0e1cb7813
|
diff --git a/cwtools/jsimp.py b/cwtools/jsimp.py
index <HASH>..<HASH> 100644
--- a/cwtools/jsimp.py
+++ b/cwtools/jsimp.py
@@ -250,6 +250,8 @@ class _BaseScript(object):
if self._stringCache is not None:
return self._stringCache
+ self._implicitlyImportsParents = True # by default, assume it is not Closure-style code.
+
# Returns a list of UTF-8 encoded strings.
data = dict(imports=[], requires=[])
imports = data['imports']
@@ -261,6 +263,8 @@ class _BaseScript(object):
imports.append(line.rstrip().replace('//import ', '', 1).encode('utf-8'))
elif line.startswith('goog.require('):
requires.append(_extractOneArgFromFuncall(line, 'goog.require').encode('utf-8'))
+ elif line.startswith('goog.provide('):
+ self._implicitlyImportsParents = False
self._stringCache = data
return data
@@ -288,32 +292,37 @@ class _BaseScript(object):
deps = []
namesSeen = set()
+ data = self._getImportantStrings()
- # Parent module is an implicit dependency
- parent = self.getParent(treeCache)
- if parent:
- deps.append(parent)
+ # Parent module is an implicit dependency for Divmod/CW-style code.
+ if self._implicitlyImportsParents:
+ parent = self.getParent(treeCache)
+ if parent:
+ deps.append(parent)
# Forced dependencies, if any
forced = self._getForcedDependencies()
if forced:
deps.extend(forced)
- for importeeName in self._getImportantStrings()['imports']:
- ##if importeeName in namesSeen or parentContainsChild(importeeName, self._name):
- ## log.msg('Unnecessary or duplicate import line in %r: // import %s' % (self, importeeName))
- namesSeen.add(importeeName)
-
+ def _addImportee(importeeName):
importee = treeCache.get(importeeName)
if not importee:
importee = self._getScriptWithName(importeeName)
treeCache[importeeName] = importee
deps.append(importee)
- for requireeName in self._getImportantStrings()['requires']:
- who = self._directoryScan.whoProvide(requireeName)
- if who is None:
+ for importeeName in data['imports']:
+ ##if importeeName in namesSeen or parentContainsChild(importeeName, self._name):
+ ## log.msg('Unnecessary or duplicate import line in %r: // import %s' % (self, importeeName))
+ namesSeen.add(importeeName)
+ _addImportee(importeeName)
+
+ for requireeName in data['requires']:
+ importee = self._directoryScan.whoProvide(requireeName)
+ if importee is None:
raise NobodyProvidesThis("%r requires %r but nobody provides it." % (self, requireeName))
+ _addImportee(importee)
return deps
|
Don't implicitly import parents for Closure-style code
|
ludiosarchive_Coreweb
|
train
|
fb3f91c1413d7545e925fc9cc88e53149503c30b
|
diff --git a/client/v3/yaml/config_test.go b/client/v3/yaml/config_test.go
index <HASH>..<HASH> 100644
--- a/client/v3/yaml/config_test.go
+++ b/client/v3/yaml/config_test.go
@@ -98,6 +98,7 @@ func TestConfigFromFile(t *testing.T) {
continue
}
if cerr != nil {
+ os.Remove(tmpfile.Name())
continue
}
|
test: cleanup temporary file for TestConfigFromFile
|
etcd-io_etcd
|
train
|
51840c1baf837de147208abd67578cba60f4da00
|
diff --git a/src/bind.js b/src/bind.js
index <HASH>..<HASH> 100644
--- a/src/bind.js
+++ b/src/bind.js
@@ -11,6 +11,7 @@ var arity = require('./arity');
* @memberOf R
* @category Function
* @category Object
+ * @see R.partial
* @sig (* -> *) -> {*} -> (* -> *)
* @param {Function} fn The function to bind to context
* @param {Object} thisObj The context to bind `fn` to
|
refer to partial in bind docs
|
ramda_ramda
|
train
|
5293d40823891e56da3efea8e3ecf818dd3c181b
|
diff --git a/bottle_sqlalchemy.py b/bottle_sqlalchemy.py
index <HASH>..<HASH> 100644
--- a/bottle_sqlalchemy.py
+++ b/bottle_sqlalchemy.py
@@ -53,7 +53,6 @@ session.
'''
import bottle
-from bottle import HTTPError
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import SQLAlchemyError
@@ -130,7 +129,13 @@ class SQLAlchemyPlugin(object):
session.commit()
except SQLAlchemyError:
session.rollback()
- raise HTTPError(500, "Database Error", _e())
+ raise bottle.HTTPError(500, "Database Error", _e())
+ except bottle.HTTPError:
+ raise
+ except bottle.HTTPResponse:
+ if commit:
+ session.commit()
+ raise
finally:
session.close()
return rv
diff --git a/test.py b/test.py
index <HASH>..<HASH> 100644
--- a/test.py
+++ b/test.py
@@ -119,6 +119,30 @@ class SQLAlchemyPluginTest(unittest.TestCase):
session.commit()
self.assertEqual(session.query(Entity).count(), 1)
+ def test_commit_on_redirect(self):
+ @self.app.get('/')
+ def test(db):
+ entity = Entity()
+ db.add(entity)
+ self._db = db
+ bottle.redirect('/')
+
+ self._install_plugin(self.engine, Base.metadata, create=True)
+ self._request_path('/')
+ self.assertEqual(self._db.query(Entity).count(), 1)
+
+ def test_commit_on_abort(self):
+ @self.app.get('/')
+ def test(db):
+ entity = Entity()
+ db.add(entity)
+ self._db = db
+ bottle.abort()
+
+ self._install_plugin(self.engine, Base.metadata, create=True)
+ self._request_path('/')
+ self.assertEqual(self._db.query(Entity).count(), 0)
+
def _request_path(self, path, method='GET'):
self.app({'PATH_INFO': path, 'REQUEST_METHOD': method},
lambda x, y: None)
|
Handling Bottle exceptions to autocommit on redirect. Based in @defnull's solution to bottle-sqlite. bottlepy/bottle-extras@4e1a<I>af<I>b<I>dcd<I>d2fbd<I>bf<I>f<I>
|
iurisilvio_bottle-sqlalchemy
|
train
|
f9935fe234fd7860511f1124c6de79b02b44e686
|
diff --git a/ServerNode.js b/ServerNode.js
index <HASH>..<HASH> 100644
--- a/ServerNode.js
+++ b/ServerNode.js
@@ -134,6 +134,21 @@ ServerNode.prototype.configureHTTP = function (options) {
});
});
+ app.get('*', function(req, res){
+
+ var externalFilePath = __dirname.replace(/node\_modules.+/i, '') + 'games/' + req.url;
+
+ doesFileExists(externalFilePath, function(exists){
+ if(exists){
+ res.sendfile(externalFilePath);
+ } else {
+ var includedFilePath = __dirname + '/games/' + req.url;
+ res.sendfile(includedFilePath);
+ }
+ });
+
+ });
+
};
ServerNode.prototype.addChannel = function (options) {
|
added catch-all-handler for supporting games with a custom folder structure
|
nodeGame_nodegame-server
|
train
|
9df7d074f635192f4134218c4721cf244d1fa39b
|
diff --git a/pymatgen/analysis/structure_prediction/tests/test_volume_predictor.py b/pymatgen/analysis/structure_prediction/tests/test_volume_predictor.py
index <HASH>..<HASH> 100644
--- a/pymatgen/analysis/structure_prediction/tests/test_volume_predictor.py
+++ b/pymatgen/analysis/structure_prediction/tests/test_volume_predictor.py
@@ -100,11 +100,12 @@ class DLSVolumePredictorTest(PymatgenTest):
lfpo = PymatgenTest.get_structure("LiFePO4")
lfpo.scale_lattice(10.1)
self.assertAlmostEqual(p.predict(lfpo), 291.62094410192924)
- lfpo.scale_lattice(0.2)
- self.assertAlmostEqual(p.predict(lfpo), 291.62094410192924)
+ # lfpo.scale_lattice(0.2)
+ # self.assertAlmostEqual(p.predict(lfpo), 291.62094410192924)
lmpo = PymatgenTest.get_structure("LiFePO4")
lmpo.replace_species({"Fe": "Mn"})
self.assertAlmostEqual(p.predict(lmpo), 290.795329052)
+
if __name__ == '__main__':
unittest.main()
|
Speed up volume predictor DLS test. @computron - pls check why the
commented out two lines cause the tests to go from 1s to ><I>s to run.
|
materialsproject_pymatgen
|
train
|
4e97bfeb74c47548cd77b9f7daddc11ce1d5406c
|
diff --git a/lib/atomo/macros.rb b/lib/atomo/macros.rb
index <HASH>..<HASH> 100644
--- a/lib/atomo/macros.rb
+++ b/lib/atomo/macros.rb
@@ -7,6 +7,8 @@ module Atomo
end
def self.register_macro(name, args, body)
+ name = "atomo_macro::" + name
+
if ms = @macros[name]
ms << [[Patterns::Any.new, args], body.method(:bytecode)]
else
@@ -21,8 +23,8 @@ module Atomo
def self.expand(node)
case node
when AST::BinarySend
- if MacroEnvironment.respond_to?(node.operator)
- MacroEnvironment.send(node.operator.to_sym, node.lhs, node.rhs)
+ if MacroEnvironment.respond_to?("atomo_macro::" + node.operator)
+ MacroEnvironment.send("atomo_macro::" + node.operator.to_sym, node.lhs, node.rhs)
else
AST::BinarySend.new(
node.operator,
@@ -31,18 +33,20 @@ module Atomo
)
end
when AST::UnarySend
- if MacroEnvironment.respond_to?(node.method_name)
- MacroEnvironment.send(node.method_name.to_sym, node.receiver, *node.arguments)
+ if MacroEnvironment.respond_to?("atomo_macro::" + node.method_name)
+ MacroEnvironment.send("atomo_macro::" + node.method_name.to_sym, node.receiver, *node.arguments)
else
AST::UnarySend.new(
expand(node.receiver),
node.method_name,
- node.arguments.collect { |a| expand(a) }
+ node.arguments.collect { |a| expand(a) },
+ node.block,
+ node.private
)
end
when AST::KeywordSend
- if MacroEnvironment.respond_to?(node.method_name)
- MacroEnvironment.send(node.method_name.to_sym, node.receiver, *node.arguments)
+ if MacroEnvironment.respond_to?("atomo_macro::" + node.method_name)
+ MacroEnvironment.send("atomo_macro::" + node.method_name.to_sym, node.receiver, *node.arguments)
else
AST::KeywordSend.new(
expand(node.receiver),
|
sprinkle macro names with something to avoid collision
|
vito_atomy
|
train
|
cf01d91c94a37d5ad5a302c1ebdbf485283ae3c7
|
diff --git a/lib/config/WikiConfig.js b/lib/config/WikiConfig.js
index <HASH>..<HASH> 100644
--- a/lib/config/WikiConfig.js
+++ b/lib/config/WikiConfig.js
@@ -483,7 +483,11 @@ function WikiConfig(parsoidConfig, resultConf, prefix) {
while (chars.length < 4) {
chars = '0' + chars;
}
- return '\\u' + chars;
+ if (chars.length === 4) {
+ return '\\u' + chars;
+ } else {
+ return '\\u{' + chars + '}';
+ }
});
}
@@ -509,7 +513,7 @@ function WikiConfig(parsoidConfig, resultConf, prefix) {
}
try {
- return new RegExp(regexResult);
+ return new RegExp(regexResult, 'u');
} catch (e) {
console.error(e);
return null;
@@ -556,7 +560,7 @@ function WikiConfig(parsoidConfig, resultConf, prefix) {
// returns just the char class, for example 'a-z'.
try {
this.linkPrefixRegex = new RegExp(
- '[' + convertCodePoints(general.linkprefixcharset) + ']+$');
+ '[' + convertCodePoints(general.linkprefixcharset) + ']+$', 'u');
} catch (e) {
console.error(e);
this.linkPrefixRegex = null;
diff --git a/lib/html2wt/ConstrainedText.js b/lib/html2wt/ConstrainedText.js
index <HASH>..<HASH> 100644
--- a/lib/html2wt/ConstrainedText.js
+++ b/lib/html2wt/ConstrainedText.js
@@ -326,7 +326,7 @@ class WikiLinkText extends RegExpConstrainedText {
var noTrails = !/^mw:WikiLink(\/Interwiki)?$/.test(type);
var badPrefix = /(^|[^\[])(\[\[)*\[$/;
if (!noTrails && wikiConfig.linkPrefixRegex) {
- badPrefix = JSUtils.rejoin('(', wikiConfig.linkPrefixRegex, ')|(', badPrefix, ')');
+ badPrefix = JSUtils.rejoin('(', wikiConfig.linkPrefixRegex, ')|(', badPrefix, ')', { flags: 'u' });
}
super({
text: text,
diff --git a/tests/parserTests.txt b/tests/parserTests.txt
index <HASH>..<HASH> 100644
--- a/tests/parserTests.txt
+++ b/tests/parserTests.txt
@@ -27541,6 +27541,19 @@ parsoid=html2wt
</p>
!! end
+!! test
+Links 16. Link prefix using unicode \x{...} escapes (T235563)
+!! options
+language=ar
+!! wikitext
+Nominated–[[1923]]
+!! html/php
+<p><a href="/index.php?title=1923&action=edit&redlink=1" class="new" title="1923 (الصفحة غير موجودة)">Nominated–1923</a>
+</p>
+!! html/parsoid
+<p><a rel="mw:WikiLink" href="./1923" title="1923" data-parsoid='{"stx":"simple","a":{"href":"./1923"},"sa":{"href":"1923"},"prefix":"Nominated–"}'>Nominated–1923</a></p>
+!! end
+
#### --------------- Quotes ---------------
#### 1. Quotes inside <b> and <i>
#### 2. Link fragments separated by <i> and <b> tags
|
Handle unicode escapes higher than \uFFFF properly in link prefix/trail
This bug is only in Parsoid/JS, but worth fixing because it drives down
spurious HTML diffs with Parsoid/PHP.
Bug: T<I>
Change-Id: If7bdd7e3e<I>d9dfe4fdc<I>d<I>cdc<I>cc0f
|
wikimedia_parsoid
|
train
|
69e941b89715f48795d792b37638ae386e73c057
|
diff --git a/js/test/Exchange/test.fetchOHLCV.js b/js/test/Exchange/test.fetchOHLCV.js
index <HASH>..<HASH> 100644
--- a/js/test/Exchange/test.fetchOHLCV.js
+++ b/js/test/Exchange/test.fetchOHLCV.js
@@ -17,7 +17,6 @@ module.exports = async (exchange, symbol) => {
'btcalpha', // issue with 404 on a documented endpoint https://travis-ci.org/ccxt/ccxt/builds/643930431#L2213
'bitmex', // an issue with null values,to be resolved later
'cex',
- 'mandala',
]
if (skippedExchanges.includes (exchange.id)) {
diff --git a/js/test/Exchange/test.fetchOrders.js b/js/test/Exchange/test.fetchOrders.js
index <HASH>..<HASH> 100644
--- a/js/test/Exchange/test.fetchOrders.js
+++ b/js/test/Exchange/test.fetchOrders.js
@@ -14,7 +14,6 @@ const log = require ('ololog')
module.exports = async (exchange, symbol) => {
const skippedExchanges = [
- 'mandala',
'rightbtc',
]
diff --git a/js/test/Exchange/test.ticker.js b/js/test/Exchange/test.ticker.js
index <HASH>..<HASH> 100644
--- a/js/test/Exchange/test.ticker.js
+++ b/js/test/Exchange/test.ticker.js
@@ -76,7 +76,6 @@ module.exports = (exchange, ticker, method, symbol) => {
'xbtce',
'coss',
'idex',
- 'mandala',
'mercado',
'okex',
'southxchange', // https://user-images.githubusercontent.com/1294454/59953532-314bea80-9489-11e9-85b3-2a711ca49aa7.png
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -463,8 +463,6 @@
"Binance Jersey",
"bequant.io",
"Bequant",
- "mandalaex.com",
- "Mandala",
"dx.exchange",
"DX.Exchange",
"oceanex.pro.com",
|
js/test minor edits, package.json tags
|
ccxt_ccxt
|
train
|
baf0d941c9bf4cd4ea5c5a9a8ee0eb5adeef48ad
|
diff --git a/lib/art-decomp/logging.rb b/lib/art-decomp/logging.rb
index <HASH>..<HASH> 100644
--- a/lib/art-decomp/logging.rb
+++ b/lib/art-decomp/logging.rb
@@ -47,13 +47,6 @@ class << self
@log.info " U = #{point.args[1].sort.inspect}, V = #{point.args[2].sort.inspect}, Qu with #{point.sender.class.to_s.split('::').last}"
end
end
-
- QvGenerator.constants.map { |c| eval("QvGenerator::#{c}") }.each do |qv_gen|
- qv_gen.class_eval { include RCapture::Interceptable }
- qv_gen.capture_pre :methods => :blankets do |point|
- @log.debug " |Qu| = #{point.args[3].size}, Qv+G with #{point.sender.class.to_s.split('::').last}"
- end
- end
end
def off
diff --git a/spec/art-decomp/logging_spec.rb b/spec/art-decomp/logging_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/art-decomp/logging_spec.rb
+++ b/spec/art-decomp/logging_spec.rb
@@ -60,14 +60,4 @@ module ArtDecomp describe Logging do
log.should =~ rex('U = [1], V = [0], Qu with BlockTable')
end
- it 'should log QvGenerators’ blankets calls (on the DEBUG level)' do
- Logging.level = Logger::DEBUG
- qv = QvGenerator::GraphColouring.new
- [mock(Blanket, :size => 8), mock(Blanket, :size => 4)].each do |qu|
- qv.blankets @fsm, Set[0], Set[1], qu
- end
- log.should =~ rex('|Qu| = 8, Qv+G with GraphColouring')
- log.should =~ rex('|Qu| = 4, Qv+G with GraphColouring')
- end
-
end end
|
drop QvGenerator-level logging
|
chastell_art-decomp
|
train
|
712b23555e7961b4bf7fe230e27355941a622755
|
diff --git a/tests/Handlers/ExceptionHandlerTest.php b/tests/Handlers/ExceptionHandlerTest.php
index <HASH>..<HASH> 100644
--- a/tests/Handlers/ExceptionHandlerTest.php
+++ b/tests/Handlers/ExceptionHandlerTest.php
@@ -59,7 +59,7 @@ class ExceptionHandlerTest extends BaseRollbarTest
$setExceptionHandler = set_exception_handler(null);
- $setExceptionHandler(null);
+ call_user_func($setExceptionHandler, null);
}
/**
|
PHP <I> and lower doesn't support calling functions with a variable for a name; use call_user_function() instead
|
rollbar_rollbar-php
|
train
|
f5d91e8f9c4dcfa96b844a37cb449db7d4e1b3e2
|
diff --git a/pex/common.py b/pex/common.py
index <HASH>..<HASH> 100644
--- a/pex/common.py
+++ b/pex/common.py
@@ -308,26 +308,31 @@ def safe_sleep(seconds):
class AtomicDirectory(object):
def __init__(self, target_dir):
+ # type: (str) -> None
self._target_dir = target_dir
self._work_dir = "{}.{}".format(target_dir, uuid4().hex)
@property
def work_dir(self):
+ # type: () -> str
return self._work_dir
@property
def target_dir(self):
+ # type: () -> str
return self._target_dir
@property
def is_finalized(self):
+ # type: () -> bool
return os.path.exists(self._target_dir)
def finalize(self, source=None):
+ # type: (Optional[str]) -> None
"""Rename `work_dir` to `target_dir` using `os.rename()`.
- :param str source: An optional source offset into the `work_dir`` to use for the atomic
- update of `target_dir`. By default the whole `work_dir` is used.
+ :param source: An optional source offset into the `work_dir`` to use for the atomic update
+ of `target_dir`. By default the whole `work_dir` is used.
If a race is lost and `target_dir` already exists, the `target_dir` dir is left unchanged and
the `work_dir` directory will simply be removed.
@@ -354,6 +359,7 @@ class AtomicDirectory(object):
self.cleanup()
def cleanup(self):
+ # type: () -> None
safe_rmtree(self._work_dir)
|
Type AtomicDirectory. (#<I>)
|
pantsbuild_pex
|
train
|
c8cf41aab975cb1117938113d816519c6c3407c8
|
diff --git a/src/Validation.php b/src/Validation.php
index <HASH>..<HASH> 100644
--- a/src/Validation.php
+++ b/src/Validation.php
@@ -194,6 +194,22 @@ class Validation {
}
/**
+ * Get the error count, optionally for a particular field.
+ *
+ * @param string $field The name of a field or an empty string for all errors.
+ * @return int Returns the error count.
+ */
+ public function getErrorCount($field = '') {
+ if (empty($field)) {
+ return iterator_count($this->getRawErrors());
+ } elseif (empty($this->errors[$field])) {
+ return 0;
+ } else {
+ return count($this->errors[$field]);
+ }
+ }
+
+ /**
* Get the error message for an error row.
*
* @param array $error The error row.
diff --git a/src/ValidationField.php b/src/ValidationField.php
index <HASH>..<HASH> 100644
--- a/src/ValidationField.php
+++ b/src/ValidationField.php
@@ -166,4 +166,11 @@ class ValidationField {
public function val($key, $default = null) {
return isset($this->field[$key]) ? $this->field[$key] : $default;
}
+
+ /**
+ * Get the error count for this field.
+ */
+ public function getErrorCount() {
+ return $this->getValidation()->getErrorCount($this->getName());
+ }
}
|
Add error count methods to the Validation classes
|
vanilla_garden-schema
|
train
|
8272705fee0261880c849fab3603556f12c5636c
|
diff --git a/lib/Cake/Test/Case/TestSuite/CakeTestCaseTest.php b/lib/Cake/Test/Case/TestSuite/CakeTestCaseTest.php
index <HASH>..<HASH> 100644
--- a/lib/Cake/Test/Case/TestSuite/CakeTestCaseTest.php
+++ b/lib/Cake/Test/Case/TestSuite/CakeTestCaseTest.php
@@ -238,6 +238,6 @@ class CakeTestCaseTest extends CakeTestCase {
*/
public function testSetupBackUpValues() {
$this->assertArrayHasKey('debug', $this->_configure);
- $this->assertArrayHasKey('plugins', $this->_pathRestore);
+ $this->assertArrayHasKey('Plugin', $this->_pathRestore);
}
}
|
Fixing failing test from previous commit.
|
cakephp_cakephp
|
train
|
5ccc07af25d4e0c178f3ce7168d8626530fc08ba
|
diff --git a/src/debug/window_manager.js b/src/debug/window_manager.js
index <HASH>..<HASH> 100644
--- a/src/debug/window_manager.js
+++ b/src/debug/window_manager.js
@@ -162,6 +162,8 @@ window.launchDebugger = function() {
logger.info('Tungsten Debugger is enabled. Run "launchDebugger()" to enable.\nA button will need to be clicked to satisfy the user input requirement for window.open.');
+var MAX_POLLS = 60;
+var POLL_INTERVAL = 1000;
/**
* When the parent window unloads, the debug window polls to reattach
* Will auto-close if the parent window hasn't reappeared after 30s
@@ -169,12 +171,12 @@ logger.info('Tungsten Debugger is enabled. Run "launchDebugger()" to enable.\nA
function pollForParentOpen() {
/* jshint validthis:true */
if (this.pollNum > 0) {
- if (this.opener && typeof this.opener.attachTungstenDebugPane === 'function') {
+ if (this.opener && !this.opener.OLD_TUNGSTEN_MASTER && typeof this.opener.attachTungstenDebugPane === 'function') {
this.opener.attachTungstenDebugPane(this);
} else {
this.pollNum -= 1;
this.loadingCounter.textContent = '' + this.pollNum;
- this.setTimeout(pollForParentOpen, 1000);
+ this.setTimeout(pollForParentOpen, POLL_INTERVAL);
}
} else {
this.window.close();
@@ -185,9 +187,11 @@ function pollForParentOpen() {
utils.addEventListener(window, 'beforeunload', function() {
if (debugWindow) {
debugWindow.activeTab = _.keys(appData.tabs.selected)[0];
- debugWindow.pollNum = appData.loading = 30;
+ debugWindow.pollNum = appData.loading = MAX_POLLS;
renderDebugPanel();
debugWindow.loadingCounter = debugWindow.document.getElementById('loading_message_count');
- debugWindow.setTimeout(pollForParentOpen, 1000);
+ // Set variable to avoid reattaching to not-yet reloading window
+ window.OLD_TUNGSTEN_MASTER = true;
+ debugWindow.setTimeout(pollForParentOpen, POLL_INTERVAL);
}
});
|
Adjusting re-attach loop to accommodate slower reloads
|
wayfair_tungstenjs
|
train
|
41ecbc4f6572b235c6ef3ce6caf8b66daf18bf0d
|
diff --git a/js/src/jupyter-leaflet.js b/js/src/jupyter-leaflet.js
index <HASH>..<HASH> 100644
--- a/js/src/jupyter-leaflet.js
+++ b/js/src/jupyter-leaflet.js
@@ -4,7 +4,17 @@ var L = require('leaflet');
require('leaflet-draw');
require('leaflet.markercluster');
-L.Icon.Default.imagePath = __webpack_public_path__;
+// https://github.com/Leaflet/Leaflet/issues/4968
+// Marker file names are hard-coded in the leaflet source causing
+// issues with webpack.
+// This workaround allows webpack to inline all marker URLs.
+
+delete L.Icon.Default.prototype._getIconUrl;
+L.Icon.Default.mergeOptions({
+ iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
+ iconUrl: require('leaflet/dist/images/marker-icon.png'),
+ shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
+});
function camel_case(input) {
diff --git a/js/webpack.config.js b/js/webpack.config.js
index <HASH>..<HASH> 100644
--- a/js/webpack.config.js
+++ b/js/webpack.config.js
@@ -1,30 +1,15 @@
var path = require('path');
var version = require('./package.json').version;
-var leaflet_marker_selector = /leaflet\/dist\/images\/marker-.*\.png/;
-
var rules = [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
-
- // We exclude the default marker files, since their names are hardcoded in
- // the leaflet source.
{
test: /\.(jpg|png|gif|svg)$/,
- exclude: leaflet_marker_selector,
use: ['file-loader']
},
- {
- test: leaflet_marker_selector,
- use: [{
- loader: 'file-loader',
- options: {
- name: '[name].[ext]'
- }
- }]
- }
];
module.exports = [
|
workaround-webpack-marker
|
jupyter-widgets_ipyleaflet
|
train
|
ba0a44eef78a842bb9e1a6a6de39731c02f96a1f
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -48,7 +48,7 @@ setup(name='mtcnn',
author='Iván de Paz Centeno',
author_email='ipazc@unileon.es',
license='MIT',
- packages=setuptools.find_packages(),
+ packages=setuptools.find_packages(exclude=["tests.*", "tests"]),
install_requires=[
],
classifiers=[
@@ -66,4 +66,4 @@ setup(name='mtcnn',
tests_require=['nose'],
include_package_data=True,
keywords="mtcnn face detection tensorflow pip package",
- zip_safe=False)
\ No newline at end of file
+ zip_safe=False)
|
Excluded tests from package release. Fixes #2
|
ipazc_mtcnn
|
train
|
30e7e356363c1e6fe73db458366102d7af1c543c
|
diff --git a/kie-api/src/main/java/org/kie/api/runtime/process/ProcessWorkItemHandlerException.java b/kie-api/src/main/java/org/kie/api/runtime/process/ProcessWorkItemHandlerException.java
index <HASH>..<HASH> 100644
--- a/kie-api/src/main/java/org/kie/api/runtime/process/ProcessWorkItemHandlerException.java
+++ b/kie-api/src/main/java/org/kie/api/runtime/process/ProcessWorkItemHandlerException.java
@@ -20,7 +20,7 @@ public class ProcessWorkItemHandlerException extends RuntimeException {
private static final long serialVersionUID = 328927887939759492L;
- private static final int MAX_NUMBER_OF_RETRIES = 3;
+ private static final int MAX_NUMBER_OF_RETRIES = Integer.parseInt(System.getProperty("org.jbpm.exception.handling_strategy.retry.count", "3"));
public enum HandlingStrategy {
RETRY, COMPLETE, ABORT, RETHROW
}
|
[JBPM-<I>] Allow to define number of Retries for WIH exception handling strategy.
|
kiegroup_droolsjbpm-knowledge
|
train
|
6065f1051fb7d98dab38fcb513ffa288a48fe166
|
diff --git a/src/android/FirebasePluginMessagingService.java b/src/android/FirebasePluginMessagingService.java
index <HASH>..<HASH> 100755
--- a/src/android/FirebasePluginMessagingService.java
+++ b/src/android/FirebasePluginMessagingService.java
@@ -105,6 +105,7 @@ public class FirebasePluginMessagingService extends FirebaseMessagingService {
notificationManager.notify(id.hashCode(), notificationBuilder.build());
} else {
+ bundle.putBoolean("tap", false);
FirebasePlugin.sendNotification(bundle);
}
}
diff --git a/src/android/OnNotificationOpenReceiver.java b/src/android/OnNotificationOpenReceiver.java
index <HASH>..<HASH> 100644
--- a/src/android/OnNotificationOpenReceiver.java
+++ b/src/android/OnNotificationOpenReceiver.java
@@ -16,6 +16,7 @@ public class OnNotificationOpenReceiver extends BroadcastReceiver {
launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle data = intent.getExtras();
+ data.putBoolean("tap", true);
FirebasePlugin.sendNotification(data);
launchIntent.putExtras(data);
context.startActivity(launchIntent);
|
Add tap boolean to notification data
|
arnesson_cordova-plugin-firebase
|
train
|
194f142e616ab5dd6d13a687b96b9f8abd1b4ea8
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -10,7 +10,7 @@ from setuptools import setup
setup(
name='kanaconv',
- version='1.0.0',
+ version='1.0.1',
description=(
'Converts hiragana and katakana to rōmaji according to '
'Modified Hepburn transliteration rules'
|
Bump to <I> - Python 2 support fixed
|
msikma_kanaconv
|
train
|
854d2766669658f5c67a4f50b38d54dae6cd948d
|
diff --git a/bin/cucumis.js b/bin/cucumis.js
index <HASH>..<HASH> 100755
--- a/bin/cucumis.js
+++ b/bin/cucumis.js
@@ -214,7 +214,10 @@ function runFeature(featureFile, cb) {
if (ast[index].background) {
ast[index].background.background = true;
background = function(cb) {
- runScenario(ast[index].background, cb);
+ runScenario(ast[index].background, function () {
+ ast[index].background.backgroundPrinted = true;
+ cb();
+ });
}
}
@@ -230,15 +233,15 @@ function runFeature(featureFile, cb) {
var scenarios = feature.scenarios;
(function next(){
- background(function() {
if (scenarios.length) {
- runScenario(scenarios.shift(), function() {
- notifyListeners('afterFeature', next);
+ background(function() {
+ runScenario(scenarios.shift(), function() {
+ notifyListeners('afterFeature', next);
+ });
});
} else {
cb();
}
- });
})();
}
});
@@ -256,15 +259,17 @@ function runScenario(scenario, cb) {
skip: false,
};
- if (scenario.background && !scenario.backgroundPrinted) {
- console.log(indent('Background:', 1));
- scenario.backgroundPrinted = true;
+ var notifyEventType = 'Scenario';
+ if (scenario.background) {
+ if (!scenario.backgroundPrinted) {
+ console.log(indent('Background:', 1));
+ }
+ notifyEventType = 'Background';
} else {
console.log(indent('Scenario' + (scenario.outline ? ' Outline' : '') + ': ' + scenario.name, 1));
}
-
- notifyListeners('beforeScenario', function() {
+ notifyListeners('before' + notifyEventType, function() {
if (scenario.breakdown && scenario.breakdown.length) {
testState.lastStepType = 'GIVEN';
@@ -310,7 +315,7 @@ function runScenario(scenario, cb) {
}
}
- notifyListeners('afterScenario', cb);
+ notifyListeners('after' + notifyEventType, cb);
}
})();
}
@@ -332,18 +337,20 @@ function runExampleSet(scenario, exampleSet, testState, cb) {
if (steps.length) {
stepCount++;
notifyListeners('beforeStep', function() {
- runStep(steps.shift(), exampleSet, testState, function() {
+ runStep(scenario, steps.shift(), exampleSet, testState, function() {
notifyListeners('afterStep', next);
});
});
} else {
- console.log('');
+ if (!scenario.background || (scenario.background && !scenario.backgroundPrinted)) {
+ console.log('');
+ }
cb();
}
})();
}
-function runStep(step, exampleSet, testState, cb) {
+function runStep(scenario, step, exampleSet, testState, cb) {
var stepType = step[0];
if (step[0] == 'AND') {
stepType = testState.lastStepType;
@@ -398,7 +405,10 @@ function runStep(step, exampleSet, testState, cb) {
undefinedSteps[snippet] = true;
}
- console.log(indent(colorize(testState.color, stepLine), 2));
+ if (!scenario.background || (scenario.background && !scenario.backgroundPrinted)) {
+ console.log(indent(colorize(testState.color, stepLine), 2));
+ }
+
if (testState.msg) {
console.log(indent(testState.msg, 3));
}
diff --git a/features/step_definitions/google.js b/features/step_definitions/google.js
index <HASH>..<HASH> 100644
--- a/features/step_definitions/google.js
+++ b/features/step_definitions/google.js
@@ -46,7 +46,13 @@ Steps.Given(/^I am using the "([^"]*)" browser$/, function (ctx, bt) {
, browser: browserType
});
- ctx.done();
+ browser
+ .chain
+ .session()
+ .end(function(err) {
+ if (err) throw err;
+ ctx.done();
+ });
});
Steps.Given(/^I am on the "([^"]*?)" "([^"]*?)" page$/, function (ctx, site, page) {
@@ -55,9 +61,9 @@ Steps.Given(/^I am on the "([^"]*?)" "([^"]*?)" page$/, function (ctx, site, pag
browser
.chain
- .session()
.open(url)
.end(function(err) {
+ if (err) throw err;
ctx.done();
});
});
@@ -67,6 +73,7 @@ Steps.When(/^I enter "([^"]*?)" into the "([^"]*?)" text field$/, function (ctx,
.chain
.type(fieldMap[lastSite][field], text)
.end(function(err) {
+ if (err) throw err;
ctx.done();
});
});
@@ -78,6 +85,7 @@ Steps.When(/^I click the "([^"]*?)" "([^"]*?)" button$/, function (ctx, site, fi
.click(fieldMap[site][field])
.waitForPageToLoad(2000)
.end(function(err) {
+ if (err) throw err;
ctx.done();
});
});
|
Stopped backgrounds running twice, and also fixed background printing
|
noblesamurai_cucumis
|
train
|
f53685ef760d69d07e653aba30ffbde7b0a1bcaf
|
diff --git a/service_sysv_linux.go b/service_sysv_linux.go
index <HASH>..<HASH> 100644
--- a/service_sysv_linux.go
+++ b/service_sysv_linux.go
@@ -205,7 +205,7 @@ case "$1" in
if is_running; then
echo -n "Stopping $name.."
kill $(get_pid)
- for i in {1..10}
+ for i in $(seq 1 10)
do
if ! is_running; then
break
|
For does not work on dash
IN case of dash(for example default on wheezy) for operator shold be reworked
|
kardianos_service
|
train
|
ef537940a6e177c523aaacfa8bdf7300d00f490b
|
diff --git a/collections_extended/setlists.py b/collections_extended/setlists.py
index <HASH>..<HASH> 100644
--- a/collections_extended/setlists.py
+++ b/collections_extended/setlists.py
@@ -226,7 +226,7 @@ class setlist(_basesetlist, MutableSequence, MutableSet):
ValueError: If value alread in self
"""
if value in self:
- raise ValueError
+ raise ValueError('Value "%s" already present' % value)
else:
# Do this first in case value isn't Hashable
self._dict[value] = len(self) + 1
@@ -243,10 +243,16 @@ class setlist(_basesetlist, MutableSequence, MutableSet):
Raises:
ValueError: If any values are already present
"""
- if not self.isdisjoint(values):
- raise ValueError
+ new_setlist = setlist()
for value in values:
- self.append(value)
+ try:
+ new_setlist.append(value)
+ except ValueError:
+ raise ValueError('New values contain duplicates')
+ if not self.isdisjoint(new_setlist):
+ raise ValueError
+ self._list.extend(new_setlist._list)
+ self._dict.update(new_setlist._dict)
def update(self, values):
"""Add all values to the end.
|
Fix #<I> - extend is atomic when extending with duplicate values.
|
mlenzen_collections-extended
|
train
|
c8514e1d541319994c8da558ade43ce25e9be7b9
|
diff --git a/IP2Location.py b/IP2Location.py
index <HASH>..<HASH> 100644
--- a/IP2Location.py
+++ b/IP2Location.py
@@ -94,8 +94,19 @@ class IP2Location(object):
if filename:
self.open(filename)
+ def __enter__(self):
+ if not hasattr(self, '_f') or self._f.closed:
+ raise ValueError("Cannot enter context with closed file")
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.close()
+
def open(self, filename):
''' Opens a database file '''
+ # Ensure old file is closed before oppening a new one
+ self.close()
+
self._f = open(filename, 'rb')
self._dbtype = struct.unpack('B', self._f.read(1))[0]
self._dbcolumn = struct.unpack('B', self._f.read(1))[0]
@@ -107,6 +118,12 @@ class IP2Location(object):
self._ipv6dbcount = struct.unpack('<I', self._f.read(4))[0]
self._ipv6dbaddr = struct.unpack('<I', self._f.read(4))[0]
+ def close(self):
+ if hasattr(self, '_f'):
+ # If there is file close it.
+ self._f.close()
+ del self._f
+
def get_country_short(self, ip):
''' Get country_short '''
rec = self.get_all(ip)
diff --git a/test.py b/test.py
index <HASH>..<HASH> 100644
--- a/test.py
+++ b/test.py
@@ -13,6 +13,7 @@
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; If not, see <http://www.gnu.org/licenses/>.
+from __future__ import with_statement
import os
import sys
@@ -52,5 +53,36 @@ for line in open(os.path.join("data", "country_test_ipv6_data.txt")):
else:
passed += 1
+test_num += 1
+try:
+ database.close()
+except:
+ failed += 1
+ print("Test DB closing (Test %d) failed." % (test_num))
+else:
+ passed += 1
+
+test_num += 1
+try:
+ with database:
+ pass
+except ValueError:
+ passed += 1
+else:
+ failed += 1
+ print("Test 'with' statement with closed db failed (Test %d)" % (test_num))
+
+
+test_num += 1
+try:
+ with IP2Location.IP2Location(os.path.join("data", "IP-COUNTRY.BIN")) as db:
+ rec = db.get_all('19.5.10.1')
+except:
+ failed += 1
+ print("Test With statement failed (Test %d)" % (test_num))
+ raise
+else:
+ passed += 1
+
print('PASS: %d' % (passed))
print('FAIL: %d' % (failed))
|
IP2Location object can be closed and can be used as Context Manager
|
chrislim2888_IP2Location-Python
|
train
|
c3722038d3c4054ed48df84936377079c4302868
|
diff --git a/collection.go b/collection.go
index <HASH>..<HASH> 100644
--- a/collection.go
+++ b/collection.go
@@ -13,6 +13,7 @@ package moss
import (
"fmt"
+ "sort"
)
// Start kicks off required background gouroutines.
@@ -77,7 +78,7 @@ func (m *collection) ExecuteBatch(bIn Batch) error {
maxStackOpenHeight = DefaultCollectionOptions.MaxStackOpenHeight
}
- bsorted := b.sort()
+ sort.Sort(b)
stackOpen := &segmentStack{collection: m}
@@ -98,7 +99,7 @@ func (m *collection) ExecuteBatch(bIn Batch) error {
stackOpen.a = append(stackOpen.a, m.stackOpen.a...)
}
- stackOpen.a = append(stackOpen.a, bsorted)
+ stackOpen.a = append(stackOpen.a, b)
m.stackOpen = stackOpen
@@ -111,7 +112,7 @@ func (m *collection) ExecuteBatch(bIn Batch) error {
close(awakeMergerCh)
}
- return b.Close()
+ return nil
}
// ------------------------------------------------------
diff --git a/moss_test.go b/moss_test.go
index <HASH>..<HASH> 100644
--- a/moss_test.go
+++ b/moss_test.go
@@ -14,6 +14,7 @@ package moss
import (
"fmt"
"reflect"
+ "sort"
"strings"
"sync"
"testing"
@@ -201,7 +202,9 @@ func TestBatchSort(t *testing.T) {
t.Errorf("wrong okv")
}
- b2 := b.sort()
+ sort.Sort(b)
+
+ b2 := b
o, k, v = b2.getOperationKeyVal(0)
if o != OperationSet || string(k) != "b" || string(v) != "B" {
diff --git a/segment.go b/segment.go
index <HASH>..<HASH> 100644
--- a/segment.go
+++ b/segment.go
@@ -27,8 +27,6 @@ func newSegment(totalOps, totalKeyValBytes int) (
// Close releases resources associated with the segment.
func (a *segment) Close() error {
- a.kvs = nil
- a.buf = nil
return nil
}
@@ -148,18 +146,6 @@ func (a *segment) mutateEx(operation uint64,
// ------------------------------------------------------
-// sort() returns a new, sorted segment from a given segment, where
-// the underlying buf bytes might be shared.
-func (b *segment) sort() *segment {
- rv := *b // Copy fields.
-
- rv.kvs = append([]uint64(nil), b.kvs...)
-
- sort.Sort(&rv)
-
- return &rv
-}
-
func (a *segment) Len() int {
return len(a.kvs) / 2
}
|
in-place sort for ExecuteBatch instead of sorted copy
|
couchbase_moss
|
train
|
f8ead09fccd5eb0e8dedd01c305917ccffcc6569
|
diff --git a/Form/Type/PortfolioType.php b/Form/Type/PortfolioType.php
index <HASH>..<HASH> 100644
--- a/Form/Type/PortfolioType.php
+++ b/Form/Type/PortfolioType.php
@@ -4,6 +4,7 @@ namespace Icap\PortfolioBundle\Form\Type;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\Form\AbstractType;
+use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
@@ -23,6 +24,9 @@ class PortfolioType extends AbstractType
'allow_delete' => true
)
)
+ ->add('commentsViewAt', 'datetime', array(
+ 'widget' => 'single_text'
+ ))
->add('widgets', 'text', array('mapped' => false));
}
@@ -38,6 +42,7 @@ class PortfolioType extends AbstractType
'data_class' => 'Icap\PortfolioBundle\Entity\Portfolio',
'translation_domain' => 'icap_portfolio',
'csrf_protection' => false,
+ 'date_format' => DateTimeType::HTML5_FORMAT
)
);
}
diff --git a/Manager/PortfolioManager.php b/Manager/PortfolioManager.php
index <HASH>..<HASH> 100644
--- a/Manager/PortfolioManager.php
+++ b/Manager/PortfolioManager.php
@@ -18,6 +18,7 @@ use Icap\PortfolioBundle\Event\Log\PortfolioAddViewerEvent;
use Icap\PortfolioBundle\Event\Log\PortfolioRemoveGuideEvent;
use JMS\DiExtraBundle\Annotation as DI;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
+use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\FormFactory;
/**
@@ -250,6 +251,7 @@ class PortfolioManager
}
$data['comments'] = $commentsDatas;
$data['unreadComments'] = $portfolio->getCountUnreadComments();
+ $data['commentsViewAt'] = $portfolio->getCommentsViewAt()->format(DATE_W3C);
return $data;
}
diff --git a/Resources/public/js/controllers/commentController.js b/Resources/public/js/controllers/commentController.js
index <HASH>..<HASH> 100644
--- a/Resources/public/js/controllers/commentController.js
+++ b/Resources/public/js/controllers/commentController.js
@@ -13,4 +13,10 @@ portfolioApp
this.message = '';
}
};
+
+ $scope.updateCountViewComments = function () {
+ portfolioManager.portfolio.commentsViewAt = new Date();
+ portfolioManager.save(portfolioManager.portfolio);
+ $scope.displayComment= !$scope.displayComment;
+ }
}]);
\ No newline at end of file
diff --git a/Resources/views/Portfolio/view.html.twig b/Resources/views/Portfolio/view.html.twig
index <HASH>..<HASH> 100644
--- a/Resources/views/Portfolio/view.html.twig
+++ b/Resources/views/Portfolio/view.html.twig
@@ -87,7 +87,7 @@
<section class="col-md-12">
{% if not viewMode %}
<div class="communication_panel_toggle" data-ng-init="displayComment=false">
- <button class="btn btn-default btn-sm pull-right"data-ng-click="displayComment=!displayComment">
+ <button class="btn btn-default btn-sm pull-right" data-ng-click="updateCountViewComments()">
{{ 'communication_panel' | trans({}, 'icap_portfolio') }} <span class="badge">{% verbatim %}{{ portfolio.unreadComments }}{% endverbatim %}</span> <span class="fa fa-chevron-right"></span>
</button>
</div>
|
[PortfolioBundle] Update comments view date on portfolio when displaying comments on it
|
claroline_Distribution
|
train
|
cd76bd00fa208b6b2e43ec9a975b1d9ef931c6f1
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -15,17 +15,24 @@ setup(
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
- "Topic :: Software Development :: Compilers",
+ 'Topic :: Software Development :: Compilers',
'Operating System :: MacOS :: MacOS X',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Programming Language :: Python',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.2',
+ 'Programming Language :: Python :: 3.3',
+ 'Programming Language :: Python :: 3.4',
+ 'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
- "License :: OSI Approved :: MIT License",
+ 'Programming Language :: Python :: 3.10',
+ 'License :: OSI Approved :: MIT License',
],
platforms = 'any',
keywords = 'monad parser combinator',
|
Bump up the version to <I>.
|
sighingnow_parsec.py
|
train
|
d015f7c5f471e9909e1e067fe30d2dd8708d2fea
|
diff --git a/lib/arproxy/config.rb b/lib/arproxy/config.rb
index <HASH>..<HASH> 100644
--- a/lib/arproxy/config.rb
+++ b/lib/arproxy/config.rb
@@ -28,6 +28,9 @@ module Arproxy
case @adapter
when String, Symbol
camelized_adapter_name = @adapter.to_s.split("_").map(&:capitalize).join
+ if camelized_adapter_name == "Sqlite3"
+ camelized_adapter_name = "SQLite3"
+ end
eval "::ActiveRecord::ConnectionAdapters::#{camelized_adapter_name}Adapter"
when Class
@adapter
|
Handle the case when adapter is configured as 'sqlite3'
|
cookpad_arproxy
|
train
|
09d849d9944f9098bb00fd665a0d284a0c6e1412
|
diff --git a/mozilla/gcli/settings.js b/mozilla/gcli/settings.js
index <HASH>..<HASH> 100644
--- a/mozilla/gcli/settings.js
+++ b/mozilla/gcli/settings.js
@@ -29,8 +29,7 @@ var types = require('gcli/types');
var allSettings = [];
/**
- * No setup required because settings are pre-loaded with Mozilla,
- * but match API with main settings.js
+ * Cache existing settings on startup
*/
exports.startup = function() {
imports.prefBranch.getChildList('').forEach(function(name) {
@@ -114,9 +113,8 @@ Object.defineProperty(Setting.prototype, 'value', {
case imports.prefBranch.PREF_STRING:
var value = imports.prefBranch.getComplexValue(this.name,
Components.interfaces.nsISupportsString).data;
- // Try in case it's a localized string (will throw an exception if not)
- var isL10n = /^chrome:\/\/.+\/locale\/.+\.properties/.test(value);
- if (!this.changed && isL10n) {
+ // In case of a localized string
+ if (/^chrome:\/\/.+\/locale\/.+\.properties/.test(value)) {
value = imports.prefBranch.getComplexValue(this.name,
Components.interfaces.nsIPrefLocalizedString).data;
}
|
Bug <I> (pref): Tidy-up
this.changed isn't used/defined/referenced anywhere else. Remove it.
Doc comment was wrong.
|
joewalker_gcli
|
train
|
2ffbd662213865dde863094bb088259c85ecce6a
|
diff --git a/client/html/templates/catalog/filter/tree-partial-standard.php b/client/html/templates/catalog/filter/tree-partial-standard.php
index <HASH>..<HASH> 100644
--- a/client/html/templates/catalog/filter/tree-partial-standard.php
+++ b/client/html/templates/catalog/filter/tree-partial-standard.php
@@ -102,11 +102,11 @@ $config = $this->config( 'client/html/catalog/tree/url/config', [] );
<?php foreach( $this->get( 'nodes', [] ) as $item ) : ?>
<?php if( $item->getStatus() > 0 ) : ?>
- <div class="cat-item catid-<?= $enc->attr( $item->getId()
- . ( $item->getLevel() == 1 ? ' top-item' : '' )
- . ( $item->hasChildren() ? ' has-submenu withchild' : ' nochild' )
- . ( $this->get( 'path', map() )->getId()->last() == $item->getId() ? ' active' : '' )
- . ' catcode-' . $item->getCode() . ' ' . $item->getConfigValue( 'css-class' ) ) ?>"
+ <div class="cat-item catid-<?= $enc->attr( $item->getId() .
+ ( $item->getLevel() == 1 ? ' top-item' : '' ) .
+ ( $item->hasChildren() ? ' has-submenu withchild' : ' nochild' ) .
+ ( $this->get( 'path', map() )->has( $item->getId() ) ? ' active' : '' ) .
+ ' catcode-' . $item->getCode() . ' ' . $item->getConfigValue( 'css-class' ) ) ?>"
data-id="<?= $item->getId() ?>">
<?php if( $item->hasChildren() ) : ?>
@@ -124,9 +124,8 @@ $config = $this->config( 'client/html/catalog/tree/url/config', [] );
</div>
<?php endif ?>
- <a class="cat-item <?=
- ( $item->getLevel() == 1 ? 'top-cat-item ' : '' ) .
- ( $this->get( 'path', map() )->getId()->last() == $item->getId() ? 'active' : '' ) ?>"
+ <a class="cat-item <?= ( $item->getLevel() == 1 ? 'top-cat-item' : '' ) .
+ ( $this->get( 'path', map() )->has( $item->getId() ) ? ' active' : '' ) ?>"
href="<?= $enc->attr( $this->url( $item->getTarget() ?: $target, $controller, $action, array_merge( $this->get( 'params', [] ), ['f_name' => $item->getName( 'url' ), 'f_catid' => $item->getId()] ), [], $config ) ) ?>"><!--
--><div class="media-list"><!--
<?php foreach( $item->getRefItems( 'media', 'icon', 'default' ) as $mediaItem ) : ?>
@@ -142,8 +141,8 @@ $config = $this->config( 'client/html/catalog/tree/url/config', [] );
<?php if( count( $item->getChildren() ) > 0 ) : ?>
<div id="<?= $enc->attr( $item->getId() ) ?>" class="submenu <?= $enc->attr(
- ( $item->hasChildren() ? ' shadow-sm' : ' nochild' )
- . ( $this->get( 'path', map() )->getId()->last() == $item->getId() ? ' active' : '' ) ) ?>"
+ ( $this->get( 'path', map() )->has( $item->getId() ) ? ' active opened' : '' ) ) .
+ ( $item->hasChildren() ? ' shadow-sm' : ' nochild' ) ?>"
data-id="<?= $item->getId() ?>">
<div class="submenu-header row">
diff --git a/client/html/themes/default/aimeos.js b/client/html/themes/default/aimeos.js
index <HASH>..<HASH> 100644
--- a/client/html/themes/default/aimeos.js
+++ b/client/html/themes/default/aimeos.js
@@ -2434,17 +2434,3 @@ jQuery(function() {
Aimeos.loadImages();
});
-
-
-
-jQuery(function() {
-
- /**
- * Sets active classes in Menu
- */
- $('.category-lists').find('.active').each(function() {
- var $this = $(this);
- $this.parents(".submenu").addClass('opened');
- $this.parents('.cat-item').add(this).addClass('active');
- });
-});
\ No newline at end of file
|
Don't set category active state via JS
|
aimeos_ai-client-html
|
train
|
81d39e1b52087555fab8411c9757607b2a2e650c
|
diff --git a/src/Client/HttpClientFactory.php b/src/Client/HttpClientFactory.php
index <HASH>..<HASH> 100644
--- a/src/Client/HttpClientFactory.php
+++ b/src/Client/HttpClientFactory.php
@@ -27,6 +27,6 @@ class HttpClientFactory
{
return $this->options->isSimpleClientType()
? new SimpleHttpClient()
- : (new ComplexHttpClient($this->options))->getClient();
+ : (new ComplexHttpClient($this->options));
}
}
\ No newline at end of file
|
Removed calling the getClient method
|
g4code_gateway
|
train
|
b2c6a2e38133bde59fb657d1c367c42cc48353dd
|
diff --git a/code/model/entity/abstract.php b/code/model/entity/abstract.php
index <HASH>..<HASH> 100644
--- a/code/model/entity/abstract.php
+++ b/code/model/entity/abstract.php
@@ -152,6 +152,30 @@ abstract class KModelEntityAbstract extends KObjectArray implements KModelEntity
}
/**
+ * Mixin an object
+ *
+ * Reset the computed_properties after a behavior has been mixed that has mixable methods
+ *
+ * @param mixed $identifier An ObjectIdentifier, identifier string or object implementing ObjectMixableInterface
+ * @param array $config An optional associative array of configuration options
+ * @return KObjectMixinInterface
+ * @throws KObjectExceptionInvalidIdentifier If the identifier is not valid
+ * @throws \UnexpectedValueException If the mixin does not implement the ObjectMixinInterface
+ */
+ public function mixin($mixin, $config = array())
+ {
+ $mixin = parent::mixin($mixin, $config);
+
+ //Reset the computed properties array
+ $methods = $mixin->getMixableMethods();
+ if(!empty($methods)) {
+ $this->__computed_properties = null;
+ }
+
+ return $mixin;
+ }
+
+ /**
* Gets the identity key
*
* @return string
|
re #<I> - Reset mixed methods on mixin.
|
timble_kodekit
|
train
|
1334201903410dda24f2ad3f50bac56f8f4563c2
|
diff --git a/src/processor/market.js b/src/processor/market.js
index <HASH>..<HASH> 100644
--- a/src/processor/market.js
+++ b/src/processor/market.js
@@ -296,12 +296,12 @@ module.exports.execute = function(market, gameTime, terminals, bulkObjects) {
return;
}
- var dealCost = utils.roundCredits(Math.ceil(amount * order.price * 100) / 100);
+ var dealCost = utils.roundCredits(amount * order.price);
if(buyer.user) {
dealCost = Math.min(dealCost, usersById[buyer.user].money || 0);
amount = Math.floor(dealCost/order.price);
- dealCost = utils.roundCredits(Math.ceil(amount * order.price * 100) / 100);
+ dealCost = utils.roundCredits(amount * order.price);
if(!amount) {
return;
}
|
fix(processor): small fixes in market cost rounding logic
|
screeps_engine
|
train
|
8199764018b24dd146bca7d3da54b514dbd3cb7b
|
diff --git a/tests/src/main/java/com/hazelcast/simulator/tests/external/ExternalClientTest.java b/tests/src/main/java/com/hazelcast/simulator/tests/external/ExternalClientTest.java
index <HASH>..<HASH> 100644
--- a/tests/src/main/java/com/hazelcast/simulator/tests/external/ExternalClientTest.java
+++ b/tests/src/main/java/com/hazelcast/simulator/tests/external/ExternalClientTest.java
@@ -14,6 +14,7 @@ import com.hazelcast.util.EmptyStatement;
import java.util.concurrent.TimeUnit;
+import static com.hazelcast.simulator.tests.helpers.HazelcastTestUtils.isMemberNode;
import static java.lang.String.format;
public class ExternalClientTest {
@@ -38,6 +39,10 @@ public class ExternalClientTest {
this.testContext = testContext;
hazelcastInstance = testContext.getTargetInstance();
+ if (isMemberNode(hazelcastInstance)) {
+ return;
+ }
+
clientsRunning = hazelcastInstance.getCountDownLatch(basename);
clientsRunning.trySetCount(waitForClientsCount);
@@ -52,6 +57,10 @@ public class ExternalClientTest {
@Run
public void run() {
+ if (isMemberNode(hazelcastInstance)) {
+ return;
+ }
+
// wait for external clients to finish
while (true) {
try {
|
Fixed that member node can grab responsibility to collect external client results.
|
hazelcast_hazelcast-simulator
|
train
|
982264279db4d2fb23193851332845c2067ac1c6
|
diff --git a/post_office/__init__.py b/post_office/__init__.py
index <HASH>..<HASH> 100644
--- a/post_office/__init__.py
+++ b/post_office/__init__.py
@@ -1,4 +1,4 @@
-VERSION = (0, 7, 0)
+VERSION = (0, 7, 1)
from .backends import EmailBackend
from .models import PRIORITY
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ from setuptools import setup
setup(
name='django-post_office',
- version='0.7.0',
+ version='0.7.1',
author='Selwin Ong',
author_email='selwin.ong@gmail.com',
packages=['post_office'],
|
Bumped version to <I>.
|
ui_django-post_office
|
train
|
377be75dd0ec6246ba63aaf8552abb455aca0f9c
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -12,7 +12,7 @@ install_requires = [
"future>=0.16.0",
"colorama>=0.3.9",
"configobj>=5.0.6",
- "networkx==2.1",
+ "networkx>=2.1",
"pyyaml>=3.12",
"gitpython>=2.1.8",
"ntfsutils>=0.1.4",
|
Update networkx package in setup.py
|
iterative_dvc
|
train
|
88799fbe93f96a9a3afa169e9c1c12b2b6a66e27
|
diff --git a/pytplot/tplot.py b/pytplot/tplot.py
index <HASH>..<HASH> 100644
--- a/pytplot/tplot.py
+++ b/pytplot/tplot.py
@@ -11,7 +11,7 @@ from bokeh.models import (CustomJS, Label, LogColorMapper, LogTicker, ColorBar,
Range1d, Span, Title, Legend, LogAxis)
from bokeh.models.glyphs import Line
from bokeh.models.tools import BoxZoomTool
-from bokeh.models.formatters import NumeralTickFormatter
+from bokeh.models.formatters import BasicTickFormatter
from . import tplot_common
from .timestamp import TimeStamp
@@ -480,7 +480,7 @@ def specplot(name, num_plots, last_plot=False, height=200, width=800, var_label=
color_mapper=LogColorMapper(palette=rainbow_colormap, low=zmin, high=zmax)
color_bar=ColorBarSideTitle(color_mapper=color_mapper, ticker=LogTicker(), border_line_color=None, location=(0,0))
color_bar.width=10
- color_bar.formatter = NumeralTickFormatter(format="0,0")
+ color_bar.formatter = BasicTickFormatter(precision=1)
color_bar.major_label_text_align = 'left'
color_bar.label_standoff = 5
color_bar.major_label_text_baseline = 'middle'
|
Changing colorbar tick formatter to exponential
|
MAVENSDC_PyTplot
|
train
|
9869f8b8cc8e4f4f62cb2ea5276a45ba790366b4
|
diff --git a/src/javascript/runtime/html4/xhr/XMLHttpRequest.js b/src/javascript/runtime/html4/xhr/XMLHttpRequest.js
index <HASH>..<HASH> 100644
--- a/src/javascript/runtime/html4/xhr/XMLHttpRequest.js
+++ b/src/javascript/runtime/html4/xhr/XMLHttpRequest.js
@@ -104,7 +104,7 @@ define("moxie/runtime/html4/xhr/XMLHttpRequest", [
el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document;
// try to detect some standard error pages
- if (/^4\d{2}\s/.test(el.title) && el.getElementsByTagName('address').length) { // standard Apache style
+ if (/^4(0[0-9]|1[0-7]|2[2346])\s/.test(el.title)) { // test if title starts with 4xx HTTP error
_status = el.title.replace(/^(\d+).*$/, '$1');
} else {
_status = 200;
|
XHR, HTML4: Detect 4xx HTTP error by the title.
|
moxiecode_moxie
|
train
|
9257e9ba1640c9a7c1de883a0eb8910e422df912
|
diff --git a/pgmpy/factors/CPD.py b/pgmpy/factors/CPD.py
index <HASH>..<HASH> 100644
--- a/pgmpy/factors/CPD.py
+++ b/pgmpy/factors/CPD.py
@@ -136,9 +136,6 @@ class TabularCPD(Factor):
return self.values.reshape(1, np.prod(self.cardinality))
def __str__(self):
- return self._str(html=False)
-
- def _str(self, html=False):
table_list = []
indexes = np.array(list(product(*[range(i) for i in self.cardinality[1:]])))
scope = self.scope()
@@ -147,7 +144,7 @@ class TabularCPD(Factor):
row.extend(np.array(self.variables[row[0]])[indexes[:, i-1]].tolist())
table_list.append(row)
table_list.extend(np.column_stack((np.array(self.variables[self.variable]), self.get_cpd())))
- return tabulate(table_list, tablefmt="grid")
+ return tabulate(table_list, tablefmt="fancy_grid")
def _repr_html_(self):
"""
|
Cleanups in __str__ method in TabularCPD.
|
pgmpy_pgmpy
|
train
|
cace39af972a595064250a22a6a6feebc89113be
|
diff --git a/src/transformers/__init__.py b/src/transformers/__init__.py
index <HASH>..<HASH> 100755
--- a/src/transformers/__init__.py
+++ b/src/transformers/__init__.py
@@ -651,6 +651,7 @@ if is_tf_available():
TF_MODEL_FOR_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_MASKED_LM_MAPPING,
TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
+ TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING,
TF_MODEL_FOR_PRETRAINING_MAPPING,
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
diff --git a/src/transformers/utils/dummy_tf_objects.py b/src/transformers/utils/dummy_tf_objects.py
index <HASH>..<HASH> 100644
--- a/src/transformers/utils/dummy_tf_objects.py
+++ b/src/transformers/utils/dummy_tf_objects.py
@@ -101,6 +101,9 @@ TF_MODEL_FOR_MASKED_LM_MAPPING = None
TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING = None
+TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = None
+
+
TF_MODEL_FOR_PRETRAINING_MAPPING = None
|
Add missing import (#<I>)
* Add missing import
* Fix dummy objects
|
huggingface_pytorch-pretrained-BERT
|
train
|
fe59df23baa55af84ab1a606c4aee044966098bb
|
diff --git a/tests/web/filter.py b/tests/web/filter.py
index <HASH>..<HASH> 100644
--- a/tests/web/filter.py
+++ b/tests/web/filter.py
@@ -61,7 +61,7 @@ class Prefix(unittest.TestCase):
'''Prefix root'''
def handler(r):
- self.assertEqual(r.request.path, '/')
+ self.assertEqual(r.request.prefixed_path, '/')
app = Map(
match('/', 'index') | handler,
@@ -89,7 +89,7 @@ class Prefix(unittest.TestCase):
'''Simple prefix'''
def handler(r):
- self.assertEqual(r.request.path, '/item')
+ self.assertEqual(r.request.prefixed_path, '/item')
app = Map(
match('/', 'index') | handler,
|
Test fixed for request.prefixed_path
|
SmartTeleMax_iktomi
|
train
|
9e2e8eae0cf55e8d1ca388f522ce8e6f019039de
|
diff --git a/example/simple.py b/example/simple.py
index <HASH>..<HASH> 100644
--- a/example/simple.py
+++ b/example/simple.py
@@ -6,7 +6,7 @@ import instana.tracer
import time
import opentracing.ext.tags as ext
-SERVICE = "python-simple"
+SERVICE = "python-overlord"
def main(argv):
instana.tracer.init(o.Options(service=SERVICE,
@@ -17,8 +17,8 @@ def main(argv):
simple()
def simple():
- parent_span = ot.tracer.start_span(operation_name="parent")
- parent_span.set_tag(ext.COMPONENT, SERVICE)
+ parent_span = ot.tracer.start_span(operation_name="asteroid")
+ parent_span.set_tag(ext.COMPONENT, "Python simple example app")
parent_span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_SERVER)
parent_span.set_tag(ext.PEER_HOSTNAME, "localhost")
parent_span.set_tag(ext.HTTP_URL, "/python/simple/one")
@@ -26,7 +26,7 @@ def simple():
parent_span.set_tag(ext.HTTP_STATUS_CODE, 200)
parent_span.log_kv({"foo": "bar"})
- child_span = ot.tracer.start_span(operation_name="child", child_of=parent_span)
+ child_span = ot.tracer.start_span(operation_name="spacedust", child_of=parent_span)
child_span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_CLIENT)
child_span.set_tag(ext.PEER_HOSTNAME, "localhost")
child_span.set_tag(ext.HTTP_URL, "/python/simple/two")
|
Example app: better service and span names
|
instana_python-sensor
|
train
|
91194c4e9f771cce763ff4dd59d8c6217e50b084
|
diff --git a/shared/tracker/remote-container.desktop.js b/shared/tracker/remote-container.desktop.js
index <HASH>..<HASH> 100644
--- a/shared/tracker/remote-container.desktop.js
+++ b/shared/tracker/remote-container.desktop.js
@@ -1,4 +1,5 @@
// @flow
+import * as AppGen from '../actions/app-gen'
import * as ChatGen from '../actions/chat-gen'
import * as ProfileGen from '../actions/profile-gen'
import * as TeamsGen from '../actions/teams-gen'
@@ -10,8 +11,10 @@ import {branch, connect, compose, lifecycle, renderNothing, withState, type Disp
const mapDispatchToProps = (dispatch: Dispatch, {teamname}) => ({
_checkRequestedAccess: (teamname: string) => dispatch(TeamsGen.createCheckRequestedAccess({teamname})),
_loadTeams: () => dispatch(TeamsGen.createGetTeams()),
- _onChat: (username: string, myUsername: string) =>
- dispatch(ChatGen.createStartConversation({users: [username, myUsername]})),
+ _onChat: (username: string, myUsername: string) => {
+ dispatch(AppGen.createShowMain())
+ dispatch(ChatGen.createStartConversation({users: [username, myUsername]}))
+ },
_onClickAvatar: (username: string) =>
dispatch(ProfileGen.createOnClickAvatar({openWebsite: true, username})),
_onClose: (username: string) => dispatch(TrackerGen.createOnClose({username})),
|
show main window on start a chat in tracker (#<I>)
|
keybase_client
|
train
|
582919f5513ad25625cf9d81854a68129184dc1d
|
diff --git a/salt/modules/vsphere.py b/salt/modules/vsphere.py
index <HASH>..<HASH> 100644
--- a/salt/modules/vsphere.py
+++ b/salt/modules/vsphere.py
@@ -4866,6 +4866,41 @@ def update_storage_policy(policy, policy_dict, service_instance=None):
@depends(HAS_PYVMOMI)
+@supports_proxies('esxcluster', 'esxdatacenter', 'vcenter')
+@gets_service_instance_via_proxy
+def list_default_storage_policy_of_datastore(datastore, service_instance=None):
+ '''
+ Returns a list of datastores assign the the storage policies.
+
+ datastore
+ Name of the datastore to assign.
+ The datastore needs to be visible to the VMware entity the proxy
+ points to.
+
+ service_instance
+ Service instance (vim.ServiceInstance) of the vCenter.
+ Default is None.
+
+ .. code-block:: bash
+ salt '*' vsphere.list_default_storage_policy_of_datastore datastore=ds1
+ '''
+ log.trace('Listing the default storage policy of datastore \'{0}\''
+ ''.format(datastore))
+ # Find datastore
+ target_ref = _get_proxy_target(service_instance)
+ ds_refs = salt.utils.vmware.get_datastores(service_instance, target_ref,
+ datastore_names=[datastore])
+ if not ds_refs:
+ raise excs.VMwareObjectRetrievalError('Datastore \'{0}\' was not '
+ 'found'.format(datastore))
+ profile_manager = salt.utils.pbm.get_profile_manager(service_instance)
+ policy = salt.utils.pbm.get_default_storage_policy_of_datastore(
+ profile_manager, ds_refs[0])
+ return _get_policy_dict(policy)
+
+
+
+@depends(HAS_PYVMOMI)
@supports_proxies('esxdatacenter', 'esxcluster')
@gets_service_instance_via_proxy
def list_datacenters_via_proxy(datacenter_names=None, service_instance=None):
|
Added salt.modules.vsphere.list_default_storage_policy_of_datastore that lists the dict representation of the policy assigned by default to a datastore
|
saltstack_salt
|
train
|
06677f3bff7000bfce01f3a1f5c52234e773971f
|
diff --git a/src/jquery.fancytree.js b/src/jquery.fancytree.js
index <HASH>..<HASH> 100644
--- a/src/jquery.fancytree.js
+++ b/src/jquery.fancytree.js
@@ -2670,7 +2670,8 @@ $.extend(Fancytree.prototype,
}
ares.push(nodeTitle);
// Note: this will trigger focusout, if node had the focus
- node.span.innerHTML = ares.join("");
+ // Note: don't set node.span.innerHTML directly - it will not cleanup the jQuery data currently associated with SPAN (if any)
+ $(node.span).html(ares.join(""));
},
/** Update element classes according to node state.
* @param {EventData} ctx
|
cleanup current jQuery data before rerendering node
|
mar10_fancytree
|
train
|
2d2786197c2ceaeb62f17ccd05b248baddcb5d04
|
diff --git a/plugins/karma.js b/plugins/karma.js
index <HASH>..<HASH> 100644
--- a/plugins/karma.js
+++ b/plugins/karma.js
@@ -58,6 +58,10 @@ exports.apply_tarpit = function (connection, hook, score, next) {
var plugin = this;
if (!plugin.cfg.tarpit) return next(); // tarpit disabled in config
+ // If tarpit is enabled on the reset_transaction hook, Haraka doesn't
+ // wait. Then bad things happen, like a Haraka crash.
+ if (hook === 'reset_transaction') return next();
+
// no delay for senders with good karma
var k = connection.results.get('karma');
if (score === undefined) {
@@ -74,8 +78,11 @@ exports.apply_tarpit = function (connection, hook, score, next) {
connection.logdebug(plugin, "static tarpit: " + delay);
}
- // roaming users
- if (connection.local_port === '587' && /^(ehlo|connect)$/.test(hook)) {
+ var max = plugin.cfg.tarpit.max || 5;
+
+ // be less punitive for roaming users
+ if (([587,465].indexOf(connection.local_port) !== -1) && /^(ehlo|connect)$/.test(hook)) {
+ max = 2;
// Reduce penalty for good history
if (k.history > 0) {
delay = parseFloat(delay - 2);
@@ -89,7 +96,6 @@ exports.apply_tarpit = function (connection, hook, score, next) {
}
}
- var max = plugin.cfg.tarpit.max || 5;
if (delay > max) {
delay = max;
connection.logdebug(plugin, "tarpit reduced to max: " + delay);
@@ -97,8 +103,8 @@ exports.apply_tarpit = function (connection, hook, score, next) {
connection.loginfo(plugin, 'tarpitting '+hook+' for ' + delay + 's');
setTimeout(function () {
- connection.logdebug(plugin, 'tarpit end');
- return next();
+ connection.loginfo(plugin, 'tarpit '+hook+' end');
+ next();
}, delay * 1000);
};
@@ -107,7 +113,7 @@ exports.should_we_deny = function (next, connection, hook) {
if (connection.early_talker) {
return plugin.apply_tarpit(connection, hook, -10, function () {
- next(DENYDISCONNECT, "You talk too soon"); // never seen a FP
+ next(DENY, "You talk too soon"); // never seen a FP
});
}
|
karma: be less punitive to roaming users
|
haraka_Haraka
|
train
|
129be0023861bf4e228b15b1759ade058fa53dd7
|
diff --git a/lib/opal/parser.rb b/lib/opal/parser.rb
index <HASH>..<HASH> 100644
--- a/lib/opal/parser.rb
+++ b/lib/opal/parser.rb
@@ -177,8 +177,6 @@ module Opal
vars << "__scope = Opal.constants"
vars << "nil = Opal.nil"
- # vars.concat @scope.locals.map { |t| "#{t}" }
- # vars.concat @scope.temps.map { |t| t }
vars.concat @helpers.keys.map { |h| "__#{h} = Opal.#{h}" }
code = "var #{vars.join ', '};\n" + @scope.to_vars + "\n" + code
@@ -241,10 +239,7 @@ module Opal
end
def process(sexp, level)
- # puts "PROCESS: (#{level})"
- # puts " #{sexp.inspect}"
type = sexp.shift
-
raise "Unsupported sexp: #{type}" unless respond_to? type
__send__ type, sexp, level
@@ -340,14 +335,11 @@ module Opal
l = process recv, :expression
r = process arglist[1], :expression
- res = "(#{a} = #{l}, #{b} = #{r}, typeof(#{a}) === "
- res += "'number' ? #{a} #{meth} #{b} : #{a}.#{mid}"
- res += "(#{b}))"
-
@scope.queue_temp a
@scope.queue_temp b
- res
+ "(%s = %s, %s = %s, typeof(%s) === 'number' ? %s %s %s : %s.%s(%s))" %
+ [a, l, b, r, a, a, meth.to_s, b, a, mid, b]
end
# s(:js_block_given)
@@ -390,13 +382,17 @@ module Opal
end
def dot2(sexp, level)
+ lhs = process sexp[0], :expression
+ rhs = process sexp[1], :expression
@helpers[:range] = true
- "__range(#{process sexp[0], :expression}, #{process sexp[1], :expression}, false)"
+ "__range(%s, %s, false)" % [lhs, rhs]
end
def dot3(sexp, level)
+ lhs = process sexp[0], :expression
+ rhs = process sexp[1], :expression
@helpers[:range] = true
- "__range(#{process sexp[0], :expression}, #{process sexp[1], :expression}, true)"
+ "__range(%s, %s, true)" % [lhs, rhs]
end
# s(:str, "string")
@@ -443,11 +439,10 @@ module Opal
to_proc = process(s(:call, s(:js_tmp, tmp), :to_proc, s(:arglist)), :expression)
- code = "(#{tmp} = #{pass}, (typeof(#{tmp}) === 'function' || #{tmp} == null ? #{tmp} : #{to_proc}))"
-
@scope.queue_temp tmp
- code
+ "(%s = %s, (typeof(%s) === 'function' || %s == null ? %s : %s))" %
+ [tmp, pass, tmp, tmp, tmp, to_proc]
end
# s(:iter, call, block_args [, body)
@@ -1255,11 +1250,10 @@ module Opal
}
end
- code = "((#{tmp} = #{process lhs, :expression}, #{tmp} !== false && "
- code += "#{tmp} !== nil) ? #{process rhs, :expression} : #{tmp})"
@scope.queue_temp tmp
- code
+ "(%s = %s, %s !== false && %s !== nil ? %s : %s)" %
+ [tmp, process(lhs, :expression), tmp, tmp, process(rhs, :expression), tmp]
end
# s(:or, lhs, rhs)
@@ -1275,11 +1269,10 @@ module Opal
}
end
- code = "(#{tmp} = #{process lhs, :expression}, #{tmp} !== false && "
- code += "#{tmp} !== nil ? #{tmp} : #{process rhs, :expression})"
@scope.queue_temp tmp
- code
+ "(%s = %s, %s !== false && %s !== nil ? %s : %s)" %
+ [tmp, process(lhs, :expression), tmp, tmp, tmp, process(rhs, :expression)]
end
# s(:yield, arg1, arg2)
@@ -1407,9 +1400,8 @@ module Opal
# s(:cvar, name)
def cvar(exp, level)
tmp = @scope.new_temp
- code = "((#{tmp} = Opal.cvars[#{exp.shift.to_s.inspect}]) == null ? null : #{tmp})"
@scope.queue_temp tmp
- code
+ "((%s = Opal.cvars[%s]) == null ? nil : %s)" % [tmp, exp.shift.to_s.inspect, tmp]
end
# @@name = rhs
@@ -1429,13 +1421,11 @@ module Opal
def colon2(sexp, level)
base = sexp[0]
name = sexp[1]
- "(#{process base, :expression})._scope.#{name.to_s}"
- # "Opal.const_get((#{process base, :expression})._scope, #{name.to_s.inspect})"
+ "(%s)._scope.%s" % [process(base, :expression), name.to_s]
end
def colon3(exp, level)
"Opal.Object._scope.#{exp.shift.to_s}"
- # "Opal.const_get(Opal.Object._scope, #{exp.shift.to_s.inspect})"
end
# super a, b, c
@@ -1447,8 +1437,6 @@ module Opal
args << process(sexp.shift, :expression)
end
- # args.unshift 'null'
-
js_super "[#{ args.join ', ' }]"
end
|
Improve readability of some code generator methods
|
opal_opal
|
train
|
64b8eeeab9b6046b3c9fdb9611960ebd82fda802
|
diff --git a/Auth/Yadis/PlainHTTPFetcher.php b/Auth/Yadis/PlainHTTPFetcher.php
index <HASH>..<HASH> 100644
--- a/Auth/Yadis/PlainHTTPFetcher.php
+++ b/Auth/Yadis/PlainHTTPFetcher.php
@@ -63,6 +63,10 @@ class Auth_Yadis_PlainHTTPFetcher extends Auth_Yadis_HTTPFetcher {
}
}
+ if (!array_key_exists('path', $parts)) {
+ $parts['path'] = '/';
+ }
+
$host = $parts['host'];
if ($parts['scheme'] == 'https') {
|
[project @ Plain http fetcher: allow for absent "path" key in parsed URL array]
|
openid_php-openid
|
train
|
d43e885ca8e9addce2eec97d25d8acbf5125f5fc
|
diff --git a/client/reader/following/controller.js b/client/reader/following/controller.js
index <HASH>..<HASH> 100644
--- a/client/reader/following/controller.js
+++ b/client/reader/following/controller.js
@@ -9,7 +9,6 @@ import i18n from 'i18n-calypso';
* Internal dependencies
*/
import { sectionify } from 'lib/route';
-import userSettings from 'lib/user-settings';
import { trackPageLoad, setPageTitle } from 'reader/controller-helper';
import AsyncLoad from 'components/async-load';
@@ -36,7 +35,6 @@ const exported = {
showMoreResults={ Boolean( showMoreResults ) }
subsSortOrder={ subsSortOrder }
context={ context }
- userSettings={ userSettings }
/>
);
next();
|
remove userSettings from reader/following/controller, because the controller passes userSettings to reader/following-manage which doesn't use userSettings at all (#<I>)
|
Automattic_wp-calypso
|
train
|
01404608d75e0140289fc7cedb938e30aa397d40
|
diff --git a/wallace/models.py b/wallace/models.py
index <HASH>..<HASH> 100644
--- a/wallace/models.py
+++ b/wallace/models.py
@@ -82,15 +82,35 @@ class Node(Base):
@property
def successors2(self):
+ print "successors2 is deprecated, use downstream_nodes instead"
+ return downstream_nodes(self, Agent)
+ # outgoing_vectors = Vector.query.filter_by(origin=self).all()
+ # return [v.destination for v in outgoing_vectors
+ # if isinstance(v.destination, Agent)]
+
+ @property
+ def downstream_nodes(self, type=None):
+ if type is None:
+ type = Node
outgoing_vectors = Vector.query.filter_by(origin=self).all()
return [v.destination for v in outgoing_vectors
- if isinstance(v.destination, Agent)]
+ if isinstance(v.destination, type)]
@property
- def predecessors2(self):
+ def upstream_nodes(self, type=None):
+ if type is None:
+ type = Node
incoming_vectors = Vector.query.filter_by(destination=self).all()
- return [v.origin for v in incoming_vectors
- if isinstance(v.origin, Agent)]
+ return [v.destination for v in incoming_vectors
+ if isinstance(v.destination, type)]
+
+ @property
+ def predecessors2(self):
+ print "predecessors2 is deprecated, use upstream_nodes instead"
+ return upstream_nodes(self, Agent)
+ # incoming_vectors = Vector.query.filter_by(destination=self).all()
+ # return [v.origin for v in incoming_vectors
+ # if isinstance(v.origin, Agent)]
def __repr__(self):
return "Node-{}-{}".format(self.uuid[:6], self.type)
|
replace successors/predecessors with upset and downstream nodes
|
Dallinger_Dallinger
|
train
|
5c38766ace81fbb3676a9aa6302c1a816b053ce6
|
diff --git a/src/Features/App.php b/src/Features/App.php
index <HASH>..<HASH> 100644
--- a/src/Features/App.php
+++ b/src/Features/App.php
@@ -39,7 +39,7 @@ trait App
/**
* Get a request to a registered class
*
- * @param string $sClass The class name
+ * @param string $sClassName The class name
*
* @return \Jaxon\Request\Factory\CallableClass\Request
*/
|
Fixed some errors detected by Scrutinizer.
|
jaxon-php_jaxon-core
|
train
|
3d34b6845eff57a3e071a92a1bdae3ba9acec793
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -6,7 +6,7 @@ from setuptools import setup, find_packages
from cms_bootstrap3 import __version__
-with open('README.md', encoding='utf-8') as fh:
+with open('README.md') as fh:
long_description = fh.read()
|
fix encoding problem in Python-<I>
|
jrief_djangocms-bootstrap
|
train
|
29f392791640647a934cb144f53096e41b200a37
|
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -69,6 +69,7 @@ if (inBrowser && substanceGlobals.TEST_UI) {
var results = harness._results;
harness.runTests = function(tests) {
+ tests = tests.slice();
function next() {
if (tests.length > 0) {
var t = tests.shift();
|
Make sure to clone the array of tests before running.
|
substance_substance
|
train
|
53673398408b6991f11d61c1ff5d2ba350f129f8
|
diff --git a/guake/terminal.py b/guake/terminal.py
index <HASH>..<HASH> 100644
--- a/guake/terminal.py
+++ b/guake/terminal.py
@@ -307,6 +307,7 @@ class GuakeTerminal(Vte.Terminal):
def _on_ctrl_click_matcher(self, matched_string):
value, tag = matched_string
+ found_matcher = False
log.debug("matched string: %s", matched_string)
# First searching in additional matchers
use_quick_open = self.settings.general.get_boolean("quick-open-enable")
|
fix scrash on ctrl+click
|
Guake_guake
|
train
|
f4b87da223beb6c042a39746b813880f4a465b63
|
diff --git a/auto_tests/tests/axis_labels.js b/auto_tests/tests/axis_labels.js
index <HASH>..<HASH> 100644
--- a/auto_tests/tests/axis_labels.js
+++ b/auto_tests/tests/axis_labels.js
@@ -84,6 +84,7 @@ AxisLabelsTestCase.prototype.testMinusOneToOne = function() {
AxisLabelsTestCase.prototype.testSmallRangeNearZero = function() {
var opts = {
+ drawAxesAtZero: true,
width: 480,
height: 320
};
diff --git a/dygraph-canvas.js b/dygraph-canvas.js
index <HASH>..<HASH> 100644
--- a/dygraph-canvas.js
+++ b/dygraph-canvas.js
@@ -383,9 +383,17 @@ DygraphCanvasRenderer.prototype._renderAxis = function() {
}
// draw a vertical line on the left to separate the chart from the labels.
+ var axisX;
+ if (this.attr_('drawAxesAtZero')) {
+ var r = this.dygraph_.toPercentXCoord(0);
+ if (r > 1 || r < 0) r = 0;
+ axisX = halfUp(this.area.x + r * this.area.w);
+ } else {
+ axisX = halfUp(this.area.x);
+ }
context.beginPath();
- context.moveTo(halfUp(this.area.x), halfDown(this.area.y));
- context.lineTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
+ context.moveTo(axisX, halfDown(this.area.y));
+ context.lineTo(axisX, halfDown(this.area.y + this.area.h));
context.closePath();
context.stroke();
@@ -436,8 +444,16 @@ DygraphCanvasRenderer.prototype._renderAxis = function() {
}
context.beginPath();
- context.moveTo(halfUp(this.area.x), halfDown(this.area.y + this.area.h));
- context.lineTo(halfUp(this.area.x + this.area.w), halfDown(this.area.y + this.area.h));
+ var axisY;
+ if (this.attr_('drawAxesAtZero')) {
+ var r = this.dygraph_.toPercentYCoord(0, 0);
+ if (r > 1 || r < 0) r = 1;
+ axisY = halfDown(this.area.y + r * this.area.h);
+ } else {
+ axisY = halfDown(this.area.y + this.area.h);
+ }
+ context.moveTo(halfUp(this.area.x), axisY);
+ context.lineTo(halfUp(this.area.x + this.area.w), axisY);
context.closePath();
context.stroke();
}
diff --git a/dygraph-options-reference.js b/dygraph-options-reference.js
index <HASH>..<HASH> 100644
--- a/dygraph-options-reference.js
+++ b/dygraph-options-reference.js
@@ -489,6 +489,12 @@ Dygraph.OPTIONS_REFERENCE = // <JSON>
"type": "boolean",
"description": "When set, the heuristic that fixes the Y axis at zero for a data set with the minimum Y value of zero is disabled. \nThis is particularly useful for data sets that contain many zero values, especially for step plots which may otherwise have lines not visible running along the bottom axis."
},
+ "drawAxesAtZero": {
+ "default": "false",
+ "labels": ["Axis display"],
+ "type": "boolean",
+ "description": "When set, draw the X axis at the Y=0 position and the Y axis at the X=0 position if those positions are inside the graph's visible area. Otherwise, draw the axes at the bottom or left graph edge as usual."
+ },
"xAxisLabelFormatter": {
"default": "",
"labels": ["Deprecated"],
diff --git a/dygraph.js b/dygraph.js
index <HASH>..<HASH> 100644
--- a/dygraph.js
+++ b/dygraph.js
@@ -233,6 +233,7 @@ Dygraph.DEFAULT_ATTRS = {
stepPlot: false,
avoidMinZero: false,
+ drawAxesAtZero: false,
// Sizes of the various chart labels.
titleHeight: 28,
diff --git a/gallery/linear-regression.js b/gallery/linear-regression.js
index <HASH>..<HASH> 100644
--- a/gallery/linear-regression.js
+++ b/gallery/linear-regression.js
@@ -112,6 +112,7 @@ Gallery.register(
labels: ['X', 'Y1', 'Y2'],
underlayCallback: drawLines,
drawPoints: true,
+ drawAxesAtZero: true,
strokeWidth: 0.0
}
);
|
Add new option "drawAxesAtZero"
When set, draw the X axis at the Y=0 position and the Y axis at the X=0
position if those positions are inside the graph's visible area.
Otherwise, draw the axes at the bottom or left graph edge as usual.
|
danvk_dygraphs
|
train
|
d06a7b9ec9527e4217bb7f17343a26894e2f2fea
|
diff --git a/src/main/resources/META-INF/resources/primefaces/fileupload/fileupload.js b/src/main/resources/META-INF/resources/primefaces/fileupload/fileupload.js
index <HASH>..<HASH> 100644
--- a/src/main/resources/META-INF/resources/primefaces/fileupload/fileupload.js
+++ b/src/main/resources/META-INF/resources/primefaces/fileupload/fileupload.js
@@ -1175,23 +1175,40 @@ PrimeFaces.widget.FileUpload.prototype.setupRestrictions = function() {
}
/**
- * IFrame response response for legacy browsers e.g. IE.
+ * IFrame response response for legacy browsers e.g. IE, FF 3.5
*/
PrimeFaces.widget.FileUpload.prototype.parseIFrameResponse = function(iframe) {
- var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
- xmlDoc.async = "false";
+ var iframeContent = iframe.contents();
+
+ if(window.DOMParser) { //FF 3.5 and before
+ var xmlString = '<?xml version="1.0" encoding="UTF-8"?>';
+ xmlString += '<partial-response><changes>';
+
+ iframeContent.find('update').each(function(i) {
+ var update = $(this),
+ id = update.attr('id'),
+ content = update.text();
+
+ xmlString += '<update id="' + id + '"><![CDATA[' + content + ']]></update>';
+ });
+
+ xmlString += '</changes></partial-response>';
- //format response so IE can parse
- var iframeContent = iframe.contents().text();
- iframeContent = $.trim(iframeContent.replace(/(> -)|(>-)/g,'>'));
+ return new DOMParser().parseFromString(xmlString, 'text/xml');
+ }
+ else { //IE
+ iframeContent = $.trim(iframeContent.replace(/(> -)|(>-)/g,'>'));
+ var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
+ xmlDoc.async = "false";
- xmlDoc.loadXML(iframeContent);
+ xmlDoc.loadXML(iframeContent);
- var responseXML = {};
- responseXML.documentElement = xmlDoc.documentElement;
+ var responseXML = {};
+ responseXML.documentElement = xmlDoc.documentElement;
- return responseXML;
-}
+ return responseXML;
+ }
+}
PrimeFaces.widget.FileUpload.prototype.startIEProgress = function(handler) {
handler.uploadRow.find('.ui-progressbar-value').addClass('ui-progressbar-value-ie');
|
Fixed fileupload for firefox <I>.x
|
primefaces_primefaces
|
train
|
8cc959bc9b01e42e15d46f70809b3e15405689b6
|
diff --git a/indy_common/authorize/auth_map.py b/indy_common/authorize/auth_map.py
index <HASH>..<HASH> 100644
--- a/indy_common/authorize/auth_map.py
+++ b/indy_common/authorize/auth_map.py
@@ -4,7 +4,7 @@ from indy_common.authorize.auth_actions import AuthActionAdd, AuthActionEdit
from indy_common.authorize.auth_constraints import AuthConstraint, AuthConstraintOr, accepted_roles, IDENTITY_OWNER
from indy_common.constants import TRUST_ANCHOR, POOL_CONFIG, VALIDATOR_INFO, POOL_UPGRADE, POOL_RESTART, NODE, \
CLAIM_DEF, SCHEMA, NYM, ROLE, AUTH_RULE, NETWORK_MONITOR, REVOC_REG_ENTRY, REVOC_REG_DEF, ATTRIB
-from plenum.common.constants import TRUSTEE, STEWARD, VERKEY
+from plenum.common.constants import TRUSTEE, STEWARD, VERKEY, TXN_AUTHOR_AGREEMENT
edit_role_actions = {} # type: Dict[str, Dict[str, AuthActionEdit]]
for role_from in accepted_roles:
@@ -40,6 +40,10 @@ key_rotation = AuthActionEdit(txn_type=NYM,
old_value='*',
new_value='*')
+txn_author_agreement = AuthActionAdd(txn_type=TXN_AUTHOR_AGREEMENT,
+ field='*',
+ value='*')
+
add_attrib = AuthActionAdd(txn_type=ATTRIB,
field='*',
value='*')
@@ -248,6 +252,7 @@ auth_map = {
add_new_network_monitor.get_action_id(): steward_or_trustee_constraint,
add_new_identity_owner.get_action_id(): trust_anchor_or_steward_or_trustee_constraint,
key_rotation.get_action_id(): owner_constraint,
+ txn_author_agreement.get_action_id(): one_trustee_constraint,
add_attrib.get_action_id(): owner_constraint,
edit_attrib.get_action_id(): owner_constraint,
add_schema.get_action_id(): trust_anchor_or_steward_or_trustee_constraint,
diff --git a/indy_node/server/config_req_handler.py b/indy_node/server/config_req_handler.py
index <HASH>..<HASH> 100644
--- a/indy_node/server/config_req_handler.py
+++ b/indy_node/server/config_req_handler.py
@@ -9,7 +9,7 @@ from plenum.common.exceptions import InvalidClientRequest
from plenum.common.txn_util import reqToTxn, is_forced, get_payload_data, append_txn_metadata, get_type
from plenum.server.config_req_handler import ConfigReqHandler as PConfigReqHandler
-from plenum.common.constants import TXN_TYPE, NAME, VERSION, FORCE
+from plenum.common.constants import TXN_TYPE, NAME, VERSION, FORCE, TXN_AUTHOR_AGREEMENT
from indy_common.constants import POOL_UPGRADE, START, CANCEL, SCHEDULE, ACTION, POOL_CONFIG, NODE_UPGRADE, PACKAGE, \
REINSTALL, AUTH_RULE, CONSTRAINT, AUTH_ACTION, OLD_VALUE, NEW_VALUE, AUTH_TYPE, FIELD, GET_AUTH_RULE
from indy_common.types import Request, ClientGetAuthRuleOperation
@@ -167,6 +167,11 @@ class ConfigReqHandler(PConfigReqHandler):
field="*",
old_value="*",
new_value="*")])
+ elif typ == TXN_AUTHOR_AGREEMENT:
+ self.write_req_validator.validate(req,
+ [AuthActionAdd(txn_type=typ,
+ field="*",
+ value="*")])
def apply(self, req: Request, cons_time):
txn = append_txn_metadata(reqToTxn(req),
diff --git a/indy_node/test/auth_rule/test_auth_map.py b/indy_node/test/auth_rule/test_auth_map.py
index <HASH>..<HASH> 100644
--- a/indy_node/test/auth_rule/test_auth_map.py
+++ b/indy_node/test/auth_rule/test_auth_map.py
@@ -30,6 +30,14 @@ def test_auth_map_nym():
assert rule_str in auth_map.auth_map.keys()
+def test_auth_map_txn_author_agreement():
+ rules = [(auth_map.txn_author_agreement, "4--ADD--*--*--*"), ]
+
+ for (rule, rule_str) in rules:
+ assert rule.get_action_id() == rule_str
+ assert rule_str in auth_map.auth_map.keys()
+
+
def test_auth_map_attrib():
rules = [(auth_map.add_attrib, "100--ADD--*--*--*"),
(auth_map.edit_attrib, "100--EDIT--*--*--*")]
|
INDY-<I>: Add TAA-related auth rules
|
hyperledger_indy-node
|
train
|
ad394f9038bb9c8130c79b4f83c32c1b71b86d79
|
diff --git a/spec/TemporaryDirectory.spec.php b/spec/TemporaryDirectory.spec.php
index <HASH>..<HASH> 100644
--- a/spec/TemporaryDirectory.spec.php
+++ b/spec/TemporaryDirectory.spec.php
@@ -14,10 +14,10 @@ describe('TemporaryDirectory', function() {
expect($this->temp->getPath())->toEndWith('/foo');
});
});
- describe('#createFile', function() {
+ describe('#createNewFile', function() {
beforeEach(function() {
$this->temp = new TemporaryDirectory($this->rootDirectory . '/bar');
- $this->file = $this->temp->createFile('file.txt');
+ $this->file = $this->temp->createNewFile('file.txt');
$this->fileName = $this->file->getName();
$this->filePath = $this->file->getPath();
});
diff --git a/src/TemporaryDirectory.php b/src/TemporaryDirectory.php
index <HASH>..<HASH> 100644
--- a/src/TemporaryDirectory.php
+++ b/src/TemporaryDirectory.php
@@ -26,7 +26,7 @@ final class TemporaryDirectory extends TemporaryNode implements FileSystemNode
$this->node = new SplFileInfo($path);
}
- public function createFile($name, $mode = FileSystemPermission::NORMAL)
+ public function createNewFile($name, $mode = FileSystemPermission::NORMAL)
{
$newFile = $this->getPath() . '/' . $name;
$file = new TemporaryFile($newFile, $mode);
|
Raname method to createNewFile
|
holyshared_peridot-temporary-plugin
|
train
|
2bfcab022e438f7e4e08bcee7300b6127d4cee93
|
diff --git a/salt/modules/mysql.py b/salt/modules/mysql.py
index <HASH>..<HASH> 100644
--- a/salt/modules/mysql.py
+++ b/salt/modules/mysql.py
@@ -1596,11 +1596,12 @@ def _mysql_user_create(
__context__["mysql.error"] = err
qry = False
else:
- if salt.utils.data.is_true(unix_socket):
- if host == "localhost":
- qry += " IDENTIFIED WITH auth_socket"
- else:
- log.error("Auth via unix_socket can be set only for host=localhost")
+ if host == "localhost":
+ qry += " IDENTIFIED WITH auth_socket"
+ else:
+ log.error("Auth via unix_socket can be set only for host=localhost")
+ __context__["mysql.error"] = err
+ qry = False
else:
if not salt.utils.data.is_true(allow_passwordless):
if password is not None:
@@ -1655,11 +1656,12 @@ def _mariadb_user_create(
__context__["mysql.error"] = err
qry = False
else:
- if salt.utils.data.is_true(unix_socket):
- if host == "localhost":
- qry += " IDENTIFIED VIA unix_socket"
- else:
- log.error("Auth via unix_socket can be set only for host=localhost")
+ if host == "localhost":
+ qry += " IDENTIFIED VIA unix_socket"
+ else:
+ log.error("Auth via unix_socket can be set only for host=localhost")
+ __context__["mysql.error"] = err
+ qry = False
else:
if not salt.utils.data.is_true(allow_passwordless):
if password is not None:
|
Removing redundant check if unix_socket is True.
|
saltstack_salt
|
train
|
6fa0b5ffab45e3242bc012cdbedea6f4dd219bb0
|
diff --git a/modules_v2/todays_events/module.php b/modules_v2/todays_events/module.php
index <HASH>..<HASH> 100644
--- a/modules_v2/todays_events/module.php
+++ b/modules_v2/todays_events/module.php
@@ -150,7 +150,7 @@ class todays_events_WT_Module extends WT_Module implements WT_Module_Block {
$sortStyle=get_block_setting($block_id, 'sortStyle', 'alpha');
echo '<tr><td class="descriptionbox wrap width33">';
- echo WT_I18N::translate('Sort Style');
+ echo WT_I18N::translate('Sort style');
echo '</td><td class="optionbox">';
echo select_edit_control('sortStyle', array('alpha'=>WT_I18N::translate('alphabetically'), 'anniv'=>WT_I18N::translate('By Anniversary')), null, $sortStyle, '');
echo '</td></tr>';
diff --git a/modules_v2/upcoming_events/module.php b/modules_v2/upcoming_events/module.php
index <HASH>..<HASH> 100644
--- a/modules_v2/upcoming_events/module.php
+++ b/modules_v2/upcoming_events/module.php
@@ -157,7 +157,7 @@ class upcoming_events_WT_Module extends WT_Module implements WT_Module_Block {
$sortStyle=get_block_setting($block_id, 'sortStyle', 'alpha');
echo '<tr><td class="descriptionbox wrap width33">';
- echo WT_I18N::translate('Sort Style');
+ echo WT_I18N::translate('Sort style');
echo '</td><td class="optionbox">';
echo select_edit_control('sortStyle', array('alpha'=>WT_I18N::translate('alphabetically'), 'anniv'=>WT_I18N::translate('By Anniversary')), null, $sortStyle, '');
echo '</td></tr>';
|
Combine translation strings that only differ by upper/lower case. Prefer the lower case one.
|
fisharebest_webtrees
|
train
|
eb6db27cb504bb272414c030130b930e131a7a5c
|
diff --git a/satpy/writers/cf_writer.py b/satpy/writers/cf_writer.py
index <HASH>..<HASH> 100644
--- a/satpy/writers/cf_writer.py
+++ b/satpy/writers/cf_writer.py
@@ -208,6 +208,9 @@ def _encode_nc(obj):
elif isinstance(obj, np.void):
return tuple(obj)
elif isinstance(obj, np.ndarray):
+ if not len(obj.dtype) and obj.dtype == np.bool_:
+ # Convert array of booleans to array of strings
+ obj = obj.astype(str)
if not len(obj.dtype) and len(obj.shape) <= 1:
# Multi-dimensional nc attributes are not supported, so we have to skip record arrays and multi-dimensional
# arrays here
|
Convert array of booleans to array of strings
|
pytroll_satpy
|
train
|
0a5c350fb5cd5863bc4930fc335f3341a5555e8a
|
diff --git a/.env.example b/.env.example
index <HASH>..<HASH> 100644
--- a/.env.example
+++ b/.env.example
@@ -50,6 +50,7 @@ DATABASE_POOL=5
#DATABASE_SOCKET=
REDIS_NAMESPACE=cortex_dev
+CACHE_URL=redis://localhost:6379/0/cache
#
# AWS (Production Configuration)
diff --git a/config/environments/development.rb b/config/environments/development.rb
index <HASH>..<HASH> 100644
--- a/config/environments/development.rb
+++ b/config/environments/development.rb
@@ -27,7 +27,7 @@ Cortex::Application.configure do
# number of complex assets.
config.assets.debug = true
- config.cache_store = :redis_store, 'redis://localhost:6379/0/cache'
+ config.cache_store = :redis_store, ENV['CACHE_URL']
if ENV['S3_BUCKET_NAME'].to_s != ''
config.paperclip_defaults = {
diff --git a/config/environments/production.rb b/config/environments/production.rb
index <HASH>..<HASH> 100644
--- a/config/environments/production.rb
+++ b/config/environments/production.rb
@@ -52,7 +52,7 @@ Cortex::Application.configure do
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
- # config.cache_store = :mem_cache_store
+ config.cache_store = :redis_store, ENV['CACHE_URL']
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
config.action_controller.asset_host = ENV['ASSET_HOST']
diff --git a/config/environments/staging.rb b/config/environments/staging.rb
index <HASH>..<HASH> 100644
--- a/config/environments/staging.rb
+++ b/config/environments/staging.rb
@@ -22,6 +22,8 @@ Cortex::Application.configure do
# Raise an error on page load if there are pending migrations
config.active_record.migration_error = :page_load
+ config.cache_store = :redis_store, ENV['CACHE_URL']
+
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
diff --git a/config/environments/test.rb b/config/environments/test.rb
index <HASH>..<HASH> 100644
--- a/config/environments/test.rb
+++ b/config/environments/test.rb
@@ -34,6 +34,8 @@ Cortex::Application.configure do
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
+ config.cache_store = :redis_store, ENV['CACHE_URL']
+
Sidekiq.configure_server do |config|
config.redis = { :namespace => 'cortex_test' }
end
|
Add CACHE_URL env variable to point to the redis store
|
cortex-cms_cortex
|
train
|
1d93859ff363abe8acbea4e347dc77cd1d749683
|
diff --git a/hellocharts-library/src/lecho/lib/hellocharts/LineChart.java b/hellocharts-library/src/lecho/lib/hellocharts/LineChart.java
index <HASH>..<HASH> 100644
--- a/hellocharts-library/src/lecho/lib/hellocharts/LineChart.java
+++ b/hellocharts-library/src/lecho/lib/hellocharts/LineChart.java
@@ -31,7 +31,7 @@ import android.view.View;
*/
public class LineChart extends View {
private static final String TAG = "LineChart";
- private static final float LINE_SMOOTHNES = 0.15f;
+ private static final float LINE_SMOOTHNES = 0.16f;
private static final int DEFAULT_LINE_WIDTH_DP = 3;
private static final int DEFAULT_POINT_RADIUS_DP = 6;
private static final int DEFAULT_POINT_TOUCH_RADIUS_DP = 12;
@@ -163,7 +163,8 @@ public class LineChart extends View {
}
}
- // Drawing points can be done in the same loop as drawing lines but it may cause problems in the future.
+ // TODO Drawing points can be done in the same loop as drawing lines but it may cause problems in the future. Reuse
+ // calculated X/Y;
private void drawPoints(Canvas canvas) {
int seriesIndex = 0;
for (InternalSeries internalSeries : mData.getInternalsSeries()) {
@@ -200,20 +201,31 @@ public class LineChart extends View {
private void prepareSmoothPath(final InternalSeries internalSeries) {
final int domainSize = mData.getDomain().size();
+ float previousPointX = Float.NaN;
+ float previousPointY = Float.NaN;
+ float currentPointX = Float.NaN;
+ float currentPointY = Float.NaN;
+ float nextPointX = Float.NaN;
+ float nextPointY = Float.NaN;
for (int valueIndex = 0; valueIndex < domainSize - 1; ++valueIndex) {
- final float currentPointX = calculateX(mData.getDomain().get(valueIndex));
- final float currentPointY = calculateY(internalSeries.getValues().get(valueIndex).getPosition());
- final float nextPointX = calculateX(mData.getDomain().get(valueIndex + 1));
- final float nextPointY = calculateY(internalSeries.getValues().get(valueIndex + 1).getPosition());
- final float previousPointX;
- final float previousPointY;
- if (valueIndex > 0) {
- previousPointX = calculateX(mData.getDomain().get(valueIndex - 1));
- previousPointY = calculateY(internalSeries.getValues().get(valueIndex - 1).getPosition());
- } else {
- previousPointX = currentPointX;
- previousPointY = currentPointY;
+ if (Float.isNaN(currentPointX)) {
+ currentPointX = calculateX(mData.getDomain().get(valueIndex));
+ currentPointY = calculateY(internalSeries.getValues().get(valueIndex).getPosition());
+ }
+ if (Float.isNaN(previousPointX)) {
+ if (valueIndex > 0) {
+ previousPointX = calculateX(mData.getDomain().get(valueIndex - 1));
+ previousPointY = calculateY(internalSeries.getValues().get(valueIndex - 1).getPosition());
+ } else {
+ previousPointX = currentPointX;
+ previousPointY = currentPointY;
+ }
+ }
+ if (Float.isNaN(nextPointX)) {
+ nextPointX = calculateX(mData.getDomain().get(valueIndex + 1));
+ nextPointY = calculateY(internalSeries.getValues().get(valueIndex + 1).getPosition());
}
+ // afterNextPoint is always new one or it is equal to nextPoint.
final float afterNextPointX;
final float afterNextPointY;
if (valueIndex < domainSize - 2) {
@@ -223,6 +235,7 @@ public class LineChart extends View {
afterNextPointX = nextPointX;
afterNextPointY = nextPointY;
}
+ // To draw cubic curve control points are needed.
final float firstDiffX = (nextPointX - previousPointX);
final float firstDiffY = (nextPointY - previousPointY);
final float secondDiffX = (afterNextPointX - currentPointX);
@@ -234,6 +247,13 @@ public class LineChart extends View {
mLinePath.moveTo(currentPointX, currentPointY);
mLinePath.cubicTo(firstControlPointX, firstControlPointY, secondControlPointX, secondControlPointY,
nextPointX, nextPointY);
+ // Shift values to prevent recalculation of values that where already calculated.
+ previousPointX = currentPointX;
+ previousPointY = currentPointY;
+ currentPointX = nextPointX;
+ currentPointY = nextPointY;
+ nextPointX = afterNextPointX;
+ nextPointY = afterNextPointY;
}
}
|
Improved smooth path drawing by reusing calculations.
|
lecho_hellocharts-android
|
train
|
88be6096aa7c417cf9109381fb305ab2b48f8caf
|
diff --git a/mbuild/compound.py b/mbuild/compound.py
index <HASH>..<HASH> 100755
--- a/mbuild/compound.py
+++ b/mbuild/compound.py
@@ -14,6 +14,7 @@ from mdtraj.core.element import Element
from mdtraj.core.element import get_by_symbol
from mdtraj.core.topology import Topology
+import mbuild
from mbuild.atom import Atom
from mbuild.box import Box
from mbuild.bond import Bond
@@ -21,6 +22,7 @@ from mbuild.formats.mol2 import write_mol2
from mbuild.orderedset import OrderedSet
from mbuild.part import Part
+import json
__all__ = ['load', 'Compound']
@@ -238,7 +240,7 @@ class Compound(Part):
the_file.write(html)
webbrowser.open('file:' + html_file[1])
- def visualize(self, show_ports=False):
+ def visualize(self, show_ports=False, export_topology=True):
"""Visualize the Compound using VMD.
Assumes you have VMD installed and can call it from the command line via
@@ -270,7 +272,21 @@ class Compound(Part):
from mdtraj.html import TrajectoryView, enable_notebook
enable_notebook()
traj = self.to_trajectory(show_ports=show_ports)
- return TrajectoryView(traj, colorBy='atom')
+ traj_view = TrajectoryView(traj, colorBy='atom')
+
+ if export_topology:
+ # get topology
+ topology = traj_view._computeTopology()
+ # export json
+ with open('topology_{}.json'.format(self.kind.lower()), 'w') as json_file:
+ json.dump(topology, json_file)
+
+ # import pdb
+ # pdb.set_trace()
+
+ return traj_view
+ # return TrajectoryView(traj, colorBy='atom')
+
@property
def xyz(self):
|
added export topology feature to visualize *
|
mosdef-hub_mbuild
|
train
|
193760dec63b52058a90eb0720d3e8849df63d94
|
diff --git a/Swat/SwatDisplayableContainer.php b/Swat/SwatDisplayableContainer.php
index <HASH>..<HASH> 100644
--- a/Swat/SwatDisplayableContainer.php
+++ b/Swat/SwatDisplayableContainer.php
@@ -21,9 +21,9 @@ class SwatDisplayableContainer extends SwatContainer
if (!$this->visible)
return;
- $div_tag = new SwatHtmlTag('div');
- $div_tag->id = $this->id;
- $div_tag->class = $this->getCSSClassString();
+ $div = new SwatHtmlTag('div');
+ $div->id = $this->id;
+ $div->class = $this->getCSSClassString();
$div->open();
$this->displayChildren();
|
Fix misnamed SwatHtmltag
This was probably never caught because we seldom (if ever) use SwatDisplableContainer's own display() method
svn commit r<I>
|
silverorange_swat
|
train
|
304f2fece4b1a8af9cb0bd88f6684a3cbf68991c
|
diff --git a/pkg/envoy/server.go b/pkg/envoy/server.go
index <HASH>..<HASH> 100644
--- a/pkg/envoy/server.go
+++ b/pkg/envoy/server.go
@@ -1104,7 +1104,31 @@ func getPortNetworkPolicyRule(sel policy.CachedSelector, wildcard bool, l7Parser
return r, canShortCircuit
}
+// getWildcardNetworkPolicyRule returns the rule for port 0, which
+// will be considered after port-specific rules.
func getWildcardNetworkPolicyRule(selectors policy.L7DataMap) *cilium.PortNetworkPolicyRule {
+ // selections are pre-sorted, so sorting is only needed if merging selections from multiple selectors
+ if len(selectors) == 1 {
+ for sel := range selectors {
+ if sel.IsWildcard() {
+ return &cilium.PortNetworkPolicyRule{}
+ }
+ selections := sel.GetSelections()
+ if len(selections) == 0 {
+ // No remote policies would match this rule. Discard it.
+ return nil
+ }
+ // convert from []uint32 to []uint64
+ remotePolicies := make([]uint64, len(selections))
+ for i, id := range selections {
+ remotePolicies[i] = uint64(id)
+ }
+ return &cilium.PortNetworkPolicyRule{
+ RemotePolicies: remotePolicies,
+ }
+ }
+ }
+
// Use map to remove duplicates
remoteMap := make(map[uint64]struct{})
wildcardFound := false
@@ -1190,7 +1214,7 @@ func getDirectionNetworkPolicy(ep logger.EndpointUpdater, l4Policy policy.L4Poli
// port-specific rules. Otherwise traffic from allowed remotes could be dropped.
rule := getWildcardNetworkPolicyRule(l4.L7RulesPerSelector)
if rule != nil {
- if len(rule.RemotePolicies) == 0 && rule.L7 == nil {
+ if len(rule.RemotePolicies) == 0 {
// Got an allow-all rule, which can short-circuit all of
// the other rules.
allowAll = true
|
envoy: Optimize also non-L7 rules
Short-circuit sorting of port 0 selections, if they come from one
selector, as the selections returned by GetSelections() are already
sorted.
Port 0 l7-rules are always nil, so no need to test for it.
|
cilium_cilium
|
train
|
0ffeb1eec8db1393bea4008553f1065b8f4164f7
|
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
@@ -247,7 +247,8 @@ class NotebookPlugin(SpyderPluginWidget):
self.set_option('main/spyder_pythonpath',
self.main.get_spyder_pythonpath())
- filename = self.tabwidget.create_new_client(filename)
+ client = self.tabwidget.create_new_client(filename)
+ filename = client.filename
if NOTEBOOK_TMPDIR not in filename:
self.add_to_recent(filename)
self.setup_menu_actions()
diff --git a/spyder_notebook/widgets/notebooktabwidget.py b/spyder_notebook/widgets/notebooktabwidget.py
index <HASH>..<HASH> 100755
--- a/spyder_notebook/widgets/notebooktabwidget.py
+++ b/spyder_notebook/widgets/notebooktabwidget.py
@@ -116,8 +116,8 @@ class NotebookTabWidget(Tabs):
Returns
-------
- filename : str or None
- File name of notebook that is opened, or None if unsuccessful.
+ client : NotebookClient or None
+ Notebook client that is opened, or None if unsuccessful.
"""
# Generate the notebook name (in case of a new one)
if not filename:
@@ -147,7 +147,7 @@ class NotebookTabWidget(Tabs):
# See issue 93
self.untitled_num -= 1
self.maybe_create_welcome_client()
- return
+ return None
welcome_client = self.maybe_create_welcome_client()
client = NotebookClient(self, filename, self.actions)
@@ -156,7 +156,7 @@ class NotebookTabWidget(Tabs):
client.load_notebook()
if welcome_client:
self.setCurrentIndex(0)
- return filename
+ return client
def maybe_create_welcome_client(self):
"""
|
Widgets: Return client instead of filename in .create_new_client()
|
spyder-ide_spyder-notebook
|
train
|
ccf6cbd964528dbb4db4974367da63581d2f9b36
|
diff --git a/src/Pckg/Database/Record.php b/src/Pckg/Database/Record.php
index <HASH>..<HASH> 100644
--- a/src/Pckg/Database/Record.php
+++ b/src/Pckg/Database/Record.php
@@ -376,6 +376,9 @@ class Record extends Object implements RecordInterface
*/
public function save(Entity $entity = null, Repository $repository = null)
{
+ /**
+ * @T00D00
+ */
if (isset($this->data['id'])) {
$this->update($entity, $repository);
diff --git a/src/Pckg/Database/Repository/PDO/Command/InsertRecord.php b/src/Pckg/Database/Repository/PDO/Command/InsertRecord.php
index <HASH>..<HASH> 100644
--- a/src/Pckg/Database/Repository/PDO/Command/InsertRecord.php
+++ b/src/Pckg/Database/Repository/PDO/Command/InsertRecord.php
@@ -74,10 +74,19 @@ class InsertRecord
}
if ($this->record->{$this->entity->getPrimaryKey()}) {
+ /**
+ * Primary key is already set to record, we need to update it.
+ */
$insert[$this->entity->getPrimaryKey()] = $this->record->{$this->entity->getPrimaryKey()};
- }
+ $this->insert($table, $insert);
+
+ } else {
+ /**
+ * Primary key is not set yet, we need to set it now.
+ */
+ $this->record->{$this->entity->getPrimaryKey()} = $this->insert($table, $insert);
- $this->record->{$this->entity->getPrimaryKey()} = $this->insert($table, $insert);
+ }
}
return $this->record->{$this->entity->getPrimaryKey()};
|
FIx saving, we need to fix updating ...
|
pckg_database
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.