hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
b7f632087e85e71c257a74eaf6a0172e28ce7ebd
|
diff --git a/js/snippetPreview.js b/js/snippetPreview.js
index <HASH>..<HASH> 100644
--- a/js/snippetPreview.js
+++ b/js/snippetPreview.js
@@ -1163,7 +1163,9 @@ SnippetPreview.prototype.createMeasurementElements = function() {
* Copies the title text to the title measure element to calculate the width in pixels.
*/
SnippetPreview.prototype.measureTitle = function() {
- this.data.titleWidth = this.element.rendered.title.offsetWidth;
+ if( this.element.rendered.title.offsetWidth !== 0 || this.element.rendered.title.textContent === "" ){
+ this.data.titleWidth = this.element.rendered.title.offsetWidth;
+ }
};
/**
|
Prevents setting the width to 0 when not empty
|
Yoast_YoastSEO.js
|
train
|
5c262c75176cdcc9c54ff1ddecf6a65c23662569
|
diff --git a/src/node/obfuscate.js b/src/node/obfuscate.js
index <HASH>..<HASH> 100644
--- a/src/node/obfuscate.js
+++ b/src/node/obfuscate.js
@@ -1,11 +1,24 @@
var VirgilCrypto = require('../../virgil_js.node');
var u = require('./utils');
+/**
+ * Obfuscates data
+ *
+ * @param {Buffer} value - Value to be obfuscated
+ * @param {Buffer} salt - The salt
+ * @param {string} [algorithm] - Hash algorithm. Default is SHA384
+ * @param {number} [iterations] - Number of iterations. Default is 2048.
+ *
+ * @returns {Buffer} - Obfuscated value
+ * */
module.exports = function obfuscate (value, salt, algorithm, iterations) {
iterations = iterations || 2048;
algorithm = algorithm || VirgilCrypto.VirgilHash.Algorithm_SHA384;
- var pbkdf = new VirgilCrypto.VirgilPBKDF(u.toByteArray(salt), iterations);
+ u.checkIsBuffer(value, 'value');
+ u.checkIsBuffer(salt, 'salt');
+
+ var pbkdf = new VirgilCrypto.VirgilPBKDF(u.bufferToByteArray(salt), iterations);
pbkdf.setHashAlgorithm(algorithm);
- return u.byteArrayToBuffer(pbkdf.derive(u.toByteArray(value))).toString('base64');
+ return u.byteArrayToBuffer(pbkdf.derive(u.bufferToByteArray(value)));
};
diff --git a/src/node/tests/obfuscate.js b/src/node/tests/obfuscate.js
index <HASH>..<HASH> 100644
--- a/src/node/tests/obfuscate.js
+++ b/src/node/tests/obfuscate.js
@@ -3,18 +3,19 @@ var VirgilCrypto = require('../');
var expect = require('expect');
describe('obfuscate', function () {
- it('it obfuscates strings', function () {
- var o1 = VirgilCrypto.obfuscate('asfasfas', 'qwqeqwe');
- var o2 = VirgilCrypto.obfuscate('asfasfas', 'qwqeqwe');
- expect(typeof o1).toEqual('string');
- expect(o1).toEqual(o2);
+ it('should obfuscate data', function () {
+ var o1 = VirgilCrypto.obfuscate(new Buffer('obfuscate me'), new Buffer('salt'));
+ var o2 = VirgilCrypto.obfuscate(new Buffer('obfuscate me'), new Buffer('salt'));
+ expect(Buffer.isBuffer(o1)).toBe(true);
+ expect(Buffer.isBuffer(o2)).toBe(true);
+ expect(o1.equals(o2)).toBe(true);
});
- it('different salt -> different result', function () {
- var o1 = VirgilCrypto.obfuscate('asfasfas', 'qwqeqwe');
- var o2 = VirgilCrypto.obfuscate('asfasfas', 'qwqeqwe2');
- expect(typeof o1).toEqual('string');
- expect(typeof o2).toEqual('string');
- expect(o1).toNotEqual(o2);
+ it('should produce different result depending on salt', function () {
+ var o1 = VirgilCrypto.obfuscate(new Buffer('obfuscate me'), new Buffer('salt1'));
+ var o2 = VirgilCrypto.obfuscate(new Buffer('obfuscate me'), new Buffer('salt2'));
+ expect(Buffer.isBuffer(o1)).toBe(true);
+ expect(Buffer.isBuffer(o2)).toBe(true);
+ expect(o1.equals(o2)).toBe(false);
});
});
|
Crypto v2 node: obfuscate accepts value and salt params as Buffers
|
VirgilSecurity_virgil-crypto-javascript
|
train
|
ed208aac7505d61ded1148b934c7f5154e8829f8
|
diff --git a/virtualbox/library_ext/vbox.py b/virtualbox/library_ext/vbox.py
index <HASH>..<HASH> 100644
--- a/virtualbox/library_ext/vbox.py
+++ b/virtualbox/library_ext/vbox.py
@@ -7,6 +7,10 @@ Add helper code to the default ISession class.
# Configure IVirtualBox bootstrap to build from vboxapi getVirtualBox
class IVirtualBox(library.IVirtualBox):
+
+ # Global flag to assert version on object construction.
+ assert_version = True
+
__doc__ = library.IVirtualBox.__doc__
def __init__(self, interface=None, manager=None):
if interface is not None:
@@ -17,6 +21,14 @@ class IVirtualBox(library.IVirtualBox):
manager = virtualbox.Manager()
self._i = manager.get_virtualbox()._i
+ if IVirtualBox.assert_version and self.version != library.vbox_version:
+ msg = ( "pyvbox built against version %s != "
+ "installed VirtualBox version %s.\n"
+ "Set vbox.VirtualBox.assert_version = False to "
+ "disable the version check assertion" ) % (library.vbox_version,
+ self.version)
+ raise EnvironmentError(msg)
+
def register_on_machine_state_changed(self, callback):
"""Set the callback function to consume on machine state changed events.
|
Add assertion in IVirtualBox constructor to check the system's running VirtualBox is the same version as the virtualbox source base used to build virtualbox.library. Also add option to turn off assertion by setting vbox.VirtualBox.assert_version = False.
|
sethmlarson_virtualbox-python
|
train
|
8af7da372b0510a049bf2f6e356ee52a9df74a3a
|
diff --git a/src/urh/settings.py b/src/urh/settings.py
index <HASH>..<HASH> 100644
--- a/src/urh/settings.py
+++ b/src/urh/settings.py
@@ -57,9 +57,9 @@ SELECTION_OPACITY = 1
NOISE_OPACITY = 0.33
# SEPARATION COLORS
-ONES_AREA_COLOR = Qt.darkGreen
-ZEROS_AREA_COLOR = Qt.darkRed
-SEPARATION_OPACITY = 0.25
+ONES_AREA_COLOR = Qt.green
+ZEROS_AREA_COLOR = Qt.magenta
+SEPARATION_OPACITY = 0.15
SEPARATION_PADDING = .05 # percent
# PROTOCOL TABLE COLORS
|
change separation colors to green and magenta
|
jopohl_urh
|
train
|
f1fb5589f5da241bbe7da554fcf99f86efe25b16
|
diff --git a/Entity/EventRepository.php b/Entity/EventRepository.php
index <HASH>..<HASH> 100644
--- a/Entity/EventRepository.php
+++ b/Entity/EventRepository.php
@@ -96,13 +96,13 @@ class EventRepository extends CommonRepository
if (!empty($options['fromDate']) && !empty($options['toDate'])) {
$query->andWhere('c.date_added BETWEEN :dateFrom AND :dateTo')
->setParameter('dateFrom', $options['fromDate']->format('Y-m-d H:i:s'))
- ->setParameter('dateTo', $options['toDate']->format('Y-m-d H:i:s'));
+ ->setParameter('dateTo', $options['toDate']->format('Y-m-d 23:59:59'));
} elseif (!empty($options['fromDate'])) {
$query->andWhere($query->expr()->gte('c.date_added', ':dateFrom'))
->setParameter('dateFrom', $options['fromDate']->format('Y-m-d H:i:s'));
} elseif (!empty($options['toDate'])) {
$query->andWhere($query->expr()->lte('c.date_added', ':dateTo'))
- ->setParameter('dateTo', $options['toDate']->format('Y-m-d H:i:s'));
+ ->setParameter('dateTo', $options['toDate']->format('Y-m-d 23:59:59'));
}
if (isset($options['order']) && !empty($options['order'])) {
|
[ENG-<I>] dateTo fix for filtering
|
TheDMSGroup_mautic-contact-client
|
train
|
827d91a9a9845cdbcb7c95e18c0c4fd48bce2cc6
|
diff --git a/docs/Valid.php b/docs/Valid.php
index <HASH>..<HASH> 100644
--- a/docs/Valid.php
+++ b/docs/Valid.php
@@ -18,7 +18,7 @@ class Valid
*
* @return Valid
*/
- public static function new(array $data): self
+ public static function create(array $data): self
{
return new static($data);
}
@@ -33,9 +33,9 @@ class Valid
$this->data = $data;
}
- public function getInt(string $field, $min = null, $max = null, $default = null): int
+ public function getInt(string $field, $min = null, $max = null, $default = 0): int
{
-
+ return 0;
}
/**
diff --git a/src/Helper.php b/src/Helper.php
index <HASH>..<HASH> 100644
--- a/src/Helper.php
+++ b/src/Helper.php
@@ -23,6 +23,7 @@ use function html_entity_decode;
use function is_array;
use function is_int;
use function is_object;
+use function is_scalar;
use function is_string;
use function mb_strlen;
use function mb_strpos;
@@ -313,4 +314,44 @@ class Helper
return $ok;
}
+
+ /**
+ * @param mixed $val
+ * @param array $list
+ *
+ * @return bool
+ */
+ public static function inArray($val, array $list): bool
+ {
+ if (!is_scalar($val)) {
+ return false;
+ }
+
+ $valType = gettype($val);
+ foreach ($list as $item) {
+ if (!is_scalar($item)) {
+ continue;
+ }
+
+ // compare value
+ switch ($valType) {
+ case 'integer':
+ $exist = $val === (int)$item;
+ break;
+ case 'float':
+ case 'double':
+ case 'string':
+ $exist = (string)$val === (string)$item;
+ break;
+ default:
+ return false;
+ }
+
+ if ($exist) {
+ return true;
+ }
+ }
+
+ return false;
+ }
}
diff --git a/src/Validator/GlobalMessage.php b/src/Validator/GlobalMessage.php
index <HASH>..<HASH> 100644
--- a/src/Validator/GlobalMessage.php
+++ b/src/Validator/GlobalMessage.php
@@ -36,6 +36,7 @@ final class GlobalMessage
'ipv4' => '{attr} is not a IPv4 address!',
'ipv6' => '{attr} is not a IPv6 address!',
'required' => 'parameter {attr} is required!',
+ 'requiredIf' => 'parameter {attr} is required!',
'length' => [
'{attr} length validation is not through!',
'{attr} must be an string/array and minimum length is {min}',
diff --git a/test/RuleValidationTest.php b/test/RuleValidationTest.php
index <HASH>..<HASH> 100644
--- a/test/RuleValidationTest.php
+++ b/test/RuleValidationTest.php
@@ -3,6 +3,7 @@
namespace Inhere\ValidateTest;
use Inhere\Validate\RuleValidation;
+use Inhere\Validate\RV;
use Inhere\Validate\Validation;
use PHPUnit\Framework\TestCase;
use PHPUnit\Runner\Version;
@@ -610,6 +611,9 @@ class RuleValidationTest extends TestCase
$this->assertEquals('list val must be an array', $v->lastError());
}
+ /**
+ * @link https://github.com/inhere/php-validate/issues/13
+ */
public function testIssue13(): void
{
$rule = [
@@ -619,7 +623,9 @@ class RuleValidationTest extends TestCase
$v = Validation::check([
'goods_id' => [
- 1144181460261978556, 114418146, 1144
+ // 1144181460261978556,
+ 114418146,
+ 1144
]
], $rule);
@@ -647,4 +653,43 @@ class RuleValidationTest extends TestCase
$this->assertFalse($v->isOk());
$this->assertSame('商品分类id必须是一串数字', $v->firstError());
}
+
+ /**
+ * @link https://github.com/inhere/php-validate/issues/21
+ */
+ public function tIssues21(): void
+ {
+ $rs = [
+ ['users.*.id', 'required'],
+ ['users.*.id', 'each', 'required'],
+ // ['users.*.id', 'each', 'string']
+ ];
+
+ $v = RV::check([
+ 'users' => [
+ ['name' => 'n1'],
+ ['name' => 'n1'],
+ ],
+ ], $rs);
+
+ $this->assertFalse($v->isOk());
+ $this->assertSame('parameter users.*.id is required!', $v->firstError());
+
+ $v = RV::check([
+ 'users' => [
+ ['name' => 'n1'],
+ ['id' => 2, 'name' => 'n1'],
+ ],
+ ], $rs);
+
+ $this->assertFalse($v->isOk());
+ $this->assertSame('', $v->firstError());
+
+ $v = RV::check([
+ 'users' => [
+ ['id' => 1, 'name' => 'n1'],
+ ['id' => 2, 'name' => 'n1'],
+ ],
+ ], $rs);
+ }
}
|
update some logic for unit tests and add new helper func
|
inhere_php-validate
|
train
|
486e78f3eef3712e194351201613362165fc158a
|
diff --git a/Command/PopulateCommand.php b/Command/PopulateCommand.php
index <HASH>..<HASH> 100644
--- a/Command/PopulateCommand.php
+++ b/Command/PopulateCommand.php
@@ -38,6 +38,7 @@ class PopulateCommand extends ContainerAwareCommand
->setName('foq:elastica:populate')
->addOption('index', null, InputOption::VALUE_OPTIONAL, 'The index to repopulate')
->addOption('type', null, InputOption::VALUE_OPTIONAL, 'The type to repopulate')
+ ->addOption('no-reset', null, InputOption::VALUE_NONE, 'If set, the indexes will not been resetted before populating.')
->setDescription('Populates search indexes from providers')
;
}
@@ -57,8 +58,9 @@ class PopulateCommand extends ContainerAwareCommand
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
- $index = $input->getOption('index');
- $type = $input->getOption('type');
+ $index = $input->getOption('index');
+ $type = $input->getOption('type');
+ $no_reset = $input->getOption('no-reset');
if (null === $index && null !== $type) {
throw new \InvalidArgumentException('Cannot specify type option without an index.');
@@ -66,9 +68,9 @@ class PopulateCommand extends ContainerAwareCommand
if (null !== $index) {
if (null !== $type) {
- $this->populateIndexType($output, $index, $type);
+ $this->populateIndexType($output, $index, $type, $no_reset);
} else {
- $this->populateIndex($output, $index);
+ $this->populateIndex($output, $index, $no_reset);
}
} else {
$indexes = array_keys($this->indexManager->getAllIndexes());
@@ -84,11 +86,14 @@ class PopulateCommand extends ContainerAwareCommand
*
* @param OutputInterface $output
* @param string $index
+ * @param boolean $no_reset
*/
- private function populateIndex(OutputInterface $output, $index)
+ private function populateIndex(OutputInterface $output, $index, $no_reset = false)
{
- $output->writeln(sprintf('Resetting: %s', $index));
- $this->resetter->resetIndex($index);
+ if ( !$no_reset ) {
+ $output->writeln(sprintf('Resetting: %s', $index));
+ $this->resetter->resetIndex($index);
+ }
$providers = $this->providerRegistry->getIndexProviders($index);
@@ -110,11 +115,14 @@ class PopulateCommand extends ContainerAwareCommand
* @param OutputInterface $output
* @param string $index
* @param string $type
+ * @param boolean $no_reset
*/
- private function populateIndexType(OutputInterface $output, $index, $type)
+ private function populateIndexType(OutputInterface $output, $index, $type, $no_reset = false)
{
- $output->writeln(sprintf('Resetting: %s/%s', $index, $type));
- $this->resetter->resetIndexType($index, $type);
+ if ( !$no_reset ) {
+ $output->writeln(sprintf('Resetting: %s/%s', $index, $type));
+ $this->resetter->resetIndexType($index, $type);
+ }
$loggerClosure = function($message) use ($output, $index, $type) {
$output->writeln(sprintf('Populating: %s/%s, %s', $index, $type, $message));
|
New Option no-reset for the populate command
|
FriendsOfSymfony_FOSElasticaBundle
|
train
|
42506158efd0418b7826195f2636dc04b6c0a834
|
diff --git a/pwkit/bblocks.py b/pwkit/bblocks.py
index <HASH>..<HASH> 100644
--- a/pwkit/bblocks.py
+++ b/pwkit/bblocks.py
@@ -244,7 +244,7 @@ def tt_bblock (tstarts, tstops, times, p0=0.05):
j = wafter[0]
else:
j = utimes.size
- assert i == 0 or np.where (utimes < tstart)[0][-1] == j - 1
+ assert j == 0 or np.where (utimes < tstart)[0][-1] == j - 1
counts = np.concatenate ((counts[:j], [0], counts[j:]))
widths = np.concatenate ((widths, [tstop - tstart]))
|
pwkit/bblocks.py: fix corner case handling bug
Reported by Maïca Clavel and collaborators of the Laboratoire AstroParticule
et Cosmologie, Université Paris Diderot. They say that the previous code will
crash if there are no events in the first two GTIs of an observation.
|
pkgw_pwkit
|
train
|
04652b73a81296c0339204b3be3f9dc7dfea67db
|
diff --git a/lib/git_org_file_scanner.rb b/lib/git_org_file_scanner.rb
index <HASH>..<HASH> 100644
--- a/lib/git_org_file_scanner.rb
+++ b/lib/git_org_file_scanner.rb
@@ -6,9 +6,10 @@ module GitOrgFileScanner
class Scanner
attr_accessor :org
- def initialize(access_token, org)
+ def initialize(access_token, org, type = 'sources')
@octokit_client = setup_client(access_token)
@org = org
+ @type = type
@org_repositories = org_repositories
end
@@ -49,7 +50,7 @@ module GitOrgFileScanner
private
def org_repositories
- @octokit_client.org_repositories(org)
+ @octokit_client.org_repositories(@org, {:type => @type})
end
def contains_file?(repo_name, file)
|
Setup the scanner to default to non-fork repos
We care less about things in forks. This also allows you to scan for public repos only, which most of the time is REALLY what we care about.
|
nellshamrell_git_org_file_scanner
|
train
|
b70d77b9133f6d6e2eae511b0c7f979242d67ffc
|
diff --git a/lib/codemirror-client.js b/lib/codemirror-client.js
index <HASH>..<HASH> 100644
--- a/lib/codemirror-client.js
+++ b/lib/codemirror-client.js
@@ -112,7 +112,24 @@ ot.CodeMirrorClient = (function () {
this.updateUserMark(user);
};
+ function cleanNoops (stack) {
+ function isNoop (operation) {
+ var ops = operation.ops;
+ return ops.length === 0 || (ops.length === 1 && !!ops[0].retain);
+ }
+
+ while (stack.length > 0) {
+ var operation = stack[stack.length - 1];
+ if (isNoop(operation)) {
+ stack.pop();
+ } else {
+ break;
+ }
+ }
+ }
+
CodeMirrorClient.prototype.unredoHelper = function (sourceStack, targetStack) {
+ cleanNoops(sourceStack);
if (sourceStack.length === 0) { return; }
var operation = sourceStack.pop();
operation.revision = this.createOperation().revision;
@@ -123,6 +140,7 @@ ot.CodeMirrorClient = (function () {
};
CodeMirrorClient.prototype.transformUnredoStack = function (stack, operation) {
+ cleanNoops(stack);
for (var i = stack.length - 1; i >= 0; i--) {
stack[i].revision = operation.revision;
var transformedPair = Operation.transform(stack[i], operation);
@@ -166,11 +184,6 @@ ot.CodeMirrorClient = (function () {
return false;
}
- /*function isNoop (operation) {
- var ops = operation.ops;
- return ops.length === 0 || (ops.length === 1 && ops[0].retain);
- }*/
-
if (this.undoStack.length === 0) {
this.undoStack.push(operation);
} else {
|
[codemirror-client] clean noops from undo stack; a noop can result from a client making one edit and another client reverting this change manually
|
Operational-Transformation_ot.js
|
train
|
ca56068e191be6ed4ec42a365f7be666bbae26d6
|
diff --git a/lib/article.js b/lib/article.js
index <HASH>..<HASH> 100644
--- a/lib/article.js
+++ b/lib/article.js
@@ -236,6 +236,6 @@ Article.prototype._end = function () {
}
this._callback(null, {
- title: articleHeader.text
+ title: articleHeader === null ? null : articleHeader.text
});
};
|
[fix] a bug when no title was found
|
AndreasMadsen_article
|
train
|
41e8ef8e82a472e6d5e4d9046708e7a45abfb7ab
|
diff --git a/salt/client/ssh/ssh_py_shim.py b/salt/client/ssh/ssh_py_shim.py
index <HASH>..<HASH> 100644
--- a/salt/client/ssh/ssh_py_shim.py
+++ b/salt/client/ssh/ssh_py_shim.py
@@ -237,7 +237,7 @@ def get_executable():
continue
c_vn = tuple([int(x) for x in stdout.split(':')])
for ns in pymap:
- if c_vn >= pymap[ns] and os.path.exists(os.path.join(OPTIONS.saltdir, ns)):
+ if c_vn[0] == pymap[ns][0] and c_vn >= pymap[ns] and os.path.exists(os.path.join(OPTIONS.saltdir, ns)):
return py_cmd
sys.exit(EX_THIN_PYTHON_INVALID)
|
require same major version while minor is allowed to be higher
|
saltstack_salt
|
train
|
a4bf541fb4d163bf597d5352e80d6c3a85604624
|
diff --git a/lib/iron_worker/api.rb b/lib/iron_worker/api.rb
index <HASH>..<HASH> 100644
--- a/lib/iron_worker/api.rb
+++ b/lib/iron_worker/api.rb
@@ -54,12 +54,15 @@ module IronWorker
@version = options[:version]
#@logger = options[:logger]
- @base_url = "#{@scheme}://#{@host}:#{@port}/#{@version}"
+ reset_base_url
@uber_client = Uber::Client.new
end
+ def reset_base_url
+ @base_url = "#{@scheme}://#{@host}:#{@port}/#{@version}"
+ end
def base_url
@base_url
@@ -77,13 +80,13 @@ module IronWorker
end
- def common_req_hash
- {
- :headers=>{"Content-Type" => 'application/json',
- "Authorization"=>"OAuth #{@token}",
- "User-Agent"=>"IronWorker Ruby Client"}
- }
- end
+ def common_req_hash
+ {
+ :headers=>{"Content-Type" => 'application/json',
+ "Authorization"=>"OAuth #{@token}",
+ "User-Agent"=>"IronWorker Ruby Client"}
+ }
+ end
def process_ex(ex)
logger.error "EX #{ex.class.name}: #{ex.message}"
diff --git a/lib/iron_worker/uber_client.rb b/lib/iron_worker/uber_client.rb
index <HASH>..<HASH> 100644
--- a/lib/iron_worker/uber_client.rb
+++ b/lib/iron_worker/uber_client.rb
@@ -107,7 +107,7 @@ module Uber
response = RestClientResponseWrapper.new(r2)
# todo: make generic exception
rescue RestClient::Exception => ex
- raise RestClientExceptionWrapper(ex)
+ raise RestClientExceptionWrapper.new(ex)
end
end
response
diff --git a/test/test_iron_worker.rb b/test/test_iron_worker.rb
index <HASH>..<HASH> 100644
--- a/test/test_iron_worker.rb
+++ b/test/test_iron_worker.rb
@@ -4,10 +4,34 @@ require_relative 'cool_model'
require_relative 'gem_dependency_worker'
require_relative 'fail_worker'
require_relative 'progress_worker'
+require_relative 'one_line_worker'
#require_relative 'workers/big_gems_worker'
class IronWorkerTests < TestBase
+ # todo: test both gems
+ #def test_rest_client
+ # Uber.gem = :rest_client
+ #
+ # worker = OneLineWorker.new
+ # worker.queue
+ #
+ # IronWorker.service.host = "http://www.wlajdfljalsjfklsldf.com/"
+ # IronWorker.service.reset_base_url
+ #
+ # status = worker.wait_until_complete
+ # p status
+ # p status["error_class"]
+ # p status["msg"]
+ # puts "\n\n\nLOG START:"
+ # log = worker.get_log
+ # puts log
+ # puts "LOG END\n\n\n"
+ # assert status["status"] == "complete", "Status was not complete, it was #{status["status"]}"
+ # Uber.gem = :typhoeus
+ #end
+
+
def test_old_gem_error_message
assert_raise do
IronWorker.config.access_key = "abc"
|
Fixed but when created rest client exception wrapper, undefined method RestClientExceptionWrapper. Didn't have .new()
|
iron-io_iron_worker_ruby
|
train
|
e8ae5376c0be81c4d38a9128ea034c422aeeb226
|
diff --git a/perspective-shell/src/main/java/org/meridor/perspective/shell/commands/EntityFormatter.java b/perspective-shell/src/main/java/org/meridor/perspective/shell/commands/EntityFormatter.java
index <HASH>..<HASH> 100644
--- a/perspective-shell/src/main/java/org/meridor/perspective/shell/commands/EntityFormatter.java
+++ b/perspective-shell/src/main/java/org/meridor/perspective/shell/commands/EntityFormatter.java
@@ -92,6 +92,7 @@ public class EntityFormatter {
i.getName(),
enumerateValues(
i.getProjectIds().stream()
+ .filter(projectsMap::containsKey)
.map(id -> projectsMap.get(id).getName())
.collect(Collectors.toList())
),
|
Fixed NPE in show images command (fixes #<I>)
|
meridor_perspective-backend
|
train
|
401fb558f7eed62ca587c6751d6b4ae1ba60ffbf
|
diff --git a/packages/NodeTypeResolver/src/NodeVisitor/MethodResolver.php b/packages/NodeTypeResolver/src/NodeVisitor/MethodResolver.php
index <HASH>..<HASH> 100644
--- a/packages/NodeTypeResolver/src/NodeVisitor/MethodResolver.php
+++ b/packages/NodeTypeResolver/src/NodeVisitor/MethodResolver.php
@@ -3,7 +3,9 @@
namespace Rector\NodeTypeResolver\NodeVisitor;
use PhpParser\Node;
+use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Stmt\ClassMethod;
+use PhpParser\Node\Stmt\Expression;
use PhpParser\NodeVisitorAbstract;
use Rector\Node\Attribute;
@@ -18,11 +20,17 @@ final class MethodResolver extends NodeVisitorAbstract
private $methodName;
/**
+ * @var string|null
+ */
+ private $methodCall;
+
+ /**
* @param Node[] $nodes
*/
public function beforeTraverse(array $nodes): void
{
$this->methodName = null;
+ $this->methodCall = null;
}
public function enterNode(Node $node): void
@@ -31,10 +39,18 @@ final class MethodResolver extends NodeVisitorAbstract
$this->methodName = $node->name->toString();
}
- if ($this->methodName === null) {
- return;
+ if ($node instanceof MethodCall) {
+ $this->methodCall = $node->name->toString();
}
$node->setAttribute(Attribute::METHOD_NAME, $this->methodName);
+ $node->setAttribute(Attribute::METHOD_CALL, $this->methodCall);
+ }
+
+ public function leaveNode(Node $node): void
+ {
+ if ($node instanceof Expression) {
+ $this->methodCall = null;
+ }
}
}
diff --git a/src/Node/Attribute.php b/src/Node/Attribute.php
index <HASH>..<HASH> 100644
--- a/src/Node/Attribute.php
+++ b/src/Node/Attribute.php
@@ -88,4 +88,9 @@ final class Attribute
* @var string
*/
public const NAMESPACE = 'namespace';
+
+ /**
+ * @var string
+ */
+ public const METHOD_CALL = 'methodCall';
}
diff --git a/src/Rector/Contrib/Symfony/Form/StringFormTypeToClassRector.php b/src/Rector/Contrib/Symfony/Form/StringFormTypeToClassRector.php
index <HASH>..<HASH> 100644
--- a/src/Rector/Contrib/Symfony/Form/StringFormTypeToClassRector.php
+++ b/src/Rector/Contrib/Symfony/Form/StringFormTypeToClassRector.php
@@ -3,8 +3,6 @@
namespace Rector\Rector\Contrib\Symfony\Form;
use PhpParser\Node;
-use PhpParser\Node\Arg;
-use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Scalar\String_;
use Rector\Node\Attribute;
use Rector\Node\NodeFactory;
@@ -48,17 +46,9 @@ final class StringFormTypeToClassRector extends AbstractRector
return false;
}
- $argNode = $node->getAttribute(Attribute::PARENT_NODE);
- if (! $argNode instanceof Arg) {
- return false;
- }
-
- $methodCallNode = $argNode->getAttribute(Attribute::PARENT_NODE);
- if (! $methodCallNode instanceof MethodCall) {
- return false;
- }
+ $methodCallName = (string) $node->getAttribute(Attribute::METHOD_CALL);
- return $methodCallNode->name->toString() === 'add';
+ return $methodCallName === 'add';
}
/**
|
add METHOD_CALL to MethodResolver
|
rectorphp_rector
|
train
|
cb17b6a60015902297cc2a2fe27fea4ac23ce542
|
diff --git a/compiler/prelude.go b/compiler/prelude.go
index <HASH>..<HASH> 100644
--- a/compiler/prelude.go
+++ b/compiler/prelude.go
@@ -955,7 +955,7 @@ var $externalize = function(v, t) {
}
args.push($internalize(arguments[i], t.params[i]));
}
- var result = v.apply(undefined, args);
+ var result = v.apply(this, args);
switch (t.results.length) {
case 0:
return;
diff --git a/js/js_test.go b/js/js_test.go
index <HASH>..<HASH> 100644
--- a/js/js_test.go
+++ b/js/js_test.go
@@ -213,12 +213,12 @@ func TestEquality(t *testing.T) {
}
func TestThis(t *testing.T) {
- dummys.Set("testThis", func() {
+ dummys.Set("testThis", func(_ string) { // string argument to force wrapping
if js.This != dummys {
t.Fail()
}
})
- dummys.Call("testThis")
+ dummys.Call("testThis", "")
}
func TestArguments(t *testing.T) {
|
preserve "this" when externalising functions
|
gopherjs_gopherjs
|
train
|
ce0e5380684fd593e2839ad1d954e1218224246c
|
diff --git a/spacy/gold.pyx b/spacy/gold.pyx
index <HASH>..<HASH> 100644
--- a/spacy/gold.pyx
+++ b/spacy/gold.pyx
@@ -834,7 +834,7 @@ cdef class Example:
if merge:
t = self.token_annotation
doc = self.doc
- if not self.doc:
+ if self.doc is None:
if not vocab:
raise ValueError(Errors.E998)
doc = Doc(vocab, words=t.words)
@@ -993,7 +993,10 @@ cdef class GoldParse:
self.links = {} if links is None else dict(links)
# avoid allocating memory if the doc does not contain any tokens
- if self.length > 0:
+ if self.length == 0:
+ # set a minimal orig so that the scorer can score an empty doc
+ self.orig = TokenAnnotation(ids=[])
+ else:
if not words:
words = [token.text for token in doc]
if not tags:
diff --git a/spacy/tests/regression/test_issue4924.py b/spacy/tests/regression/test_issue4924.py
index <HASH>..<HASH> 100644
--- a/spacy/tests/regression/test_issue4924.py
+++ b/spacy/tests/regression/test_issue4924.py
@@ -5,5 +5,4 @@ from spacy.language import Language
def test_issue4924():
nlp = Language()
docs_golds = [("", {})]
- with pytest.raises(ValueError):
- nlp.evaluate(docs_golds)
+ nlp.evaluate(docs_golds)
diff --git a/spacy/tests/test_gold.py b/spacy/tests/test_gold.py
index <HASH>..<HASH> 100644
--- a/spacy/tests/test_gold.py
+++ b/spacy/tests/test_gold.py
@@ -480,3 +480,10 @@ def test_tuples_to_example(merged_dict):
assert ex_dict["token_annotation"]["tags"] == merged_dict["tags"]
assert ex_dict["token_annotation"]["sent_starts"] == merged_dict["sent_starts"]
assert ex_dict["doc_annotation"]["cats"] == cats
+
+
+def test_empty_example_goldparse():
+ nlp = English()
+ doc = nlp("")
+ example = Example(doc=doc)
+ assert len(example.get_gold_parses()) == 1
|
Check whether doc is instantiated in Example.get_gold_parses() (#<I>)
* Check whether doc is instantiated
When creating docs to pair with gold parses, modify test to check
whether a doc is unset rather than whether it contains tokens.
* Restore test of evaluate on an empty doc
* Set a minimal gold.orig for the scorer
Without a minimal gold.orig the scorer can't evaluate empty docs. This
is the v3 equivalent of #<I>.
|
explosion_spaCy
|
train
|
40c90bbcc76291c589fc50f375b51bb80746a322
|
diff --git a/src/blocks/scratch3_event.js b/src/blocks/scratch3_event.js
index <HASH>..<HASH> 100644
--- a/src/blocks/scratch3_event.js
+++ b/src/blocks/scratch3_event.js
@@ -71,14 +71,10 @@ Scratch3EventBlocks.prototype.broadcastAndWait = function (args, util) {
}
}
// We've run before; check if the wait is still going on.
- var waiting = false;
- for (var i = 0; i < util.stackFrame.triggeredThreads.length; i++) {
- var thread = util.stackFrame.triggeredThreads[i];
- var activeThreads = this.runtime.threads;
- if (activeThreads.indexOf(thread) > -1) { // @todo: A cleaner way?
- waiting = true;
- }
- }
+ var instance = this;
+ var waiting = util.stackFrame.triggeredThreads.some(function(thread) {
+ return instance.runtime.isActiveThread(thread);
+ });
if (waiting) {
util.yieldFrame();
}
diff --git a/src/engine/runtime.js b/src/engine/runtime.js
index <HASH>..<HASH> 100644
--- a/src/engine/runtime.js
+++ b/src/engine/runtime.js
@@ -212,6 +212,15 @@ Runtime.prototype._removeThread = function (thread) {
};
/**
+ * Return whether a thread is currently active/running.
+ * @param {?Thread} thread Thread object to check.
+ * @return {Boolean} True if the thread is active/running.
+ */
+Runtime.prototype.isActiveThread = function (thread) {
+ return this.threads.indexOf(thread) > -1;
+};
+
+/**
* Toggle a script.
* @param {!string} topBlockId ID of block that starts the script.
*/
|
Add `isActiveThread` and simplify broadcast-and-wait accordingly
|
LLK_scratch-vm
|
train
|
f33aa9c94557e634e72caf868872d7d8662cc24a
|
diff --git a/neurom/core/__init__.py b/neurom/core/__init__.py
index <HASH>..<HASH> 100644
--- a/neurom/core/__init__.py
+++ b/neurom/core/__init__.py
@@ -30,7 +30,6 @@
from .tree import i_chain2 as _chain_neurites
from .tree import Tree as _Tree
-from .types import NeuriteType
def iter_neurites(obj, mapfun=None, filt=None):
diff --git a/neurom/core/section_neuron.py b/neurom/core/section_neuron.py
index <HASH>..<HASH> 100644
--- a/neurom/core/section_neuron.py
+++ b/neurom/core/section_neuron.py
@@ -33,7 +33,7 @@ from collections import defaultdict
from collections import namedtuple
import numpy as np
from neurom.io.hdf5 import H5
-from neurom.core import NeuriteType
+from neurom.core.types import NeuriteType
from neurom.core.tree import Tree, ipreorder, ibifurcation_point
from neurom.core.types import tree_type_checker as is_type
from neurom.core.dataformat import POINT_TYPE
|
Remove import of core.types.NeuriteTypes in core.__init__.py
This import was causing problems in setup.py, which is run before
the Enum<I> package has been installed.
|
BlueBrain_NeuroM
|
train
|
24bcac42be0e2fbac621baf8f753ef2e6c1eb68d
|
diff --git a/builtin/providers/aws/resource_aws_eip.go b/builtin/providers/aws/resource_aws_eip.go
index <HASH>..<HASH> 100644
--- a/builtin/providers/aws/resource_aws_eip.go
+++ b/builtin/providers/aws/resource_aws_eip.go
@@ -208,8 +208,20 @@ func resourceAwsEipUpdate(d *schema.ResourceData, meta interface{}) error {
}
}
- log.Printf("[DEBUG] EIP associate configuration: %#v (domain: %v)", assocOpts, domain)
- _, err := ec2conn.AssociateAddress(assocOpts)
+ log.Printf("[DEBUG] EIP associate configuration: %s (domain: %s)", assocOpts, domain)
+
+ err := resource.Retry(1*time.Minute, func() *resource.RetryError {
+ _, err := ec2conn.AssociateAddress(assocOpts)
+ if err != nil {
+ if awsErr, ok := err.(awserr.Error); ok {
+ if awsErr.Code() == "InvalidAllocationID.NotFound" {
+ return resource.RetryableError(awsErr)
+ }
+ }
+ return resource.NonRetryableError(err)
+ }
+ return nil
+ })
if err != nil {
// Prevent saving instance if association failed
// e.g. missing internet gateway in VPC
|
provider/aws: Retry EIP association (#<I>)
|
hashicorp_terraform
|
train
|
be0cba7a4a2bdf42f238e2d438c2014f0f57482d
|
diff --git a/MAVProxy/modules/mavproxy_asterix.py b/MAVProxy/modules/mavproxy_asterix.py
index <HASH>..<HASH> 100644
--- a/MAVProxy/modules/mavproxy_asterix.py
+++ b/MAVProxy/modules/mavproxy_asterix.py
@@ -148,7 +148,10 @@ class AsterixModule(mp_module.MPModule):
self.tracks[icao_address] = Track(adsb_pkt)
if self.asterix_settings.debug > 0:
print(adsb_pkt)
- self.master.mav.send(adsb_pkt)
+ # send on all links
+ for i in range(len(self.mpstate.mav_master)):
+ conn = self.mpstate.mav_master[i]
+ conn.mav.send(adsb_pkt)
adsb_mod = self.module('adsb')
if adsb_mod:
# the adsb module is loaded, display on the map
diff --git a/MAVProxy/modules/mavproxy_genobstacles.py b/MAVProxy/modules/mavproxy_genobstacles.py
index <HASH>..<HASH> 100644
--- a/MAVProxy/modules/mavproxy_genobstacles.py
+++ b/MAVProxy/modules/mavproxy_genobstacles.py
@@ -254,6 +254,7 @@ class GenobstaclesModule(mp_module.MPModule):
self.last_t = 0
self.start()
self.menu_added_map = False
+ self.pkt_queue = []
if mp_util.has_wxpython:
self.menu = MPMenuSubMenu('Obstacles',
items=[MPMenuItem('Restart', 'Restart', '# genobstacles restart'),
@@ -350,6 +351,14 @@ class GenobstaclesModule(mp_module.MPModule):
self.sock.close()
self.sock = None
+ def idle_task(self):
+ while len(self.pkt_queue) > 0:
+ try:
+ self.sock.send(self.pkt_queue[0])
+ self.pkt_queue.pop(0)
+ except Exception as ex:
+ return
+
def mavlink_packet(self, m):
'''trigger sends from ATTITUDE packets'''
if m.get_type() != 'ATTITUDE':
@@ -365,10 +374,10 @@ class GenobstaclesModule(mp_module.MPModule):
for a in self.aircraft:
if not gen_settings.stop:
a.update(1.0)
- try:
- self.sock.send(a.pickled())
- except Exception as ex:
- pass
+ self.pkt_queue.append(a.pickled())
+ while len(self.pkt_queue) > len(self.aircraft)*2:
+ self.pkt_queue.pop(0)
+
if self.module('map') is not None and not self.menu_added_map:
self.menu_added_map = True
self.module('map').add_menu(self.menu)
|
asterix: send pkts to all links
|
ArduPilot_MAVProxy
|
train
|
8199602c94146777aa0d8476f14aac62f92e4ca6
|
diff --git a/src/createLambdaProxyContext.js b/src/createLambdaProxyContext.js
index <HASH>..<HASH> 100644
--- a/src/createLambdaProxyContext.js
+++ b/src/createLambdaProxyContext.js
@@ -60,7 +60,11 @@ module.exports = function createLambdaProxyContext(request, options, stageVariab
let claims;
if (token) {
- claims = jwt.decode(token) || undefined;
+ try {
+ claims = jwt.decode(token) || undefined;
+ } catch (err) {
+ // Do nothing
+ }
}
return {
|
Prevent uncaught error with invalid token
Should an invalid token be passed in the headers, the handler fails with an uncaught error. The error should be ignored instead.
|
dherault_serverless-offline
|
train
|
12bc32dcd060f9178aa118cd7a795f7ed7266df5
|
diff --git a/manifest.php b/manifest.php
index <HASH>..<HASH> 100755
--- a/manifest.php
+++ b/manifest.php
@@ -27,7 +27,7 @@ return array(
'version' => '2.1.2',
'author' => 'Open Assessment Technologies SA',
'requires' => array(
- 'tao' => '>=3.5.0',
+ 'tao' => '>=7.0.0',
'taoItems' => '*',
'taoTests' => '*',
'taoMediaManager' => '*'
|
Updated tao fs support required
|
oat-sa_extension-tao-revision
|
train
|
ce9967808ff13e4826d194a4945ce1136b76c1cb
|
diff --git a/cdmbriefparser.py b/cdmbriefparser.py
index <HASH>..<HASH> 100644
--- a/cdmbriefparser.py
+++ b/cdmbriefparser.py
@@ -53,9 +53,9 @@ def trim_docstring( docstring ):
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[ -1 ]:
- trimmed.pop()
+ del trimmed[ -1 ]
while trimmed and not trimmed[ 0 ]:
- trimmed.pop( 0 )
+ del trimmed[ 0 ]
# Return a single string:
return '\n'.join( trimmed )
|
del is faster than list.pop()
|
SergeySatskiy_cdm-pythonparser
|
train
|
70e0e38783a7c2d9b330aa0beb85d7f900cf3e13
|
diff --git a/healthcheck/__init__.py b/healthcheck/__init__.py
index <HASH>..<HASH> 100644
--- a/healthcheck/__init__.py
+++ b/healthcheck/__init__.py
@@ -95,8 +95,8 @@ class HealthCheck(object):
results.append(result)
- fn = lambda result, passed: passed and (result.get('passed') or result.get('skipped'))
- passed = reduce(fn, results)
+ fn = lambda passed, result: passed and (result.get('passed') or result.get('skipped'))
+ passed = reduce(fn, results, True)
if passed:
message = "OK"
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, find_packages
setup(name='healthcheck',
- version='0.1.2',
+ version='0.1.3',
description='Adds healthcheck endpoints to Flask apps',
author='Frank Stratton',
author_email='frank@runscope.com',
|
Fix healthcheck when there aren't any check functions defined
|
ateliedocodigo_py-healthcheck
|
train
|
64ca4a902f5922532f040889c64e1b62a117ffb4
|
diff --git a/parler/models.py b/parler/models.py
index <HASH>..<HASH> 100644
--- a/parler/models.py
+++ b/parler/models.py
@@ -221,7 +221,11 @@ class TranslatableModel(models.Model):
Return the language codes of all translated variations.
"""
accessor = getattr(self, self._translations_field)
- qs = accessor.get_queryset()
+ try:
+ qs = accessor.get_queryset()
+ except AttributeError:
+ # Fallback for Django 1.4 and Django 1.5
+ qs = accessor.get_query_set()
if qs._prefetch_done:
return sorted(obj.language_code for obj in qs)
else:
@@ -252,7 +256,11 @@ class TranslatableModel(models.Model):
if not self._state.adding and self.pk:
# 2.1, use prefetched data
accessor = getattr(self, self._translations_field)
- qs = accessor.get_queryset()
+ try:
+ qs = accessor.get_queryset()
+ except AttributeError:
+ # Fallback for Django 1.4 and Django 1.5
+ qs = accessor.get_query_set()
if qs._prefetch_done:
for object in qs:
if object.language_code == language_code:
@@ -332,7 +340,11 @@ class TranslatableModel(models.Model):
try:
accessor = getattr(self, self._translations_field)
- qs = accessor.get_queryset()
+ try:
+ qs = accessor.get_queryset()
+ except AttributeError:
+ # Fallback for Django 1.4 and Django 1.5
+ qs = accessor.get_query_set()
if qs._prefetch_done:
translation = list(qs)[0]
else:
|
Fix prefetched translations for Django <I> and Django <I>
|
django-parler_django-parler
|
train
|
59c8076367c346465844d6abc28f4b189e2960c3
|
diff --git a/test/server.py b/test/server.py
index <HASH>..<HASH> 100644
--- a/test/server.py
+++ b/test/server.py
@@ -5,13 +5,19 @@ import urlparse
import urllib
def test():
+ sv_url = 'http://id.server.url/'
+ id_url = 'http://foo.com/'
+ rt_url = 'http://return.to/'
+
store = _memstore.MemoryStore()
- s = server.OpenIDServer('http://id.server.url/', store)
+ s = server.OpenIDServer(sv_url, store)
+ # The only thing tested so far is the failure case of
+ # checkid_immediate in dumb mode.
args = {
'openid.mode': 'checkid_immediate',
- 'openid.identity': 'http://foo.com/',
- 'openid.return_to': 'http://return.to/',
+ 'openid.identity': id_url,
+ 'openid.return_to': rt_url,
}
fail = lambda i, r: 0
@@ -19,17 +25,16 @@ def test():
assert status == server.REDIRECT, status
- expected = 'http://return.to/?openid.mode=id_res&openid.user_setup_url='
+ expected = rt_url + '?openid.mode=id_res&openid.user_setup_url='
eargs = [
- ('openid.identity', 'http://foo.com/'),
+ ('openid.identity', id_url),
('openid.mode', 'checkid_setup'),
- ('openid.return_to', 'http://return.to/'),
+ ('openid.return_to', rt_url),
]
- expected += urllib.quote_plus('http://id.server.url/?' + urllib.urlencode(eargs))
-
+ expected += urllib.quote_plus(sv_url + '?' + urllib.urlencode(eargs))
+
assert info == expected, (info, expected)
-
if __name__ == '__main__':
test()
|
[project @ Clean up server test a bit]
|
necaris_python3-openid
|
train
|
da4b4bfc5d96305f55e8e1e692780b8e93d725ee
|
diff --git a/aws/resource_aws_glue_crawler_test.go b/aws/resource_aws_glue_crawler_test.go
index <HASH>..<HASH> 100644
--- a/aws/resource_aws_glue_crawler_test.go
+++ b/aws/resource_aws_glue_crawler_test.go
@@ -1762,7 +1762,7 @@ resource "aws_glue_connection" "test" {
connection_type = "NETWORK"
- name = "%s"
+ name = "%[1]s"
physical_connection_requirements {
availability_zone = aws_subnet.test[0].availability_zone
@@ -1783,7 +1783,7 @@ resource "aws_glue_crawler" "test" {
path = "s3://bucket1"
}
}
-`, rName, rName)
+`, rName)
}
func testAccGlueCrawlerConfig_S3Target_Exclusions2(rName, exclusion1, exclusion2 string) string {
|
f/aws_glue_crawler:support for s3_target connection_name
|
terraform-providers_terraform-provider-aws
|
train
|
576ec3582370fa627b06dcbe4fa384d82cda6048
|
diff --git a/classes/core_mysql.php b/classes/core_mysql.php
index <HASH>..<HASH> 100644
--- a/classes/core_mysql.php
+++ b/classes/core_mysql.php
@@ -86,7 +86,7 @@ class core_mysql
}
else
{
- if ($params == true) {
+ if ($params === true) {
$resulting[] = @mysql_fetch_array($this->result,MYSQL_ASSOC);
} elseif ($params['item']) {
$item = $params['item'];
|
Making sure that the system runs a type check on true.
|
dark-prospect-games_obsidian-moon-engine
|
train
|
3a0e394fe24a24b15142105a9aa6f9495af86515
|
diff --git a/class.form.php b/class.form.php
index <HASH>..<HASH> 100644
--- a/class.form.php
+++ b/class.form.php
@@ -852,7 +852,7 @@ class form extends base {
$str = "";
if(empty($this->referenceValues) && !empty($_SESSION["pfbc-values"]) && array_key_exists($this->attributes["id"], $_SESSION["pfbc-values"]))
- $this->setReferenceValues($_SESSION["pfbc-values"][$this->attributes["id"]]);
+ $this->setValues($_SESSION["pfbc-values"][$this->attributes["id"]]);
//If windows normalize backslashes to forward slashes.
if( PHP_OS == 'WINNT' )
@@ -1702,7 +1702,12 @@ STR;
return $content;
}
+ //This function is identical to setValues() and is included for backwards compatibility.
public function setReferenceValues($params) {
+ $this->setValues($params);
+ }
+
+ public function setValues($params) {
$this->referenceValues = $params;
}
|
Added setValues() function which is identical in functionality to
setReferenceValues(). It's shorter and easier to remember.
setReferenceValues() will be retained for backwards compatibility.
git-svn-id: <URL>
|
lkorth_php-form-builder-class
|
train
|
c1f8dc9bec7c0a58fc53fb56fd47d4de373e7bc1
|
diff --git a/lib/axlsx/drawing/one_cell_anchor.rb b/lib/axlsx/drawing/one_cell_anchor.rb
index <HASH>..<HASH> 100644
--- a/lib/axlsx/drawing/one_cell_anchor.rb
+++ b/lib/axlsx/drawing/one_cell_anchor.rb
@@ -7,7 +7,7 @@ module Axlsx
class OneCellAnchor
include Axlsx::OptionsParser
-
+
# Creates a new OneCellAnchor object and an Pic associated with it.
# @param [Drawing] drawing
# @option options [Array] start_at the col, row to start at
@@ -23,6 +23,7 @@ module Axlsx
drawing.anchors << self
@from = Marker.new
parse_options options
+ start_at(*options[:start_at]) if options[:start_at]
@object = Pic.new(self, options)
end
|
fix(options): fix parsing for start_at end_at
|
randym_axlsx
|
train
|
c32d556b8ce08a70262be56672874a95b8057e19
|
diff --git a/lib/travis/github/services/fetch_config.rb b/lib/travis/github/services/fetch_config.rb
index <HASH>..<HASH> 100644
--- a/lib/travis/github/services/fetch_config.rb
+++ b/lib/travis/github/services/fetch_config.rb
@@ -63,7 +63,7 @@ module Travis
def retrying(times)
count, result = 0, nil
- until result || count > 3
+ until result || count > times
result = yield
count += 1
Travis.logger.warn("[request:fetch_config] Retrying to fetch config for #{config_url}") unless result
|
Changed function to use variable times instead of using static number
|
travis-ci_travis-core
|
train
|
7d9092d8d910302d7ab5b8b190a68b21b46d7790
|
diff --git a/lib/anorexic/rack_server.rb b/lib/anorexic/rack_server.rb
index <HASH>..<HASH> 100644
--- a/lib/anorexic/rack_server.rb
+++ b/lib/anorexic/rack_server.rb
@@ -95,7 +95,7 @@ module Anorexic
options[:middleware].push *Anorexic.default_middleware
options[:middleware].unshift [Rack::ContentLength] unless options[:middleware].include? [Rack::ContentLength]
- options[:middleware].unshift [Anorexic::AnoRack::ReEncoder]
+ options[:middleware].unshift [Anorexic::AnoRack::ReEncoder, ::Anorexic.default_content_type]
if options[:debug]
options[:middleware].unshift [Rack::ShowExceptions, options[:file_root]]
diff --git a/lib/anorexic/rack_server_middleware.rb b/lib/anorexic/rack_server_middleware.rb
index <HASH>..<HASH> 100644
--- a/lib/anorexic/rack_server_middleware.rb
+++ b/lib/anorexic/rack_server_middleware.rb
@@ -33,7 +33,7 @@ module Anorexic
end
- # Middleware to redirect 404 not found errors to the local 404.html file
+ # Middleware to report 404 not found errors or render the local 404.haml / 404.html file
class NotFound
def initialize app, root = nil
@root = (root == false) || ::File.expand_path(File.join(Dir.pwd , 'public') )
@@ -66,7 +66,7 @@ module Anorexic
end
end
- # Middleware to redirect exception errors to the local 500.html file
+ # Middleware to report internal errors or render the local 500.haml / 500.html file
class Exceptions
def initialize app, root = nil
@root = (root == false) || ::File.expand_path(File.join(Dir.pwd , 'public') )
@@ -105,7 +105,7 @@ module Anorexic
end
# Serve the index file in a folder
- # This was written because the :index option in Rack::Static is broken.
+ # This was written because the :index option in Rack::Static breaks the code.
class ServeIndex
def initialize app, root, index_file = 'index.html'
@index_name = index_file
diff --git a/lib/anorexic/version.rb b/lib/anorexic/version.rb
index <HASH>..<HASH> 100644
--- a/lib/anorexic/version.rb
+++ b/lib/anorexic/version.rb
@@ -1,3 +1,3 @@
module Anorexic
- VERSION = "0.2.1"
+ VERSION = "0.3.0"
end
|
v. bump for re-written code base (RackServer)
|
boazsegev_plezi
|
train
|
1905294afb6af3cf69b8098ba1ff30c1f85eaf5b
|
diff --git a/src/Controller/Component/FilterComponent.php b/src/Controller/Component/FilterComponent.php
index <HASH>..<HASH> 100644
--- a/src/Controller/Component/FilterComponent.php
+++ b/src/Controller/Component/FilterComponent.php
@@ -260,18 +260,20 @@ class FilterComponent extends Component
} else {
$slug = $filter->slug;
}
- $sort = array_keys($this->activeSort)[0];
- $useDefaultSort = ($this->defaultSort['field'] === $sort && $this->activeSort[$sort] === $this->defaultSort['dir']);
$url = [
'action' => $this->action,
'sluggedFilter' => $slug
];
- if (!$useDefaultSort) {
- $url['?'] = [
- 's' => $sort
- ];
- if (!isset($this->sortFields[$sort]['custom'])) {
- $url['?']['d'] = $this->activeSort[$sort];
+ if ($this->_sortEnabled) {
+ $sort = array_keys($this->activeSort)[0];
+ $useDefaultSort = ($this->defaultSort['field'] === $sort && $this->activeSort[$sort] === $this->defaultSort['dir']);
+ if (!$useDefaultSort) {
+ $url['?'] = [
+ 's' => $sort
+ ];
+ if (!isset($this->sortFields[$sort]['custom'])) {
+ $url['?']['d'] = $this->activeSort[$sort];
+ }
}
}
$this->controller->redirect($url);
@@ -494,9 +496,7 @@ class FilterComponent extends Component
*/
protected function _initFilterOptions()
{
- if ((empty($this->request->query) && empty($this->defaultSort)) ||
- (empty($this->filterFields) && empty($this->sortFields))
- ) {
+ if (!$this->_filterEnabled && !$this->_sortEnabled) {
return;
}
|
allow either filtering or sorting and not require both to be configured
|
frankfoerster_cakephp-filter
|
train
|
765c87edcc79857a904987fed61ff0cab5fd9b1f
|
diff --git a/lib/rollbar/delay/delayed_job.rb b/lib/rollbar/delay/delayed_job.rb
index <HASH>..<HASH> 100644
--- a/lib/rollbar/delay/delayed_job.rb
+++ b/lib/rollbar/delay/delayed_job.rb
@@ -1,5 +1,7 @@
module Rollbar
module Delay
+ # This class provides the DelayedJob async handler. Users can
+ # use DelayedJob in order to send the reports to the Rollbar API
class DelayedJob
class << self
def call(payload)
|
Add class docs for DelayedJob async handler
|
rollbar_rollbar-gem
|
train
|
c66f7596bb7bbafa4dfef8e3678d76264858ed8c
|
diff --git a/lib/backend/connection.js b/lib/backend/connection.js
index <HASH>..<HASH> 100644
--- a/lib/backend/connection.js
+++ b/lib/backend/connection.js
@@ -136,7 +136,7 @@ Connection.prototype.emitMessage = function(type, body, callback, options) {
}
}).bind(this), options.timeout);
}
- this._sender.emit('message', envelope);
+ this._sender.emit('message', envelope, options.emittedCallback);
return envelope;
};
|
Accept event emitted callback
It will be used in tests to remove .wait().
|
droonga_express-droonga
|
train
|
e0ff0e79a9ab4421705a5bfbe1c7dc092c0132f9
|
diff --git a/lib/revalidator.js b/lib/revalidator.js
index <HASH>..<HASH> 100644
--- a/lib/revalidator.js
+++ b/lib/revalidator.js
@@ -406,4 +406,4 @@
}
-})(module.exports);
+})(typeof module === 'object' && module && module.exports ? module.exports : window);
|
Update the exports line to work in node.js, browser and browserify
Also make the validate function available in window instead of window.json (inline with revalidator documentation)
|
flatiron_revalidator
|
train
|
89043e4a294476cce4dc94b57cc681cb42f22cb2
|
diff --git a/pyrax/cf_wrapper/client.py b/pyrax/cf_wrapper/client.py
index <HASH>..<HASH> 100644
--- a/pyrax/cf_wrapper/client.py
+++ b/pyrax/cf_wrapper/client.py
@@ -283,22 +283,6 @@ class Client(object):
return True
- @handle_swiftclient_exception
- def purge_cdn_object(self, container, name, email_addresses=[]):
- ct = self.get_container(container)
- oname = self._resolve_name(name)
- if not ct.cdn_enabled:
- raise exc.NotCDNEnabled("The object '%s' is not in a CDN-enabled container." % oname)
- hdrs = {}
- if email_addresses:
- if not isinstance(email_addresses, (list, tuple)):
- email_addresses = [email_addresses]
- emls = ", ".join(email_addresses)
- hdrs = {"X-Purge-Email": emls}
- self.connection.cdn_request("DELETE", ct.name, oname, hdrs=hdrs)
- return True
-
-
def get_object(self, container, obj_name):
"""Returns a StorageObject instance for the object in the container."""
cont = self.get_container(container)
@@ -562,12 +546,6 @@ class Client(object):
return (hdrs["x-account-container-count"], hdrs["x-account-bytes-used"])
- def get_container_streaming_uri(self, container):
- """Returns the URI for streaming content, or None if CDN is not enabled."""
- cont = self.get_container(container)
- return cont.cdn_streaming_uri
-
-
@handle_swiftclient_exception
def list_containers(self, limit=None, marker=None, **parms):
"""Returns a list of all container names as strings."""
@@ -642,6 +620,12 @@ class Client(object):
ct.cdn_log_retention = enabled
+ def get_container_streaming_uri(self, container):
+ """Returns the URI for streaming content, or None if CDN is not enabled."""
+ cont = self.get_container(container)
+ return cont.cdn_streaming_uri
+
+
def set_container_web_index_page(self, container, page):
"""
Sets the header indicating the index page in a container
@@ -666,6 +650,22 @@ class Client(object):
return self.set_container_metadata(container, hdr, clear=False)
+ @handle_swiftclient_exception
+ def purge_cdn_object(self, container, name, email_addresses=[]):
+ ct = self.get_container(container)
+ oname = self._resolve_name(name)
+ if not ct.cdn_enabled:
+ raise exc.NotCDNEnabled("The object '%s' is not in a CDN-enabled container." % oname)
+ hdrs = {}
+ if email_addresses:
+ if not isinstance(email_addresses, (list, tuple)):
+ email_addresses = [email_addresses]
+ emls = ", ".join(email_addresses)
+ hdrs = {"X-Purge-Email": emls}
+ self.connection.cdn_request("DELETE", ct.name, oname, hdrs=hdrs)
+ return True
+
+
def _get_user_agent(self):
return self.connection.user_agent
|
Reorganized some of the client code. No logic changes.
|
pycontribs_pyrax
|
train
|
c22ce1a12cc1ad75d50696321a96bd2f1d9a7e86
|
diff --git a/src/_pytest/python.py b/src/_pytest/python.py
index <HASH>..<HASH> 100644
--- a/src/_pytest/python.py
+++ b/src/_pytest/python.py
@@ -1162,7 +1162,8 @@ def _idval(val, argname, idx, idfn, item, config):
return ascii_escaped(val.pattern)
elif isinstance(val, enum.Enum):
return str(val)
- elif (inspect.isclass(val) or inspect.isfunction(val)) and hasattr(val, "__name__"):
+ elif hasattr(val, "__name__") and isinstance(val.__name__, str):
+ # name of a class, function, module, etc.
return val.__name__
return str(argname) + str(idx)
|
parametrize: allow __name__ id for modules or other objects as well
|
pytest-dev_pytest
|
train
|
b9b2b9561089cc0e39ffe4b75bd30d0b6bea1a33
|
diff --git a/nion/swift/model/DisplayItem.py b/nion/swift/model/DisplayItem.py
index <HASH>..<HASH> 100755
--- a/nion/swift/model/DisplayItem.py
+++ b/nion/swift/model/DisplayItem.py
@@ -1423,14 +1423,7 @@ class DisplayItem(Observable.Observable, Persistence.PersistentObject):
self.insert_display_layer(before_index, **display_layer_copy)
self.__auto_display_legend()
- def populate_display_layers(self) -> None:
- if len(self.display_layers) == 0:
- # create basic display layers here
- while len(self.display_layers) < len(self.display_data_channels):
- self.__add_display_layer_auto(dict(), len(self.display_layers))
-
def append_display_data_channel_for_data_item(self, data_item: DataItem.DataItem) -> None:
- self.populate_display_layers()
if not data_item in self.data_items:
display_data_channel = DisplayDataChannel(data_item)
self.append_display_data_channel(display_data_channel, display_layer=dict())
diff --git a/nion/swift/test/DisplayItem_test.py b/nion/swift/test/DisplayItem_test.py
index <HASH>..<HASH> 100644
--- a/nion/swift/test/DisplayItem_test.py
+++ b/nion/swift/test/DisplayItem_test.py
@@ -195,8 +195,7 @@ class TestDisplayItemClass(unittest.TestCase):
document_model.append_data_item(data_item)
document_model.append_data_item(data_item2)
display_item = document_model.get_display_item_for_data_item(data_item)
- display_item.remove_display_layer(0)
- self.assertEqual(0, len(display_item.display_layers))
+ self.assertEqual(1, len(display_item.display_layers))
display_item.append_display_data_channel_for_data_item(data_item2)
self.assertEqual(2, len(display_item.display_layers))
self.assertIn("data_index", display_item.display_layers[0])
|
Remove special case of populating display layers.
|
nion-software_nionswift
|
train
|
9d8eb3f645d77297c7b0c854ef9d1ff2b9ca592a
|
diff --git a/automat/_methodical.py b/automat/_methodical.py
index <HASH>..<HASH> 100644
--- a/automat/_methodical.py
+++ b/automat/_methodical.py
@@ -91,7 +91,7 @@ class MethodicalState(object):
method = attr.ib()
serialized = attr.ib(repr=False)
- def upon(self, input, enter, outputs, collector=list):
+ def upon(self, input, enter=None, outputs=None, collector=list):
"""
Declare a state transition within the :class:`automat.MethodicalMachine`
associated with this :class:`automat.MethodicalState`:
@@ -110,6 +110,10 @@ class MethodicalState(object):
:raises ValueError: if the state transition from `self` via `input`
has already been defined.
"""
+ if enter is None:
+ enter = self
+ if outputs is None:
+ outputs = []
inputArgs = _getArgNames(input.argSpec)
for output in outputs:
outputArgs = _getArgNames(output.argSpec)
diff --git a/automat/_test/test_methodical.py b/automat/_test/test_methodical.py
index <HASH>..<HASH> 100644
--- a/automat/_test/test_methodical.py
+++ b/automat/_test/test_methodical.py
@@ -365,6 +365,50 @@ class MethodicalTests(TestCase):
self.assertIn("nameOfInput", str(cm.exception))
self.assertIn("outputThatDoesntMatch", str(cm.exception))
+ def test_stateLoop(self):
+ """
+ It is possible to write a self-loop by omitting "enter"
+ """
+ class Mechanism(object):
+ m = MethodicalMachine()
+ @m.input()
+ def input(self):
+ "an input"
+ @m.input()
+ def say_hi(self):
+ "an input"
+ @m.output()
+ def _start_say_hi(self):
+ return "hi"
+ @m.state(initial=True)
+ def start(self):
+ "a state"
+ def said_hi(self):
+ "a state with no inputs"
+ start.upon(input, outputs=[])
+ start.upon(say_hi, outputs=[_start_say_hi])
+ a_mechanism = Mechanism()
+ [a_greeting] = a_mechanism.say_hi()
+ self.assertEqual(a_greeting, "hi")
+
+
+ def test_defaultOutputs(self):
+ """
+ It is possible to write a transition with no outputs
+ """
+ class Mechanism(object):
+ m = MethodicalMachine()
+ @m.input()
+ def finish(self):
+ "final transition"
+ @m.state(initial=True)
+ def start(self):
+ "a start state"
+ @m.state()
+ def finished(self):
+ "a final state"
+ start.upon(finish, enter=finished)
+ Mechanism().finish()
def test_getArgNames(self):
"""
|
Fix #<I>: Allow enter to have a default
Since enter follows outputs, and there are some use cases
(including in the tests) which use the argument order,
this also allows outputs to have a default. This has been
discussed before (in the same ticket) as desirable.
|
glyph_automat
|
train
|
1beb3f73d699b38a8ff53d5066529ac290c29654
|
diff --git a/packages/@uppy/companion/src/server/provider/dropbox/index.js b/packages/@uppy/companion/src/server/provider/dropbox/index.js
index <HASH>..<HASH> 100644
--- a/packages/@uppy/companion/src/server/provider/dropbox/index.js
+++ b/packages/@uppy/companion/src/server/provider/dropbox/index.js
@@ -57,10 +57,9 @@ class DropBox extends Provider {
let stats
let reqErr
const finishReq = () => {
- if (reqErr || stats.statusCode !== 200) {
- const err = this._error(reqErr, stats)
- logger.error(err, 'provider.dropbox.list.error')
- done(err)
+ if (reqErr) {
+ logger.error(reqErr, 'provider.dropbox.list.error')
+ done(reqErr)
} else {
stats.body.user_email = userInfo.body.email
done(null, this.adaptData(stats.body, options.companion))
@@ -70,6 +69,9 @@ class DropBox extends Provider {
this.stats(options, (err, resp) => {
statsDone = true
stats = resp
+ if (err || resp.statusCode !== 200) {
+ err = this._error(err, resp)
+ }
reqErr = reqErr || err
if (userInfoDone) {
finishReq()
@@ -79,6 +81,10 @@ class DropBox extends Provider {
this._userInfo(options, (err, resp) => {
userInfoDone = true
userInfo = resp
+ if (err || resp.statusCode !== 200) {
+ err = this._error(err, resp)
+ }
+
reqErr = reqErr || err
if (statsDone) {
finishReq()
|
companion: catch errors when fetching dropbox user email (#<I>)
|
transloadit_uppy
|
train
|
091622154cfb3a9e6073eba2543e017a00f7f46e
|
diff --git a/lib/mongo/cluster.rb b/lib/mongo/cluster.rb
index <HASH>..<HASH> 100644
--- a/lib/mongo/cluster.rb
+++ b/lib/mongo/cluster.rb
@@ -116,7 +116,7 @@ module Mongo
seeds.each{ |seed| add(seed) }
- @cursor_reaper = CursorReaper.new(self)
+ @cursor_reaper = CursorReaper.new
@cursor_reaper.run!
ObjectSpace.define_finalizer(self, self.class.finalize(pools))
diff --git a/lib/mongo/cluster/cursor_reaper.rb b/lib/mongo/cluster/cursor_reaper.rb
index <HASH>..<HASH> 100644
--- a/lib/mongo/cluster/cursor_reaper.rb
+++ b/lib/mongo/cluster/cursor_reaper.rb
@@ -25,9 +25,6 @@ module Mongo
extend Forwardable
include Retryable
- # @return [ Mongo::Cluster ] The cluster associated with this cursor reaper.
- attr_reader :cluster
-
# The default time interval for the cursor reaper to send pending kill cursors operations.
#
# @since 2.3.0
@@ -41,11 +38,10 @@ module Mongo
# @api private
#
# @since 2.3.0
- def initialize(cluster)
+ def initialize
@to_kill = {}
@active_cursors = Set.new
@mutex = Mutex.new
- @cluster = cluster
end
# Start the cursor reaper's thread.
diff --git a/spec/mongo/cluster/cursor_reaper_spec.rb b/spec/mongo/cluster/cursor_reaper_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/mongo/cluster/cursor_reaper_spec.rb
+++ b/spec/mongo/cluster/cursor_reaper_spec.rb
@@ -7,7 +7,7 @@ describe Mongo::Cluster::CursorReaper do
end
let(:reaper) do
- described_class.new(authorized_client.cluster)
+ described_class.new
end
let(:active_cursors) do
|
RUBY-<I> No need to pass the cluster to CursorReaper
|
mongodb_mongo-ruby-driver
|
train
|
a8da588f1349b2dee88c40e600d0633728a5a839
|
diff --git a/lib/workers/package/versions.js b/lib/workers/package/versions.js
index <HASH>..<HASH> 100644
--- a/lib/workers/package/versions.js
+++ b/lib/workers/package/versions.js
@@ -15,7 +15,12 @@ module.exports = {
function determineUpgrades(npmDep, config) {
const currentVersion = config.currentVersion;
if (!isValidVersion(currentVersion)) {
- logger.warn(`${npmDep.name} currentVersion ${currentVersion} is invalid`);
+ const knownTags = ['latest', 'next', 'future', 'alpha', 'beta'];
+ if (knownTags.indexOf(currentVersion) === -1) {
+ logger.warn(`${npmDep.name} currentVersion ${currentVersion} is invalid`);
+ } else {
+ logger.debug(`Skipping ${npmDep.name} with tag ${currentVersion}`);
+ }
return [];
}
const versions = npmDep.versions;
diff --git a/test/workers/package/versions.spec.js b/test/workers/package/versions.spec.js
index <HASH>..<HASH> 100644
--- a/test/workers/package/versions.spec.js
+++ b/test/workers/package/versions.spec.js
@@ -14,6 +14,10 @@ describe('workers/package/versions', () => {
config.currentVersion = 'invalid';
versions.determineUpgrades(qJson, config).should.have.length(0);
});
+ it('return empty if using a known tag', () => {
+ config.currentVersion = 'next';
+ versions.determineUpgrades(qJson, config).should.have.length(0);
+ });
it('return empty if null versions', () => {
config.currentVersion = '1.0.0';
const testDep = {
|
Don’t warn if currentVersion is a known tag
Closes #<I>
|
renovatebot_renovate
|
train
|
b1473f2eae121c461a894e675780927c185604f9
|
diff --git a/lib/svtplay_dl/tests/output.py b/lib/svtplay_dl/tests/output.py
index <HASH>..<HASH> 100644
--- a/lib/svtplay_dl/tests/output.py
+++ b/lib/svtplay_dl/tests/output.py
@@ -50,37 +50,37 @@ class progressbarTest(unittest.TestCase):
def test_0_100(self):
svtplay_dl.output.progressbar(100, 0)
self.assertEqual(
- self.mockfile.read(), "\r[000/100][.........................] "
+ self.mockfile.read(), "\r[000/100][...............] "
)
def test_progress_1_100(self):
svtplay_dl.output.progressbar(100, 1)
self.assertEqual(
- self.mockfile.read(), "\r[001/100][.........................] "
+ self.mockfile.read(), "\r[001/100][...............] "
)
def test_progress_2_100(self):
svtplay_dl.output.progressbar(100, 2)
self.assertEqual(
- self.mockfile.read(), "\r[002/100][.........................] "
+ self.mockfile.read(), "\r[002/100][...............] "
)
def test_progress_50_100(self):
svtplay_dl.output.progressbar(100, 50)
self.assertEqual(
- self.mockfile.read(), "\r[050/100][============.............] "
+ self.mockfile.read(), "\r[050/100][=======........] "
)
def test_progress_100_100(self):
svtplay_dl.output.progressbar(100, 100)
self.assertEqual(
- self.mockfile.read(), "\r[100/100][=========================] "
+ self.mockfile.read(), "\r[100/100][===============] "
)
def test_progress_20_100_msg(self):
svtplay_dl.output.progressbar(100, 20, "msg")
self.assertEqual(
- self.mockfile.read(), "\r[020/100][=====....................] msg"
+ self.mockfile.read(), "\r[020/100][===............] msg"
)
def test_progress_20_100_termwidth(self):
@@ -88,7 +88,7 @@ class progressbarTest(unittest.TestCase):
svtplay_dl.output.progressbar(100, 20)
self.assertEqual(
self.mockfile.read(),
- "\r[020/100][==========........................................] "
+ "\r[020/100][========................................] "
)
class EtaTest(unittest.TestCase):
|
tests: fix output tests after changed progressbar size.
|
spaam_svtplay-dl
|
train
|
535d9c5b7fd2e01361c56a71c2ab08e0ff652e16
|
diff --git a/app/controllers/alchemy/api/contents_controller.rb b/app/controllers/alchemy/api/contents_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/alchemy/api/contents_controller.rb
+++ b/app/controllers/alchemy/api/contents_controller.rb
@@ -16,7 +16,7 @@ module Alchemy
if params[:element_id].present?
@contents = @contents.where(element_id: params[:element_id])
end
- render json: @contents, adapter: :json, root: :contents
+ render json: @contents, adapter: :json, root: 'contents'
end
# Returns a json object for content
diff --git a/app/controllers/alchemy/api/elements_controller.rb b/app/controllers/alchemy/api/elements_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/alchemy/api/elements_controller.rb
+++ b/app/controllers/alchemy/api/elements_controller.rb
@@ -20,7 +20,7 @@ module Alchemy
if params[:named].present?
@elements = @elements.named(params[:named])
end
- render json: @elements, adapter: :json, root: :elements
+ render json: @elements, adapter: :json, root: 'elements'
end
# Returns a json object for element
diff --git a/app/controllers/alchemy/api/pages_controller.rb b/app/controllers/alchemy/api/pages_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/alchemy/api/pages_controller.rb
+++ b/app/controllers/alchemy/api/pages_controller.rb
@@ -16,7 +16,7 @@ module Alchemy
if params[:page_layout].present?
@pages = @pages.where(page_layout: params[:page_layout])
end
- render json: @pages, adapter: :json, root: :pages
+ render json: @pages, adapter: :json, root: 'pages'
end
# Returns all pages as nested json object for tree views
|
Use strings as JSON root keys in API controllers
ActiveModelSerializers <I> has a bug that assumes root keys are
always Strings. A fix has been merged but not released yet. Using
String instead of a Symbol for now.
See <URL>
|
AlchemyCMS_alchemy_cms
|
train
|
6cfa943784c6462231ffd51e8afb30b0803c03bb
|
diff --git a/packages/fractal/src/cli/commands/new.js b/packages/fractal/src/cli/commands/new.js
index <HASH>..<HASH> 100644
--- a/packages/fractal/src/cli/commands/new.js
+++ b/packages/fractal/src/cli/commands/new.js
@@ -24,7 +24,7 @@ module.exports = {
const basePath = baseDir.startsWith('/') ? baseDir : Path.join(process.cwd(), baseDir);
const viewsPath = Path.join(__dirname, '../../../views/cli/new');
const fractalFileTpl = Path.join(viewsPath, 'fractal.hbs');
- const docsIndexTpl = Path.join(viewsPath, 'docs/index.hbs');
+ const docsIndexTpl = Path.join(viewsPath, 'docs/index.md');
const exampleComponent = Path.join(viewsPath, 'components/example');
if (helpers.fileExistsSync(basePath)) {
|
fix: update file extension of docs index in new command (#<I>)
The default docs index file was renamed in <URL>
|
frctl_fractal
|
train
|
bcd85def5c3320abb9ae69d5b4762c89403b116f
|
diff --git a/version.php b/version.php
index <HASH>..<HASH> 100644
--- a/version.php
+++ b/version.php
@@ -29,7 +29,7 @@
defined('MOODLE_INTERNAL') || die();
-$version = 2018112800.00; // YYYYMMDD = weekly release date of this DEV branch.
+$version = 2018112900.00; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
|
MDL-<I> versions: main version bump
|
moodle_moodle
|
train
|
af80050a21d75ea07a61b392bd986d3ae1b4eefc
|
diff --git a/src/ContentDelivery/Catalog/SortOrderConfig.php b/src/ContentDelivery/Catalog/SortOrderConfig.php
index <HASH>..<HASH> 100644
--- a/src/ContentDelivery/Catalog/SortOrderConfig.php
+++ b/src/ContentDelivery/Catalog/SortOrderConfig.php
@@ -28,7 +28,7 @@ class SortOrderConfig implements \JsonSerializable
* @param string $selectedDirection
* @param bool $isSelected
*/
- public function __construct(AttributeCode $attributeCode, $selectedDirection, $isSelected)
+ private function __construct(AttributeCode $attributeCode, $selectedDirection, $isSelected)
{
$this->attributeCode = $attributeCode;
$this->selectedDirection = $selectedDirection;
|
Issue #<I>: Make SortOrderConfig constructor private
|
lizards-and-pumpkins_catalog
|
train
|
d7770e3ae9fba833964fd0513cbf3a287880461a
|
diff --git a/requests_http_signature/__init__.py b/requests_http_signature/__init__.py
index <HASH>..<HASH> 100644
--- a/requests_http_signature/__init__.py
+++ b/requests_http_signature/__init__.py
@@ -5,6 +5,10 @@ import email.utils
import requests
from requests.compat import urlparse
+from requests.exceptions import RequestException
+
+class RequestsHttpSignatureException(RequestException):
+ """An error occurred while constructing the HTTP Signature for your request."""
class Crypto:
def __init__(self, algorithm):
@@ -67,6 +71,8 @@ class HTTPSignatureAuth(requests.auth.AuthBase):
request.headers["Date"] = email.utils.formatdate(timestamp, usegmt=True)
def add_digest(self, request):
+ if request.body is None and "digest" in self.headers:
+ raise RequestsHttpSignatureException("Could not compute digest header for request without a body")
if request.body is not None and "Digest" not in request.headers:
if "digest" not in self.headers:
self.headers.append("digest")
diff --git a/test/test.py b/test/test.py
index <HASH>..<HASH> 100755
--- a/test/test.py
+++ b/test/test.py
@@ -9,8 +9,7 @@ from requests.adapters import HTTPAdapter
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) # noqa
-from requests_http_signature import HTTPSignatureAuth
-
+from requests_http_signature import HTTPSignatureAuth, RequestsHttpSignatureException
hmac_secret = b"monorail_cat"
passphrase = b"passw0rd"
@@ -46,6 +45,10 @@ class TestRequestsHTTPSignature(unittest.TestCase):
self.session.get(url, auth=HTTPSignatureAuth(key=hmac_secret, key_id="sekret"))
with self.assertRaises(AssertionError):
self.session.get(url, auth=HTTPSignatureAuth(key=hmac_secret[::-1], key_id="sekret"))
+ with self.assertRaisesRegex(RequestsHttpSignatureException,
+ "Could not compute digest header for request without a body"):
+ self.session.get(url,
+ auth=HTTPSignatureAuth(key=hmac_secret[::-1], key_id="sekret", headers=["date", "digest"]))
def test_rfc_examples(self):
# The date in the RFC is wrong (2014 instead of 2012).
|
Raise informative error when unable to compute body digest
|
pyauth_requests-http-signature
|
train
|
f6c262c3c3e089dee9f1c47d838a97feafeec018
|
diff --git a/src/components/ebay-pagination/index.js b/src/components/ebay-pagination/index.js
index <HASH>..<HASH> 100644
--- a/src/components/ebay-pagination/index.js
+++ b/src/components/ebay-pagination/index.js
@@ -65,6 +65,7 @@ function getTemplateData(state) {
function init() {
this.pageContainerEl = this.el.querySelector('.pagination__items');
+ this.pageContainerEl.style.flexWrap = 'nowrap';
this.pageEls = this.pageContainerEl.children;
this.containerEl = this.el;
this.previousPageEl = this.el.querySelector('.pagination__previous');
@@ -91,46 +92,42 @@ function refresh() {
for (let i = 0; i < this.state.items.length; i++) {
if (this.state.items[i].current) {
current = i;
- } else {
- // remove all hidden attribues to get accurate widths
- this.pageEls[i].removeAttribute('hidden');
}
+ this.pageEls[i].removeAttribute('hidden');
}
+
const totalPages = this.pageEls.length;
- const pageNumWidth = this.pageEls[current].offsetWidth + constants.margin;
- const containerWidth = this.containerEl.offsetWidth - pageNumWidth * 2;
- const numPagesAllowed = Math.floor((containerWidth) / (pageNumWidth));
- const adjustedNumPages = Math.min(constants.maxPagesAllowed - 1,
- Math.max(numPagesAllowed, constants.minPagesRequired));
+ const pageNumWidth = this.pageEls[0].children[0].offsetWidth + constants.margin;
+ const numPagesAllowed = (((this.pageContainerEl.offsetWidth) / pageNumWidth));
+ const adjustedNumPages = Math.floor(Math.min(constants.maxPagesAllowed,
+ Math.max(numPagesAllowed, constants.minPagesRequired)));
let start = 0;
let end = adjustedNumPages;
- const rangeLeft = Math.floor(adjustedNumPages * 0.5);
+ let rangeLeft = Math.floor(adjustedNumPages * 0.5);
const rangeRight = Math.floor(adjustedNumPages * 0.5);
+ if (rangeLeft + rangeRight + 1 > adjustedNumPages) {
+ rangeLeft -= 1;
+ }
+
start = current - rangeLeft;
end = current + rangeRight;
- if (end > totalPages) {
- start -= (end - totalPages);
- }
if (totalPages < constants.maxPagesAllowed) {
end = totalPages;
}
- if (totalPages - current < rangeRight) {
- start -= (rangeRight - (totalPages - current));
+ if (current + rangeRight >= totalPages) {
+ end = totalPages;
+ start = end - adjustedNumPages;
}
- if (start < 0) {
- end -= start;
+ if (start <= 0) {
+ end = adjustedNumPages - 1;
start = 0;
}
- if (end - start < constants.minPagesRequired && end === totalPages && start > 0) {
- start = end - constants.minPagesRequired;
- }
-
for (let i = 0; i < totalPages; i++) {
if (i < start || i > end) {
this.pageEls[i].setAttribute('hidden', true);
diff --git a/src/components/ebay-pagination/test/test.browser.js b/src/components/ebay-pagination/test/test.browser.js
index <HASH>..<HASH> 100644
--- a/src/components/ebay-pagination/test/test.browser.js
+++ b/src/components/ebay-pagination/test/test.browser.js
@@ -352,9 +352,9 @@ describe('given the pagination has the second item selected', () => {
it('then it shows items 0 through 5', () => testItemVisibility(root, 0, 5));
});
- describe('when the component is 550px wide', () => {
+ describe('when the component is 540px wide', () => {
beforeEach((done) => {
- widget.el.style.width = '550px';
+ widget.el.style.width = '540px';
testUtils.triggerEvent(window, 'resize');
setTimeout(done, 20);
});
@@ -396,9 +396,20 @@ describe('given the pagination has the fifth item selected', () => {
it('then it shows items 2 through 7', () => testItemVisibility(root, 2, 7));
});
- describe('when the component is 550px wide', () => {
+ describe('when the component is 440px wide', () => {
beforeEach((done) => {
- widget.el.style.width = '550px';
+ widget.el.style.width = '440px';
+ testUtils.triggerEvent(window, 'resize');
+ setTimeout(done, 20);
+ });
+ afterEach(() => widget.destroy());
+
+ it('then it shows items 2 through 8', () => testItemVisibility(root, 2, 8));
+ });
+
+ describe('when the component is 540px wide', () => {
+ beforeEach((done) => {
+ widget.el.style.width = '540px';
testUtils.triggerEvent(window, 'resize');
setTimeout(done, 20);
});
@@ -440,9 +451,9 @@ describe('given the pagination has the eighth item selected', () => {
it('then it shows items 4 through 9', () => testItemVisibility(root, 4, 9));
});
- describe('when the component is 550px wide', () => {
+ describe('when the component is 540px wide', () => {
beforeEach((done) => {
- widget.el.style.width = '550px';
+ widget.el.style.width = '540px';
testUtils.triggerEvent(window, 'resize');
setTimeout(done, 20);
});
|
Pagination: improve hidden overflow logic (#<I>)
|
eBay_ebayui-core
|
train
|
0768263ba116980d2b92f8118ef1ef5abfdd20af
|
diff --git a/src/rabird/core/distutils/command/install.py b/src/rabird/core/distutils/command/install.py
index <HASH>..<HASH> 100644
--- a/src/rabird/core/distutils/command/install.py
+++ b/src/rabird/core/distutils/command/install.py
@@ -291,106 +291,25 @@ class GithubUwbpepPackages(object):
raise KeyError("Can't find the requirement : %s" % requirement_text)
-class PypiUwbpepPackages(object):
- page_url = "https://pypi.python.org/pypi/uwbpep/1.0"
-
+class PypiUwbpepPackages(BasePackages):
def __init__(self):
- pass
-
- def parse(self):
- print('Downloading list page of "Unofficial Windows Binaries for Python Extension Packages" ...')
- bytes_io = io.BytesIO()
- try:
- download_file_insecure_to_io(self.page_url, bytes_io)
- content = bytes_io.getvalue().decode('utf-8')
- finally:
- bytes_io.close()
-
- print("Download finished. \nParsing ...")
-
+ super(BasePackages, self).__init__()
+
+ def _get_page_url(self):
+ return "https://pypi.python.org/pypi/uwbpep/1.0"
+
+ def _parse_urls(self, content):
re_flags = re.DOTALL|re.MULTILINE
- matched = re.findall('<a href="([^"]*?\.whl#md5=[^"]*?)"', content, re_flags)
-
- # Initialize packages with names
- packages = {}
-
- # Decrypt links
- for amatch in matched:
- url = amatch
- filename = os.path.basename(url.split("#")[0])
- # Removed the first "uwbpep1.0_" tag!
- filename = filename[len("uwbpep1.0_"):]
-
- filebasename, fileextname = os.path.splitext(filename)
- if fileextname not in [".whl", ".exe", ".zip"]:
- continue
-
- if len(filename.split("-")) < 5:
- continue
-
- if fileextname == ".exe":
- # Fixed *.exe name to fit for Wheel() requirement! A slight trick
- # to support *.exe package.
-
- filebasename = filebasename.replace('.win-amd64', '-win_amd64')
- filebasename = filebasename.replace('.win', '-win')
- filebasename = filebasename.replace('-py2.', '-cp2')
- filebasename = filebasename.replace('-py3.', '-cp3')
-
- wheel_info = filebasename.split('-')
- filename = "%s-%s-%s-%s-%s.whl" % (
- wheel_info[0],
- wheel_info[1],
- wheel_info[3],
- 'none',
- wheel_info[2]
- )
- elif fileextname == ".zip":
- filename = "%s%s" % (filebasename, ".whl")
-
- wheel = Wheel(filename)
-
- package_name = wheel.name.lower().replace("_", "-")
- if package_name not in packages:
- packages[package_name] = {}
- packages[package_name]["wheels"] = []
- packages[package_name]["requirements"] = []
-
- packages[package_name]["wheels"].append((wheel, url))
-
- self.packages = packages
-
- def find_package(self, requirement_text):
- requirement = pkg_resources.Requirement.parse(requirement_text)
- wheel_contexts = self.packages[requirement.key]["wheels"]
+ return re.findall(r'<a href="([^"]*?\.whl#md5=[^"]*?)"', content, re_flags)
+
+ def _decode_url_and_filename(self, amatch):
+ url = amatch
+ filename = os.path.basename(url.split("#")[0])
+ # Removed the first "uwbpep1.0_" tag!
+ filename = filename[len("uwbpep1.0_"):]
- if is_64bit():
- python_platform = "64"
- else:
- python_platform = "32"
-
- python_versions = set([
- "cp%s" % platform.python_version_tuple()[0],
- "cp%s%s" % (platform.python_version_tuple()[0], platform.python_version_tuple()[1]),
- "py%s" % platform.python_version_tuple()[0],
- "py%s%s" % (platform.python_version_tuple()[0], platform.python_version_tuple()[1]),
- ])
-
- for wheel, url in wheel_contexts:
- if python_platform not in wheel.plats[0]:
- continue
-
- if len(set(wheel.pyversions) & python_versions) <= 0:
- continue
-
- wheel_version = Version(wheel.version)
- if not requirement.specifier.contains(wheel_version):
- continue
-
- return (wheel, url)
+ return (url, filename)
- raise KeyError("Can't find the requirement : %s" % requirement_text)
-
class install(distutils_install):
"""
The install command provide extension packages automatic install from
@@ -411,7 +330,7 @@ class install(distutils_install):
"""
def _prepare_requirements(self):
# Try to use pip install first
- failed_requires = []
+ failed_requires = ["pywin32"]
for arequire in self.distribution.install_requires:
# pip.main() will return 0 while successed ..
@@ -419,7 +338,7 @@ class install(distutils_install):
failed_requires.append(arequire)
if len(failed_requires) > 0:
- packages = PythonlibsPackages()
+ packages = PypiUwbpepPackages()
packages.parse()
# Try to install failed requires from UWBPEP
|
Implemented PypiUwbpepPackages by BasePackages
All duplicated stuffs are removed
|
starofrainnight_rabird.core
|
train
|
300e7235025c04ef96641a87411a824f6b626ec5
|
diff --git a/src/test/java/de/slackspace/openkeepass/domain/KeyFileTest.java b/src/test/java/de/slackspace/openkeepass/domain/KeyFileTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/de/slackspace/openkeepass/domain/KeyFileTest.java
+++ b/src/test/java/de/slackspace/openkeepass/domain/KeyFileTest.java
@@ -28,7 +28,7 @@ public class KeyFileTest {
String xml = "<KeyFile><Key><Data>RP+rYNZL4lrGtDMBPzOuctlh3NAutSG5KGsT38C+qPQ=</Data></Key></KeyFile>";
ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
- KeyFile keyFile = (KeyFile) new SimpleXmlParser().fromXml(inputStream, KeyFile.class);
+ KeyFile keyFile = new SimpleXmlParser().fromXml(inputStream, KeyFile.class);
Assert.assertEquals("RP+rYNZL4lrGtDMBPzOuctlh3NAutSG5KGsT38C+qPQ=", keyFile.getKey().getData());
}
diff --git a/src/test/java/de/slackspace/openkeepass/domain/KeyTest.java b/src/test/java/de/slackspace/openkeepass/domain/KeyTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/de/slackspace/openkeepass/domain/KeyTest.java
+++ b/src/test/java/de/slackspace/openkeepass/domain/KeyTest.java
@@ -1,5 +1,6 @@
package de.slackspace.openkeepass.domain;
+import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.junit.Assert;
@@ -20,4 +21,14 @@ public class KeyTest {
String xml = XmlStringCleaner.cleanXmlString(new String(bos.toByteArray()));
Assert.assertEquals("<Key><Data>someData</Data></Key>", xml);
}
+
+ @Test
+ public void shouldUnmarshallObject() {
+ String xml = "<Key><Data>someData</Data></Key>";
+
+ ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
+ Key key = new SimpleXmlParser().fromXml(inputStream, Key.class);
+
+ Assert.assertEquals("someData", key.getData());
+ }
}
|
Added test to unmarshall key
|
cternes_openkeepass
|
train
|
57fccd226e5427155470ae20dce8831bd51fae8e
|
diff --git a/comments/app.js b/comments/app.js
index <HASH>..<HASH> 100644
--- a/comments/app.js
+++ b/comments/app.js
@@ -107,7 +107,7 @@ app.get('/auth/:sdk/:version/comments_recent', function(req, res) {
});
});
-// Returns the most upvoted users.
+// Returns top users (with most upvotes or with most comments).
app.get('/auth/:sdk/:version/users', function(req, res) {
new Request(req).getTopUsers(req.query.sortBy, function(users) {
res.json(users);
diff --git a/comments/lib/comments.js b/comments/lib/comments.js
index <HASH>..<HASH> 100644
--- a/comments/lib/comments.js
+++ b/comments/lib/comments.js
@@ -366,10 +366,10 @@ Comments.prototype = {
},
/**
- * Retrieves users ordered by number of upvotes.
+ * Retrieves users ordered by number of upvotes or number of comments.
* @param {String} sortBy Either "votes" or "comments"
* @param {Function} callback Called when done.
- * @param {String} callback.err Error message when login failed.
+ * @param {String} callback.err Error message when query failed.
* @param {Object} callback.users The top users.
*/
getTopUsers: function(sortBy, callback) {
diff --git a/template/app/view/comments/Users.js b/template/app/view/comments/Users.js
index <HASH>..<HASH> 100644
--- a/template/app/view/comments/Users.js
+++ b/template/app/view/comments/Users.js
@@ -50,7 +50,6 @@ Ext.define('Docs.view.comments.Users', {
cls: "iScroll users-list",
autoScroll: true,
store: Ext.create('Ext.data.Store', {
- model: 'Image',
fields: ["username", "score", "emailHash", "moderator"]
}),
allowDeselect: true,
@@ -61,7 +60,7 @@ Ext.define('Docs.view.comments.Users', {
'<span class="score">{score}</span>',
'<img class="avatar" width="25" height="25" src="http://www.gravatar.com/avatar/{emailHash}',
'?s=25&r=PG&d=http://www.sencha.com/img/avatar.png">',
- '<span href="#" class="username <tpl if="moderator">moderator</tpl>">{username}</span>',
+ '<span class="username <tpl if="moderator">moderator</tpl>">{username}</span>',
'</li>',
'</tpl>',
'</ul>'
|
Small tweaks and fixes to comments users code.
|
senchalabs_jsduck
|
train
|
32821f0c7684148df899f79932c2e138c3ace6f5
|
diff --git a/tests/test_config.py b/tests/test_config.py
index <HASH>..<HASH> 100644
--- a/tests/test_config.py
+++ b/tests/test_config.py
@@ -18,6 +18,7 @@ PYPIRC = """\
index-servers =
server1
server2
+ server3
[server1]
username:me
@@ -28,6 +29,10 @@ username:meagain
password: secret
realm:acme
repository:http://another.pypi/
+
+[server3]
+username:cbiggles
+password:yh^%#rest-of-my-password
"""
PYPIRC_OLD = """\
@@ -113,6 +118,20 @@ class PyPIRCCommandTestCase(support.TempdirManager,
finally:
f.close()
+ def test_config_interpolation(self):
+ # using the % character in .pypirc should not raise an error (#20120)
+ self.write_file(self.rc, PYPIRC)
+ cmd = self._cmd(self.dist)
+ cmd.repository = 'server3'
+ config = cmd._read_pypirc()
+
+ config = list(sorted(config.items()))
+ waited = [('password', 'yh^%#rest-of-my-password'), ('realm', 'pypi'),
+ ('repository', 'https://pypi.python.org/pypi'),
+ ('server', 'server3'), ('username', 'cbiggles')]
+ self.assertEqual(config, waited)
+
+
def test_suite():
return unittest.makeSuite(PyPIRCCommandTestCase)
|
Issue #<I>: Add a test case to verify the % char can be used in .pypirc
I noticed that there is no test for this feature while doing
triaging work on pypa/pypi-legacy.
|
pypa_setuptools
|
train
|
0e7b925baf93405a31b982f55ba3e5d950ef7507
|
diff --git a/doc.go b/doc.go
index <HASH>..<HASH> 100644
--- a/doc.go
+++ b/doc.go
@@ -1,6 +1,14 @@
/*
Package goa provides the runtime support for goa web applications.
+see also http://goa.design
+
+package cors: https://godoc.org/github.com/raphael/goa/cors
+
+package design: https://godoc.org/github.com/raphael/goa/design
+
+package dsl: https://godoc.org/github.com/raphael/goa/design/dsl
+
Code Generation
goa applications development begins with writing the *design* of an application. The design is
|
Add links to other docs to GoDoc
|
goadesign_goa
|
train
|
dea9526835fdf4aa90ed341c0407a6576f2f1ce1
|
diff --git a/rdbtools/cli/rdb.py b/rdbtools/cli/rdb.py
index <HASH>..<HASH> 100755
--- a/rdbtools/cli/rdb.py
+++ b/rdbtools/cli/rdb.py
@@ -22,6 +22,8 @@ Example : %prog --command json -k "user.*" /var/redis/6379/dump.rdb"""
parser.add_option("-t", "--type", dest="types", action="append",
help="""Data types to include. Possible values are string, hash, set, sortedset, list. Multiple typees can be provided.
If not specified, all data types will be returned""")
+ parser.add_option("-s", "--size", dest="size", default=None,
+ help="Limit memory output to keys greater to or equal to this value (in bytes)")
(options, args) = parser.parse_args()
@@ -57,7 +59,7 @@ Example : %prog --command json -k "user.*" /var/redis/6379/dump.rdb"""
elif 'json' == options.command:
callback = JSONCallback(f)
elif 'memory' == options.command:
- reporter = PrintAllKeys(f)
+ reporter = PrintAllKeys(f, options.size)
callback = MemoryCallback(reporter, 64)
elif 'protocol' == options.command:
callback = ProtocolCallback(f)
@@ -71,7 +73,7 @@ Example : %prog --command json -k "user.*" /var/redis/6379/dump.rdb"""
elif 'json' == options.command:
callback = JSONCallback(sys.stdout)
elif 'memory' == options.command:
- reporter = PrintAllKeys(sys.stdout)
+ reporter = PrintAllKeys(sys.stdout, options.size)
callback = MemoryCallback(reporter, 64)
elif 'protocol' == options.command:
callback = ProtocolCallback(sys.stdout)
diff --git a/rdbtools/memprofiler.py b/rdbtools/memprofiler.py
index <HASH>..<HASH> 100644
--- a/rdbtools/memprofiler.py
+++ b/rdbtools/memprofiler.py
@@ -68,14 +68,16 @@ class StatsAggregator():
return json.dumps({"aggregates":self.aggregates, "scatters":self.scatters, "histograms":self.histograms})
class PrintAllKeys():
- def __init__(self, out):
+ def __init__(self, out, size):
+ self._size = int(size)
self._out = out
self._out.write("%s,%s,%s,%s,%s,%s,%s\n" % ("database", "type", "key",
"size_in_bytes", "encoding", "num_elements", "len_largest_element"))
def next_record(self, record) :
- self._out.write("%d,%s,%s,%d,%s,%d,%d\n" % (record.database, record.type, encode_key(record.key),
- record.bytes, record.encoding, record.size, record.len_largest_element))
+ if self._size is None or record.size >= self._size:
+ self._out.write("%d,%s,%s,%d,%s,%d,%d\n" % (record.database, record.type, encode_key(record.key),
+ record.bytes, record.encoding, record.size, record.len_largest_element))
class MemoryCallback(RdbCallback):
'''Calculates the memory used if this rdb file were loaded into RAM
|
Added --size argument to filter keys by size
|
sripathikrishnan_redis-rdb-tools
|
train
|
d16c86acce1f84277f0c5dfeff7c73ac0b7480ef
|
diff --git a/lib/Sabre/VObject/Parser/MimeDir.php b/lib/Sabre/VObject/Parser/MimeDir.php
index <HASH>..<HASH> 100644
--- a/lib/Sabre/VObject/Parser/MimeDir.php
+++ b/lib/Sabre/VObject/Parser/MimeDir.php
@@ -38,24 +38,6 @@ class MimeDir extends Parser {
protected $root;
/**
- * Creates the parser.
- *
- * Optionally, it's possible to parse the input stream here.
- *
- * @param resource|null|string $input
- * @param int $options Any parser options (OPTION constants).
- * @return void
- */
- public function __construct($input = null, $options = 0) {
-
- if (!is_null($input)) {
- $this->setInput($input);
- }
- $this->options = $options;
-
- }
-
- /**
* Parses an iCalendar or vCard file
*
* Pass a stream or a string. If null is parsed, the existing buffer is
|
Using the parent's constructor.
|
sabre-io_vobject
|
train
|
3438d937b28e23bf9f48a27891aa4973e43307ee
|
diff --git a/teamcity/jb_behave_formatter.py b/teamcity/jb_behave_formatter.py
index <HASH>..<HASH> 100644
--- a/teamcity/jb_behave_formatter.py
+++ b/teamcity/jb_behave_formatter.py
@@ -5,12 +5,10 @@ Behave formatter that supports TC
import datetime
import traceback
from collections import deque
-from distutils import version
from behave.formatter.base import Formatter
from behave.model import Step, Feature, Scenario
from behave.model_core import Status
-from behave import __version__ as behave_version
from teamcity.messages import TeamcityServiceMessages
@@ -35,7 +33,6 @@ class TeamcityFormatter(Formatter):
def __init__(self, stream_opener, config):
super(TeamcityFormatter, self).__init__(stream_opener, config)
- assert version.LooseVersion(behave_version) >= version.LooseVersion("1.2.6"), "Only 1.2.6+ is supported"
self._messages = TeamcityServiceMessages()
self.__feature = None
diff --git a/teamcity/pytest_plugin.py b/teamcity/pytest_plugin.py
index <HASH>..<HASH> 100644
--- a/teamcity/pytest_plugin.py
+++ b/teamcity/pytest_plugin.py
@@ -26,18 +26,6 @@ diff_tools.patch_unittest_diff()
_ASSERTION_FAILURE_KEY = '_teamcity_assertion_failure'
-def _is_bool_supported():
- """
- Type "bool" is not supported before 2.9
- """
- try:
- from pytest import __version__
- from distutils import version
- return version.LooseVersion(str(__version__)) >= version.LooseVersion("2.9")
- except ImportError:
- return False
-
-
def pytest_addoption(parser):
group = parser.getgroup("terminal reporting", "reporting", after="general")
@@ -48,8 +36,7 @@ def pytest_addoption(parser):
parser.addoption('--jb-swapdiff', action="store_true", dest="swapdiff", default=False, help="Swap actual/expected in diff")
kwargs = {"help": "skip output of passed tests for JetBrains TeamCity service messages"}
- if _is_bool_supported():
- kwargs.update({"type": "bool"})
+ kwargs.update({"type": "bool"})
parser.addini("skippassedoutput", **kwargs)
parser.addini("swapdiff", **kwargs)
|
Stop using outdated module, drop ancient verions of pytest and behave
|
JetBrains_teamcity-messages
|
train
|
720c8416ce88224002e7acaf5985a125f6bf2417
|
diff --git a/src/featherlight.js b/src/featherlight.js
index <HASH>..<HASH> 100644
--- a/src/featherlight.js
+++ b/src/featherlight.js
@@ -534,6 +534,20 @@
}
},
+ beforeOpen: function(_super, event) {
+ this._previouslyActive = document.activeElement;
+ document.activeElement.blur();
+ return _super(event);
+ },
+
+ afterClose: function(_super, event) {
+ if (this._previouslyActive) { // Bulletproofing
+ this._previouslyActive.focus();
+ this._previouslyActive = null;
+ }
+ return _super(event);
+ },
+
onResize: function(_super, event){
this.resize(this.$content.naturalWidth, this.$content.naturalHeight);
return _super(event);
diff --git a/test/featherlight.html b/test/featherlight.html
index <HASH>..<HASH> 100644
--- a/test/featherlight.html
+++ b/test/featherlight.html
@@ -60,6 +60,8 @@
Hello
<i>world</i>
</div>
+
+ <input class="for-focus">
</section>
</body>
</html>
diff --git a/test/featherlight_test.js b/test/featherlight_test.js
index <HASH>..<HASH> 100644
--- a/test/featherlight_test.js
+++ b/test/featherlight_test.js
@@ -423,6 +423,14 @@ var stubAjaxLoad = function(content) {
close.focus();
expect($(document.activeElement)).to.have.class('featherlight-close-icon');
});
+
+ it('removes focus and then resets it', function() {
+ $('input').focus();
+ $.featherlight({text: 'Hello'});
+ expect($(document.activeElement)).not.to.have.class('for-focus');
+ $.featherlight.close();
+ expect($(document.activeElement)).to.have.class('for-focus');
+ })
});
});
}(jQuery));
|
Improve focus handling [#<I>]
|
noelboss_featherlight
|
train
|
30e6ab5b2b1b104a94878c2bfb37fc62581ae93e
|
diff --git a/lib/arjdbc/postgresql/adapter.rb b/lib/arjdbc/postgresql/adapter.rb
index <HASH>..<HASH> 100644
--- a/lib/arjdbc/postgresql/adapter.rb
+++ b/lib/arjdbc/postgresql/adapter.rb
@@ -1411,13 +1411,10 @@ module ActiveRecord::ConnectionAdapters
self.class.type_cast_config_to_boolean(@config[:insert_returning]) : nil
end
- class ColumnDefinition < ActiveRecord::ConnectionAdapters::ColumnDefinition
- attr_accessor :array
- def array?; !!@array; end
- end
-
require 'arjdbc/postgresql/base/schema_definitions'
+ ColumnDefinition = ActiveRecord::ConnectionAdapters::PostgreSQL::ColumnDefinition
+
ColumnMethods = ActiveRecord::ConnectionAdapters::PostgreSQL::ColumnMethods
TableDefinition = ActiveRecord::ConnectionAdapters::PostgreSQL::TableDefinition
diff --git a/lib/arjdbc/postgresql/base/schema_definitions.rb b/lib/arjdbc/postgresql/base/schema_definitions.rb
index <HASH>..<HASH> 100644
--- a/lib/arjdbc/postgresql/base/schema_definitions.rb
+++ b/lib/arjdbc/postgresql/base/schema_definitions.rb
@@ -1,6 +1,11 @@
module ActiveRecord
module ConnectionAdapters
module PostgreSQL
+ class ColumnDefinition < ActiveRecord::ConnectionAdapters::ColumnDefinition
+ attr_accessor :array
+ def array?; !!@array; end
+ end
+
module ColumnMethods
def xml(*args)
options = args.extract_options!
|
[postgres] move the ColumnDefinition into base/schema_definitions.rb as well
|
jruby_activerecord-jdbc-adapter
|
train
|
d246a295d264c2df9cebe5d3bf0bc7956a71b2fd
|
diff --git a/stream_test.go b/stream_test.go
index <HASH>..<HASH> 100644
--- a/stream_test.go
+++ b/stream_test.go
@@ -427,8 +427,71 @@ var _ = Describe("Stream", func() {
str.AddStreamFrame(&frame)
str.RegisterRemoteError(testErr)
b := make([]byte, 4)
+ n, err := str.Read(b)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(n).To(Equal(4))
+ })
+
+ It("reads a delayed StreamFrame that arrives after receiving a remote error", func() {
+ str.RegisterRemoteError(testErr)
+ frame := frames.StreamFrame{
+ Offset: 0,
+ Data: []byte{0xDE, 0xAD, 0xBE, 0xEF},
+ }
+ err := str.AddStreamFrame(&frame)
+ Expect(err).ToNot(HaveOccurred())
+ b := make([]byte, 4)
+ n, err := str.Read(b)
+ Expect(err).ToNot(HaveOccurred())
+ Expect(n).To(Equal(4))
+ })
+
+ It("returns the error if reading past the offset of the frame received", func() {
+ frame := frames.StreamFrame{
+ Offset: 0,
+ Data: []byte{0xDE, 0xAD, 0xBE, 0xEF},
+ }
+ str.AddStreamFrame(&frame)
+ str.RegisterRemoteError(testErr)
+ b := make([]byte, 10)
+ n, err := str.Read(b)
+ Expect(b[0:4]).To(Equal(frame.Data))
+ Expect(err).To(MatchError(testErr))
+ Expect(n).To(Equal(4))
+ })
+
+ It("returns an EOF when reading past the offset, if the stream received a finbit", func() {
+ frame := frames.StreamFrame{
+ Offset: 0,
+ Data: []byte{0xDE, 0xAD, 0xBE, 0xEF},
+ FinBit: true,
+ }
+ str.AddStreamFrame(&frame)
+ str.RegisterRemoteError(testErr)
+ b := make([]byte, 10)
+ n, err := str.Read(b)
+ Expect(b[:4]).To(Equal(frame.Data))
+ Expect(err).To(MatchError(io.EOF))
+ Expect(n).To(Equal(4))
+ })
+
+ It("continues reading in small chunks after receiving a remote error", func() {
+ frame := frames.StreamFrame{
+ Offset: 0,
+ Data: []byte{0xDE, 0xAD, 0xBE, 0xEF},
+ FinBit: true,
+ }
+ str.AddStreamFrame(&frame)
+ str.RegisterRemoteError(testErr)
+ b := make([]byte, 3)
_, err := str.Read(b)
Expect(err).ToNot(HaveOccurred())
+ Expect(b).To(Equal([]byte{0xde, 0xad, 0xbe}))
+ b = make([]byte, 3)
+ n, err := str.Read(b)
+ Expect(err).To(MatchError(io.EOF))
+ Expect(b[:1]).To(Equal([]byte{0xef}))
+ Expect(n).To(Equal(1))
})
It("stops writing after receiving a remote error", func() {
|
add more stream tests for reading after receiving a RST_STREAM
|
lucas-clemente_quic-go
|
train
|
ad390e8903d6c4e51dc693252be5a63e29a0f55a
|
diff --git a/lib/function/matrix/inv.js b/lib/function/matrix/inv.js
index <HASH>..<HASH> 100644
--- a/lib/function/matrix/inv.js
+++ b/lib/function/matrix/inv.js
@@ -10,6 +10,7 @@ function factory (type, config, load, typed) {
var unaryMinus = load(require('../arithmetic/unaryMinus'));
var det = load(require('../matrix/det'));
var eye = load(require('./eye'));
+ var abs = load(require('../arithmetic/abs'));
/**
* Calculate the inverse of a square matrix.
@@ -145,16 +146,21 @@ function factory (type, config, load, typed) {
// loop over all columns, and perform row reductions
for (var c = 0; c < cols; c++) {
- // element Acc should be non zero. if not, swap content
- // with one of the lower rows
- r = c;
- while (r < rows && A[r][c] == 0) {
+ // Pivoting: Swap row c with row r, where row r contains the largest element A[r][c]
+ var A_big = A[c][c];
+ var r_big = c;
+ r = c+1;
+ while (r < rows) {
+ if(abs(A[r][c]) > A_big) {
+ A_big = abs(A[r][c]);
+ r_big = r;
+ }
r++;
}
- if (r == rows || A[r][c] == 0) {
- // TODO: in case of zero det, just return a matrix wih Infinity values? (like octave)
+ if(A_big == 0) {
throw Error('Cannot calculate inverse, determinant is zero');
}
+ r = r_big;
if (r != c) {
temp = A[c]; A[c] = A[r]; A[r] = temp;
temp = B[c]; B[c] = B[r]; B[r] = temp;
diff --git a/test/function/matrix/inv.test.js b/test/function/matrix/inv.test.js
index <HASH>..<HASH> 100644
--- a/test/function/matrix/inv.test.js
+++ b/test/function/matrix/inv.test.js
@@ -84,6 +84,35 @@ describe('inv', function() {
assert.throws(function () {math.concat(inv(new Date()))}, /TypeError: Unexpected type of argument/);
});
+ it('should avoid issues with elements that are almost zero', function() {
+
+ approx.deepEqual(inv([
+ [0, 1, 0, 788 ],
+ [-1, 0, 0, 692 ],
+ [0, 0, 1, 0 ],
+ [0, 0, 0, 1]
+ ]), [
+ [0, -1, 0, 692 ],
+ [1, 0, 0, -788 ],
+ [0, 0, 1, 0],
+ [0, 0, 0, 1]
+ ]);
+
+ approx.deepEqual(inv([
+ [6.123233995736766e-17, 1, 0, 788 ],
+ [-1, 6.123233995736766e-17, 0, 692 ],
+ [0, 0, 1, 0 ],
+ [0, 0, 0, 1]
+ ]), [
+ [6.123233995736766e-17, -1, 0, 692 ],
+ [1, 6.123233995736766e-17, 0, -788 ],
+ [0, 0, 1, 0],
+ [0, 0, 0, 1]
+ ]);
+
+
+ })
+
it('should LaTeX inv', function () {
var expression = math.parse('inv([[1,2],[3,4]])');
assert.equal(expression.toTex(), '\\left(\\begin{bmatrix}1&2\\\\3&4\\\\\\end{bmatrix}\\right)^{-1}');
|
Add pivoting to matrix inverse algorithm, and tests
|
josdejong_mathjs
|
train
|
8df7b1c2626908e6f97c9d2f0d73822ee60581ba
|
diff --git a/lib/pokerstats/hand_statistics.rb b/lib/pokerstats/hand_statistics.rb
index <HASH>..<HASH> 100644
--- a/lib/pokerstats/hand_statistics.rb
+++ b/lib/pokerstats/hand_statistics.rb
@@ -249,10 +249,11 @@ class HandStatistics
end
def self.player_statistics_migration_data
- plugin_factory.inject(""){|string, each_plugin|
+ plugin_factory.inject("") do |string, each_plugin|
string + "#\t#{each_plugin.inspect}\n"
each_plugin.report_specification do |each_datum|
string + "t.#{each_datum[0]}\t#{each[1].inspect}\n"
+ end
end
end
|
fix compile bug in hand_statistics2
|
wizardwerdna_pokerstats
|
train
|
53b5b95ef553947605cee81d8e023e49e144946a
|
diff --git a/command/refresh_test.go b/command/refresh_test.go
index <HASH>..<HASH> 100644
--- a/command/refresh_test.go
+++ b/command/refresh_test.go
@@ -511,8 +511,14 @@ func TestRefresh_backup(t *testing.T) {
t.Fatalf("err: %s", err)
}
outPath := outf.Name()
- outf.Close()
- os.Remove(outPath)
+ defer outf.Close()
+
+ // Need to put some state content in the output file so that there's
+ // something to back up.
+ err = statefile.Write(statefile.New(state, "baz", 0), outf)
+ if err != nil {
+ t.Fatalf("error writing initial output state file %s", err)
+ }
// Backup path
backupf, err := ioutil.TempFile(testingDir, "tf")
|
command: Fix TestRefresh_backup
The local filesystem state manager no longer creates backup files eagerly,
instead creating them only if on first write there is already a snapshot
present in the target file.
Therefore for this test to exercise the codepaths it intends to we must
create an initial state snapshot for it to overwrite, creating the backup
in the process.
There are several other tests for this behavior elsewhere, so this test
is primarily to verify that the refresh command is configuring the backend
appropriately to get the backups written in the desired location.
|
hashicorp_terraform
|
train
|
f5a42d64c300d06e4ae0b519ed8b5cceefc0e22c
|
diff --git a/src/components/BoardContainer.js b/src/components/BoardContainer.js
index <HASH>..<HASH> 100644
--- a/src/components/BoardContainer.js
+++ b/src/components/BoardContainer.js
@@ -14,7 +14,7 @@ const laneActions = require('../actions/LaneActions')
class BoardContainer extends Component {
wireEventBus = () => {
let eventBus = {
- publish: (event) => {
+ publish: event => {
switch (event.type) {
case 'ADD_CARD':
return this.props.actions.addCard({laneId: event.laneId, card: event.card})
@@ -36,26 +36,58 @@ class BoardContainer extends Component {
}
componentWillReceiveProps (nextProps) {
- if (nextProps.data && nextProps.data !== this.props.data) {
+ // nextProps.data changes when Board input props change and reducerData changes due to event bus changes
+ const {data, reducerData} = this.props
+ if (this.props.onDataChange && nextProps.reducerData && reducerData !== nextProps.reducerData) {
+ this.props.onDataChange(nextProps.reducerData)
+ }
+ if (nextProps.data && nextProps.data !== data) {
this.props.actions.loadBoard(nextProps.data)
- this.props.onDataChange && this.props.onDataChange(nextProps.data)
}
}
render () {
const {reducerData, style, ...otherProps} = this.props
- return <BoardDiv style={style} {...otherProps}>
- {
- reducerData.lanes.map((lane) => {
+ return (
+ <BoardDiv style={style} {...otherProps}>
+ {reducerData.lanes.map(lane => {
const {id, ...otherProps} = lane
- const {tagStyle, draggable, handleDragStart, handleDragEnd, onCardClick, onLaneClick, onLaneScroll, laneSortFunction, customCardLayout, cardStyle, children} = this.props
- return <Lane key={`${id}`}
- id={id}
- {...otherProps}
- {...{tagStyle, draggable, handleDragStart, handleDragEnd, onCardClick, onLaneClick, onLaneScroll, laneSortFunction, customCardLayout, cardStyle, children}}
- />
+ const {
+ tagStyle,
+ draggable,
+ handleDragStart,
+ handleDragEnd,
+ onCardClick,
+ onLaneClick,
+ onLaneScroll,
+ laneSortFunction,
+ customCardLayout,
+ cardStyle,
+ children
+ } = this.props
+ return (
+ <Lane
+ key={`${id}`}
+ id={id}
+ {...otherProps}
+ {...{
+ tagStyle,
+ draggable,
+ handleDragStart,
+ handleDragEnd,
+ onCardClick,
+ onLaneClick,
+ onLaneScroll,
+ laneSortFunction,
+ customCardLayout,
+ cardStyle,
+ children
+ }}
+ />
+ )
})}
- </BoardDiv>
+ </BoardDiv>
+ )
}
}
@@ -74,10 +106,10 @@ BoardContainer.propTypes = {
style: PropTypes.object
}
-const mapStateToProps = (state) => {
+const mapStateToProps = state => {
return state.lanes ? {reducerData: state} : {}
}
-const mapDispatchToProps = (dispatch) => ({actions: bindActionCreators({...boardActions, ...laneActions}, dispatch)})
+const mapDispatchToProps = dispatch => ({actions: bindActionCreators({...boardActions, ...laneActions}, dispatch)})
export default connect(mapStateToProps, mapDispatchToProps)(DragDropContext(MultiBackend(HTML5toTouch))(BoardContainer))
|
fix: onDataChange not called when internal state changed due to eventBus or UI interactions
<URL>
|
rcdexta_react-trello
|
train
|
2e7c69dc4d185dc790b7d15857235458ef3eb7a6
|
diff --git a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDocAssembler.java b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDocAssembler.java
index <HASH>..<HASH> 100644
--- a/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDocAssembler.java
+++ b/subprojects/groovy-groovydoc/src/main/java/org/codehaus/groovy/tools/groovydoc/SimpleGroovyClassDocAssembler.java
@@ -268,51 +268,61 @@ public class SimpleGroovyClassDocAssembler extends VisitorAdapter implements Gro
private void processPropertiesFromGetterSetter(SimpleGroovyMethodDoc currentMethodDoc) {
String methodName = currentMethodDoc.name();
+ int len = methodName.length();
+ String prefix = null;
+ String propName = null;
+ if (len > 3 && methodName.startsWith("get")) {
+ prefix = "get";
+ propName = methodName.substring(3);
+ } else if (len > 3 && methodName.startsWith("set")) {
+ prefix = "set";
+ propName = methodName.substring(3);
+ } else if (len > 2 && methodName.startsWith("is")) {
+ prefix = "is";
+ propName = methodName.substring(2);
+ } else {
+ // Not a (get/set/is) method that contains a property name
+ return;
+ }
+
SimpleGroovyClassDoc classDoc = getCurrentClassDoc();
+ // TODO: not sure why but groovy.ui.view.BasicContentPane#buildOutputArea classDoc is null
+ if (classDoc == null) {
+ return;
+ }
GroovyMethodDoc methods[] = classDoc.methods();
- String setOrGet = methodName.substring(0, Math.min(methodName.length(), 3));
- if (setOrGet.equals("set") || setOrGet.equals("get") || setOrGet.startsWith("is")) {
-
- //find expected method name
- String expectedMethodName = null ;
- if (setOrGet.equals("set") && (currentMethodDoc.parameters().length >= 1 && !currentMethodDoc.parameters()[0].typeName().equals("boolean"))) {
- expectedMethodName = "get" + methodName.substring(3);
- } else if (setOrGet.equals("get") && !currentMethodDoc.returnType().typeName().equals("boolean")) {
- expectedMethodName = "set" + methodName.substring(3);
- } else if (setOrGet.startsWith("is")) {
- expectedMethodName = "set" + methodName.substring(2);
- } else {
- expectedMethodName = "is" + methodName.substring(3);
- }
-
- for (GroovyMethodDoc methodDoc : methods) {
- if (methodDoc.name().equals(expectedMethodName)) {
+ //find expected method name
+ String expectedMethodName = null;
+ if ("set".equals(prefix) && (currentMethodDoc.parameters().length >= 1 && !currentMethodDoc.parameters()[0].typeName().equals("boolean"))) {
+ expectedMethodName = "get" + propName;
+ } else if ("get".equals(prefix) && !currentMethodDoc.returnType().typeName().equals("boolean")) {
+ expectedMethodName = "set" + propName;
+ } else if ("is".equals(prefix)) {
+ expectedMethodName = "set" + propName;
+ } else {
+ expectedMethodName = "is" + propName;
+ }
- //extract the field name
- String fieldName = null;
- if (expectedMethodName.startsWith("set") && methodName.startsWith("is")) {
- fieldName = methodName.substring(2);
- } else {
- fieldName = methodName.substring(3);
- }
+ for (GroovyMethodDoc methodDoc : methods) {
+ if (methodDoc.name().equals(expectedMethodName)) {
- fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);
- SimpleGroovyFieldDoc currentFieldDoc = new SimpleGroovyFieldDoc(fieldName, classDoc);
+ //extract the field name
+ String fieldName = propName.substring(0, 1).toLowerCase() + propName.substring(1);
+ SimpleGroovyFieldDoc currentFieldDoc = new SimpleGroovyFieldDoc(fieldName, classDoc);
- //find the type of the field; if it's a setter, need to get the type of the params
- if(expectedMethodName.startsWith("set") && methodDoc.parameters().length >= 1) {
- String typeName = methodDoc.parameters()[0].typeName();
- currentFieldDoc.setType(new SimpleGroovyType(typeName));
- } else {
- //if it's not setter, get the type info of the return type of the get* method
- currentFieldDoc.setType(methodDoc.returnType());
- }
+ //find the type of the field; if it's a setter, need to get the type of the params
+ if(expectedMethodName.startsWith("set") && methodDoc.parameters().length >= 1) {
+ String typeName = methodDoc.parameters()[0].typeName();
+ currentFieldDoc.setType(new SimpleGroovyType(typeName));
+ } else {
+ //if it's not setter, get the type info of the return type of the get* method
+ currentFieldDoc.setType(methodDoc.returnType());
+ }
- if (methodDoc.isPublic() && currentMethodDoc.isPublic()) {
- classDoc.addProperty(currentFieldDoc);
- break;
- }
+ if (methodDoc.isPublic() && currentMethodDoc.isPublic()) {
+ classDoc.addProperty(currentFieldDoc);
+ break;
}
}
}
|
Fix groovydoc processPropertiesFromGetterSetter build exceptions
Fixes StringIndexOutOfBoundsException if method name was exactly named [set/get/is] with no property name or NPE if classDoc was null.
|
apache_groovy
|
train
|
ae029a1379a2a963973ce752a5feb9c69ceec2a1
|
diff --git a/server/src/main/java/org/jboss/as/server/DomainServerMain.java b/server/src/main/java/org/jboss/as/server/DomainServerMain.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/org/jboss/as/server/DomainServerMain.java
+++ b/server/src/main/java/org/jboss/as/server/DomainServerMain.java
@@ -81,8 +81,8 @@ public final class DomainServerMain {
* @param args ignored
*/
public static void main(String[] args) {
- // TODO: privileged block
- System.setProperty("log4j.defaultInitOverride", "true");
+
+ SecurityActions.setSystemProperty("log4j.defaultInitOverride", "true");
new BridgeRepositorySelector().start();
final InputStream initialInput = System.in;
|
Use a privileged action to set system property
was: <I>b<I>c<I>b5c<I>c<I>b9de1f<I>cfee3d<I>
|
wildfly_wildfly-core
|
train
|
9e84478728bf810388a29c15c4a8dc24045c8222
|
diff --git a/src/shellingham/__init__.py b/src/shellingham/__init__.py
index <HASH>..<HASH> 100644
--- a/src/shellingham/__init__.py
+++ b/src/shellingham/__init__.py
@@ -4,7 +4,7 @@ import os
from ._core import ShellDetectionFailure
-__version__ = '1.2.3'
+__version__ = '1.2.3.dev0'
def detect_shell(pid=None, max_depth=6):
|
Prebump to <I>.dev0
|
sarugaku_shellingham
|
train
|
b05f12ee9e06d00279fd142327a2306878076613
|
diff --git a/pyinfra/operations/files.py b/pyinfra/operations/files.py
index <HASH>..<HASH> 100644
--- a/pyinfra/operations/files.py
+++ b/pyinfra/operations/files.py
@@ -144,6 +144,9 @@ def download(
'|| (echo "MD5 did not match!" && exit 1)'
).format(dest, md5sum)
+ else:
+ host.noop('file: {0} has already been downloaded'.format(dest))
+
@operation
def line(
@@ -655,9 +658,12 @@ def put(
yield chmod(dest, mode)
else:
+ changed = False
+
# Check mode
if mode and remote_file['mode'] != mode:
yield chmod(dest, mode)
+ changed = True
# Check user/group
if (
@@ -665,6 +671,10 @@ def put(
or (group and remote_file['group'] != group)
):
yield chown(dest, user, group)
+ changed = True
+
+ if not changed:
+ host.noop('file {0} is already uploaded'.format(dest))
@operation
@@ -1108,19 +1118,24 @@ def directory(
if no_check_owner_mode:
return
- # Check mode
+ changed = False
+
if mode and (not info or info['mode'] != mode):
yield chmod(path, mode, recursive=recursive)
info['mode'] = mode
+ changed = True
- # Check user/group
if (
(not info and (user or group))
or (user and info['user'] != user)
or (group and info['group'] != group)
):
yield chown(path, user, group, recursive=recursive)
+ changed = True
if user:
info['user'] = user
if group:
info['group'] = group
+
+ if not changed:
+ host.noop('directory {0} already exists'.format(path))
|
Implement noop logging for some files operations.
|
Fizzadar_pyinfra
|
train
|
55bb203c873f5225b2c3e6330f7b0b54dad57d64
|
diff --git a/apptentive/src/com/apptentive/android/sdk/module/messagecenter/view/MessageCenterActivityContent.java b/apptentive/src/com/apptentive/android/sdk/module/messagecenter/view/MessageCenterActivityContent.java
index <HASH>..<HASH> 100644
--- a/apptentive/src/com/apptentive/android/sdk/module/messagecenter/view/MessageCenterActivityContent.java
+++ b/apptentive/src/com/apptentive/android/sdk/module/messagecenter/view/MessageCenterActivityContent.java
@@ -19,12 +19,13 @@ import android.widget.Toast;
import com.apptentive.android.sdk.ApptentiveInternal;
import com.apptentive.android.sdk.Log;
import com.apptentive.android.sdk.model.Event;
-import com.apptentive.android.sdk.model.FileMessage;
-import com.apptentive.android.sdk.model.TextMessage;
+
import com.apptentive.android.sdk.module.ActivityContent;
import com.apptentive.android.sdk.module.messagecenter.MessageManager;
import com.apptentive.android.sdk.module.messagecenter.MessagePollingWorker;
import com.apptentive.android.sdk.module.messagecenter.model.MessageCenterListItem;
+import com.apptentive.android.sdk.module.messagecenter.model.OutgoingFileMessage;
+import com.apptentive.android.sdk.module.messagecenter.model.OutgoingTextMessage;
import com.apptentive.android.sdk.module.metric.MetricModule;
import com.apptentive.android.sdk.util.Constants;
@@ -56,7 +57,7 @@ public class MessageCenterActivityContent extends ActivityContent {
MessageCenterView.OnSendMessageListener onSendMessageListener = new MessageCenterView.OnSendMessageListener() {
public void onSendTextMessage(String text) {
- final TextMessage message = new TextMessage();
+ final OutgoingTextMessage message = new OutgoingTextMessage();
message.setBody(text);
message.setRead(true);
message.setCustomData(customData);
@@ -73,7 +74,7 @@ public class MessageCenterActivityContent extends ActivityContent {
public void onSendFileMessage(Uri uri) {
// First, create the file, and populate some metadata about it.
- final FileMessage message = new FileMessage();
+ final OutgoingFileMessage message = new OutgoingFileMessage();
boolean successful = message.internalCreateStoredImage(context.getApplicationContext(), uri.toString());
if (successful) {
message.setRead(true);
|
AND-<I> Change the class names after merging with next
|
apptentive_apptentive-android
|
train
|
f672f5dde7cdc2a1c1fef8831760ae5e509d2a1b
|
diff --git a/src/CommonFactory.php b/src/CommonFactory.php
index <HASH>..<HASH> 100644
--- a/src/CommonFactory.php
+++ b/src/CommonFactory.php
@@ -169,7 +169,7 @@ class CommonFactory implements Factory, DomainEventFactory
*/
public function createEnvironmentBuilder()
{
- $version = $this->getCurrentVersion();
+ $version = $this->getCurrentDataVersion();
return $this->createEnvironmentBuilderWithVersion(DataVersion::fromVersionString($version));
}
@@ -182,7 +182,7 @@ class CommonFactory implements Factory, DomainEventFactory
return new EnvironmentBuilder($version);
}
- private function getCurrentVersion()
+ private function getCurrentDataVersion()
{
/** @var DataPoolReader $dataPoolReader */
$dataPoolReader = $this->getMasterFactory()->createDataPoolReader();
|
Issue #<I>: Also rename the private getter in CommonFactory to getCurrentDataVersion
|
lizards-and-pumpkins_catalog
|
train
|
f48432a61ab6d3d97c4a93dc9c2178a9b01695a9
|
diff --git a/linode/login_client.py b/linode/login_client.py
index <HASH>..<HASH> 100644
--- a/linode/login_client.py
+++ b/linode/login_client.py
@@ -220,6 +220,7 @@ class LinodeLoginClient:
split = list(urlparse(url))
params = {
"client_id": self.client_id,
+ "response_type": "code", # needed for all logins
}
if scopes:
params["scopes"] = OAuthScopes.serialize(scopes)
|
Add now-needed response_type param to login urls
With a recent login.linode.com update, a "response_type" parameter
is required for oauth login attempts. This adds it in, allowing oauth
logins through the login client to continue working.
|
linode_linode_api4-python
|
train
|
c4bdb21a7516db17287df7bb29293f49f0ac5238
|
diff --git a/limpyd/fields.py b/limpyd/fields.py
index <HASH>..<HASH> 100644
--- a/limpyd/fields.py
+++ b/limpyd/fields.py
@@ -640,17 +640,6 @@ class HashableField(RedisField):
available_getters = ('hget', )
available_modifiers = ('hincrby', 'hincrbyfloat', 'hset', 'hsetnx')
- _commands = {
- 'getters': ('hget', ),
- 'full_modifiers': ('hset', 'hsetnx', ),
- 'partial_modifiers': ('hincrby', 'hincrbyfloat', ),
- }
-
- _commands_to_proxy = {
- 'hset': '_set',
- 'hsetnx': '_set'
- }
-
@property
def key(self):
return self._instance.key
|
Remove unused temp code commited by error
|
limpyd_redis-limpyd
|
train
|
c9c8d876d06523b5213c22e1cbf5fc24ad4c97a9
|
diff --git a/src/image/Factory/ImageFactory.php b/src/image/Factory/ImageFactory.php
index <HASH>..<HASH> 100644
--- a/src/image/Factory/ImageFactory.php
+++ b/src/image/Factory/ImageFactory.php
@@ -13,6 +13,7 @@ namespace WBW\Library\Image\Factory;
use WBW\Library\Image\Model\Image;
use WBW\Library\Image\Model\ImageInterface;
+use WBW\Library\Image\Utility\ImageUtility;
/**
* Image factory.
@@ -34,27 +35,7 @@ class ImageFactory {
$image->init();
- if ($image->getWidth() < $maxWidth || $image->getHeight() < $maxHeight) {
- return [$image->getWidth(), $image->getHeight()];
- }
-
- if (null === $image->getOrientation()) {
- $max = max($maxWidth, $maxHeight);
- return [$max, $max];
- }
-
- $ratio = $image->getWidth() / $image->getHeight();
-
- $width = $maxWidth;
- $height = $maxHeight;
-
- if (ImageInterface::ORIENTATION_HORIZONTAL === $image->getOrientation()) {
- $height = intval($width / $ratio);
- } else {
- $width = intval($height * $ratio);
- }
-
- return [$width, $height];
+ return ImageUtility::getDimensions($image->getWidth(), $image->getHeight(), $maxWidth, $maxHeight);
}
/**
diff --git a/tests/image/Factory/ImageFactoryTest.php b/tests/image/Factory/ImageFactoryTest.php
index <HASH>..<HASH> 100644
--- a/tests/image/Factory/ImageFactoryTest.php
+++ b/tests/image/Factory/ImageFactoryTest.php
@@ -48,17 +48,17 @@ class ImageFactoryTest extends AbstractTestCase {
*/
public function testNewDimensions(): void {
- $hImage = new Image($this->images[1]); // Horizontal image
- $sImage = new Image($this->images[2]); // Square image
- $vImage = new Image($this->images[3]); // Vertical image
+ $hImage = new Image($this->images[1]); // Landscape image
+ $sImage = new Image($this->images[2]); // Squarish image
+ $vImage = new Image($this->images[3]); // Portrait image
$this->assertEquals([1920, 1037], ImageFactory::newDimensions($hImage, 2000, 1100));
- $this->assertEquals([1000, 540], ImageFactory::newDimensions($hImage, 1000, 900));
+ $this->assertEquals([1000, 900], ImageFactory::newDimensions($hImage, 1000, 900));
$this->assertEquals([1600, 1600], ImageFactory::newDimensions($sImage, 1600, 1200));
$this->assertEquals([1600, 1600], ImageFactory::newDimensions($sImage, 1200, 1600));
- $this->assertEquals([540, 1000], ImageFactory::newDimensions($vImage, 900, 1000));
+ $this->assertEquals([900, 1000], ImageFactory::newDimensions($vImage, 900, 1000));
}
/**
|
Update Image factory:
- implements Image utility
|
webeweb_core-library
|
train
|
82e84ec37e0ae2f1ba0e43145f7dad5f4ea6ea17
|
diff --git a/fedmsg_meta_fedora_infrastructure/conglomerators/bodhi.py b/fedmsg_meta_fedora_infrastructure/conglomerators/bodhi.py
index <HASH>..<HASH> 100644
--- a/fedmsg_meta_fedora_infrastructure/conglomerators/bodhi.py
+++ b/fedmsg_meta_fedora_infrastructure/conglomerators/bodhi.py
@@ -31,7 +31,6 @@ class RequestByUserAndPackage(fedmsg.meta.base.BaseConglomerator):
subtitle = '{agent} submitted {N} {package} updates for {branches}'
tmpl['subtitle'] = subtitle.format(
agent=agent, package=package, N=N, branches=branches)
- tmpl['icon'] = self.processor.__icon__
tmpl['secondary_icon'] = gravatar_url(msg['agent'])
base = 'https://admin.fedoraproject.org/updates/%s/'
tmpl['link'] = base % package
|
Unnecessary. self.produce_template(..) actually includes this.
|
fedora-infra_fedmsg_meta_fedora_infrastructure
|
train
|
a7f61e8220db7bd422dd33a5ef21dfdbf37b1b38
|
diff --git a/lib/bolt/cli.rb b/lib/bolt/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/bolt/cli.rb
+++ b/lib/bolt/cli.rb
@@ -8,7 +8,7 @@ module Bolt
class CLIError < RuntimeError
attr_reader :error_code
- def initialize(msg, error_code)
+ def initialize(msg, error_code: 1)
super(msg)
@error_code = error_code
end
@@ -52,7 +52,7 @@ END
options[:nodes] = options[:nodes].split(',')
options
rescue Trollop::CommandlineError => e
- raise Bolt::CLIError.new(e.message, 1)
+ raise Bolt::CLIError, e.message
rescue Trollop::HelpNeeded
parser.educate
raise Bolt::CLIExit
@@ -66,7 +66,7 @@ END
if MODES.include?(args[0])
args.shift
else
- raise Bolt::CLIError.new("Expected a mode of run, exec, or script", 1)
+ raise Bolt::CLIError, "Expected a mode of run, exec, or script"
end
end
@@ -107,9 +107,8 @@ END
def load_task_data(name, modules)
if modules.nil?
- raise Bolt::CLIError.new(
- "The '--modules' option must be specified to run a task", 1
- )
+ raise Bolt::CLIError,
+ "The '--modules' option must be specified to run a task"
end
begin
@@ -117,7 +116,7 @@ END
require 'puppet/node/environment'
require 'puppet/info_service'
rescue LoadError
- raise Bolt::CLIError.new("Puppet must be installed to execute tasks", 1)
+ raise Bolt::CLIError, "Puppet must be installed to execute tasks"
end
module_name, file_name = name.split('::', 2)
@@ -131,9 +130,7 @@ END
file = data[:files].find { |f| File.basename(f, '.*') == file_name }
if file.nil?
- raise Bolt::CLIError.new(
- "Failed to load task file for '#{name}'", 1
- )
+ raise Bolt::CLIError, "Failed to load task file for '#{name}'"
end
metadata =
|
(maint) Don't require exit code in CLIError
Default to 1
|
puppetlabs_bolt
|
train
|
b705d9202c10113c8a1d7dd464de5e527fc85c3f
|
diff --git a/gulpfile.js b/gulpfile.js
index <HASH>..<HASH> 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -10,6 +10,10 @@ var testFiles = []; // Declared in the karma.conf.js
var rootDir = process.cwd();
var distDirectory = 'dist';
+gulp.task('watch', function(){
+ gulp.watch(['js/**/*.ts', 'server/data_form.ts'], ['build']);
+})
+
/**
* Main task: cleans, builds, run tests, and bundles up for distribution.
*/
|
added watch task to gulp to auto-build.
|
forms-angular_forms-angular
|
train
|
e6af3c74fe6b61d0f80574723f0498c59c31907d
|
diff --git a/scripts/generate_all_jobs.py b/scripts/generate_all_jobs.py
index <HASH>..<HASH> 100755
--- a/scripts/generate_all_jobs.py
+++ b/scripts/generate_all_jobs.py
@@ -133,8 +133,8 @@ def main(argv=sys.argv[1:]):
generate_release_compare_page_job(
args.config_url, ros_distro_name, ros_distro_names[:index],
dry_run=not args.commit)
- generate_blocked_releases_page_job(
- args.config_url, ros_distro_name, dry_run=not args.commit)
+ generate_blocked_releases_page_job(
+ args.config_url, ros_distro_name, dry_run=not args.commit)
def generate_check_agents_job(config_url, dry_run=False):
|
do not generate a blocked-releases job for the first distro (#<I>)
|
ros-infrastructure_ros_buildfarm
|
train
|
7a0991d016c110ccf7f16b9000374ce0568733bc
|
diff --git a/libusb1.py b/libusb1.py
index <HASH>..<HASH> 100644
--- a/libusb1.py
+++ b/libusb1.py
@@ -572,20 +572,32 @@ libusb_transfer_p = POINTER(libusb_transfer)
libusb_transfer_cb_fn_p = CFUNCTYPE(None, libusb_transfer_p)
-libusb_transfer._fields_ = [('dev_handle', libusb_device_handle_p),
- ('flags', c_uint8),
- ('endpoint', c_uchar),
- ('type', c_uchar),
- ('timeout', c_uint),
- ('status', c_int), # enum libusb_transfer_status
- ('length', c_int),
- ('actual_length', c_int),
- ('callback', libusb_transfer_cb_fn_p),
- ('user_data', py_object),
- ('buffer', c_void_p),
- ('num_iso_packets', c_int),
- ('iso_packet_desc', libusb_iso_packet_descriptor)
+_libusb_transfer_fields = [
+ ('dev_handle', libusb_device_handle_p),
+ ('flags', c_uint8),
+ ('endpoint', c_uchar),
+ ('type', c_uchar),
+ ('timeout', c_uint),
+ ('status', c_int), # enum libusb_transfer_status
+ ('length', c_int),
+ ('actual_length', c_int),
+ ('callback', libusb_transfer_cb_fn_p),
+ ('user_data', py_object),
+ ('buffer', c_void_p),
+ ('num_iso_packets', c_int),
+ ('iso_packet_desc', libusb_iso_packet_descriptor)
]
+if platform.system() == 'FreeBSD' and getattr(libusb,
+ 'libusb_get_string_descriptor', None) is None:
+ # Old FreeBSD version has a slight ABI incompatibility.
+ # Work around it unless libusb_get_string_descriptor is available, as it
+ # is only available on fixed versions.
+ assert _libusb_transfer_fields[2][0] == 'endpoint'
+ _libusb_transfer_fields[2] = ('endpoint', c_uint32)
+ assert _libusb_transfer_fields[11][0] == 'num_iso_packets'
+ _libusb_transfer_fields.insert(11, ('os_priv', c_void_p))
+
+libusb_transfer._fields_ = _libusb_transfer_fields
libusb_capability = Enum({
# The libusb_has_capability() API is available.
|
Support FreeBSD's libusb.so<I> ABI incompatibility.
It has been fixed in <I>, and the easiest way to detect it via ctypes is
by checking the presence of an export also added in <I> .
|
vpelletier_python-libusb1
|
train
|
df3d411cc0f31e955d73a323977a913b9a16000b
|
diff --git a/cumulusci/tasks/robotframework/debugger/ui.py b/cumulusci/tasks/robotframework/debugger/ui.py
index <HASH>..<HASH> 100644
--- a/cumulusci/tasks/robotframework/debugger/ui.py
+++ b/cumulusci/tasks/robotframework/debugger/ui.py
@@ -170,24 +170,12 @@ class DebuggerCli(cmd.Cmd, object):
print("{}: {}-> {}".format(i, indent, x.longname), file=self.stdout)
print("", file=self.stdout)
- def _highlight_element(self, element, style=None):
- """Highlight a Selenium Webdriver element
+ def _highlight_element(self, element):
+ """Highlight a Selenium Webdriver element"""
- style can be None, a string with css styles, or a dict of css styles
- element needs to be an instance of WebElement
- """
-
- if style is None:
- element_style = """
+ element_style = """
box-shadow: 0px 1px 4px 2px inset #FFFF00;
- """
- elif isinstance(style, dict):
- element_style = "\n".join(
- "{}: {};".format(key, value) for key, value in style.items()
- )
- else:
- element_style = style
-
+ """
original_style = element.get_attribute("style")
new_style = original_style + element_style
self.selenium.driver.execute_script(
|
Remove custom styles for highlight_element
I think this is a feature we want, but I never fully implemented it.
It will be easy to add back in later.
|
SFDO-Tooling_CumulusCI
|
train
|
4ccc5bbe7c56f34242c4bf816e30fc4e5ca65150
|
diff --git a/server/container_create.go b/server/container_create.go
index <HASH>..<HASH> 100644
--- a/server/container_create.go
+++ b/server/container_create.go
@@ -394,6 +394,10 @@ func (s *Server) createSandboxContainer(ctx context.Context, containerID string,
specgen.AddBindMount(sb.resolvPath, "/etc/resolv.conf", []string{"ro"})
}
+ if sb.hostname != "" {
+ specgen.SetHostname(sb.hostname)
+ }
+
specgen.AddAnnotation("ocid/name", containerName)
specgen.AddAnnotation("ocid/sandbox_id", sb.id)
specgen.AddAnnotation("ocid/sandbox_name", sb.infraContainer.Name())
diff --git a/server/sandbox.go b/server/sandbox.go
index <HASH>..<HASH> 100644
--- a/server/sandbox.go
+++ b/server/sandbox.go
@@ -141,6 +141,7 @@ type sandbox struct {
cgroupParent string
privileged bool
resolvPath string
+ hostname string
}
const (
diff --git a/server/sandbox_run.go b/server/sandbox_run.go
index <HASH>..<HASH> 100644
--- a/server/sandbox_run.go
+++ b/server/sandbox_run.go
@@ -259,6 +259,7 @@ func (s *Server) RunPodSandbox(ctx context.Context, req *pb.RunPodSandboxRequest
g.AddAnnotation("ocid/shm_path", shmPath)
g.AddAnnotation("ocid/privileged_runtime", fmt.Sprintf("%v", privileged))
g.AddAnnotation("ocid/resolv_path", resolvPath)
+ g.AddAnnotation("ocid/hostname", hostname)
sb := &sandbox{
id: id,
@@ -273,6 +274,7 @@ func (s *Server) RunPodSandbox(ctx context.Context, req *pb.RunPodSandboxRequest
shmPath: shmPath,
privileged: privileged,
resolvPath: resolvPath,
+ hostname: hostname,
}
s.addSandbox(sb)
|
Set the container hostnames same as pod hostname
|
cri-o_cri-o
|
train
|
49255ce4d571fcdf2bb135c14bfaad12f7a415f9
|
diff --git a/packages/heroku-cli-plugin-certs-v5/commands/certs/add.js b/packages/heroku-cli-plugin-certs-v5/commands/certs/add.js
index <HASH>..<HASH> 100644
--- a/packages/heroku-cli-plugin-certs-v5/commands/certs/add.js
+++ b/packages/heroku-cli-plugin-certs-v5/commands/certs/add.js
@@ -121,7 +121,10 @@ function * addDomains (context, heroku, meta, promisesResult) {
return domain.hostname.match(/^[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+$/) ? 'ALIAS/CNAME' : 'CNAME'
}
- let domains = apiDomains.concat(addedDomains).map((domain) => Object.assign({}, domain, {type: type(domain)}))
+ let domains = apiDomains.concat(addedDomains)
+ .filter((domain) => domain.kind === 'custom')
+ .map((domain) => Object.assign({}, domain, {type: type(domain)}))
+
cli.table(domains, {columns: [
{label: 'Domain', key: 'hostname'},
{label: 'Record Type', key: 'type'},
diff --git a/packages/heroku-cli-plugin-certs-v5/test/commands/certs/add.js b/packages/heroku-cli-plugin-certs-v5/test/commands/certs/add.js
index <HASH>..<HASH> 100644
--- a/packages/heroku-cli-plugin-certs-v5/test/commands/certs/add.js
+++ b/packages/heroku-cli-plugin-certs-v5/test/commands/certs/add.js
@@ -289,7 +289,8 @@ ${certificateDetails}
.reply(200, [
{'kind': 'custom', 'hostname': 'biz.example.com', 'cname': 'biz.example.com.herokudns.com'},
{'kind': 'custom', 'hostname': 'baz.example.org', 'cname': 'baz.example.org.herokudns.com'},
- {'kind': 'custom', 'hostname': 'example.org', 'cname': 'example.org.herokudns.com'}
+ {'kind': 'custom', 'hostname': 'example.org', 'cname': 'example.org.herokudns.com'},
+ {'kind': 'heroku', 'hostname': 'haiku.herokuapp.com', 'cname': 'haiku.herokuapp.com'}
])
inquirer.prompt = (prompts) => {
|
Only include custom domains in _certs:add output
|
heroku_cli
|
train
|
7ea2a497591c32f50bc6e9d8a93d5a774f05a133
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -63,7 +63,7 @@ function _CRC16(buf, length) {
/**
* Parse the data for a Modbus -
- * Read Coils (FC=02,01)
+ * Read Coils (FC=02, 01)
*
* @param {buffer} data the data buffer to parse.
* @param {function} next the function to call next.
@@ -87,7 +87,7 @@ function _readFC2(data, next) {
/**
* Parse the data for a Modbus -
- * Read Input Registers (FC=04,03)
+ * Read Input Registers (FC=04, 03)
*
* @param {buffer} data the data buffer to parse.
* @param {function} next the function to call next.
diff --git a/ports/c701port.js b/ports/c701port.js
index <HASH>..<HASH> 100644
--- a/ports/c701port.js
+++ b/ports/c701port.js
@@ -34,20 +34,21 @@ function crc16(buf) {
/**
* check if a buffer chunk can be a modbus answer
+ * or modbus exception
*
* @param {buffer} buf the buffer to check.
* @return {boolean} if the buffer can be an answer
*/
function checkData(modbus, buf) {
// check buffer size
- if (buf.length != modbus._length) return false;
+ if (buf.length != modbus._length && buf.length != 5) return false;
// calculate crc16
var crcIn = buf.readUInt16LE(buf.length - 2);
// check buffer unit-id, command and crc
return (buf[0] == modbus._id &&
- buf[1] == modbus._cmd &&
+ (0x7f & buf[1]) == modbus._cmd &&
crcIn == crc16(buf));
}
diff --git a/ports/rtubufferedport.js b/ports/rtubufferedport.js
index <HASH>..<HASH> 100644
--- a/ports/rtubufferedport.js
+++ b/ports/rtubufferedport.js
@@ -32,20 +32,21 @@ function crc16(buf) {
/**
* check if a buffer chunk can be a modbus answer
+ * of modbus exception
*
* @param {buffer} buf the buffer to check.
* @return {boolean} if the buffer can be an answer
*/
function checkData(modbus, buf) {
// check buffer size
- if (buf.length != modbus._length) return false;
+ if (buf.length != modbus._length && buf.length != 5) return false;
// calculate crc16
var crcIn = buf.readUInt16LE(buf.length - 2);
// check buffer unit-id, command and crc
return (buf[0] == modbus._id &&
- buf[1] == modbus._cmd &&
+ (0x7f & buf[1]) == modbus._cmd &&
crcIn == crc16(buf));
}
diff --git a/ports/telnetport.js b/ports/telnetport.js
index <HASH>..<HASH> 100644
--- a/ports/telnetport.js
+++ b/ports/telnetport.js
@@ -34,20 +34,21 @@ function crc16(buf) {
/**
* check if a buffer chunk can be a modbus answer
+ * or modbus exception
*
* @param {buffer} buf the buffer to check.
* @return {boolean} if the buffer can be an answer
*/
function checkData(modbus, buf) {
// check buffer size
- if (buf.length != modbus._length) return false;
+ if (buf.length != modbus._length && buf.length != 5) return false;
// calculate crc16
var crcIn = buf.readUInt16LE(buf.length - 2);
// check buffer unit-id, command and crc
return (buf[0] == modbus._id &&
- buf[1] == modbus._cmd &&
+ (0x7f & buf[1]) == modbus._cmd &&
crcIn == crc16(buf));
}
@@ -83,7 +84,7 @@ var TelnetPort = function(ip, options) {
var bufferLength = modbus._buffer.length ;
// check data length
- if (bufferLength < 6 || length < 6) return;
+ if (bufferLength < 5 || length < 5) return;
// loop and check length-sized buffer chunks
for (var i = 0; i < (bufferLength - length + 1); i++) {
|
add checking for valid modbus exceptions in the buffered ports
|
yaacov_node-modbus-serial
|
train
|
4f96522ec17b5d97ed4d914fa57be715f0eae4f8
|
diff --git a/model/state/thumbnails.php b/model/state/thumbnails.php
index <HASH>..<HASH> 100644
--- a/model/state/thumbnails.php
+++ b/model/state/thumbnails.php
@@ -25,7 +25,7 @@ class ComFilesModelStateThumbnails extends KModelState
$this->_source_container = $parts[0];
- $this->set('name', basename($parts[1]));
+ $this->set('name', basename($parts[1]) . '.jpg');
$this->set('folder', dirname($parts[1]));
}
|
#<I> Set thumbnail name from source name.
|
joomlatools_joomlatools-framework
|
train
|
0887038bcca909ead5b1273e4eb3d62fac3f8c2a
|
diff --git a/src/main/java/org/aerogear/connectivity/service/impl/SenderServiceImpl.java b/src/main/java/org/aerogear/connectivity/service/impl/SenderServiceImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/aerogear/connectivity/service/impl/SenderServiceImpl.java
+++ b/src/main/java/org/aerogear/connectivity/service/impl/SenderServiceImpl.java
@@ -57,6 +57,7 @@ public class SenderServiceImpl implements SenderService {
@Override
public void sendToAliases(PushApplication pushApplication, SelectiveSendMessage message) {
+ final List<String> submittedAliases = message.getAliases();
final UnifiedPushMessage unifiedPushMessage = new UnifiedPushMessage(message.getMessage());
// TODO: Make better...
@@ -69,7 +70,7 @@ public class SenderServiceImpl implements SenderService {
for (MobileVariantInstanceImpl instance : instancesPerVariant) {
// see if the alias does match for the instance
- if (message.getAliases().contains(instance.getAlias())) {
+ if (submittedAliases != null && submittedAliases.contains(instance.getAlias())) {
// add it
iOSTokenPerVariant.add(instance.getDeviceToken());
}
@@ -90,7 +91,7 @@ public class SenderServiceImpl implements SenderService {
for (MobileVariantInstanceImpl instance : instancesPerVariant) {
// see if the alias does match for the instance
- if (message.getAliases().contains(instance.getAlias())) {
+ if (submittedAliases != null && submittedAliases.contains(instance.getAlias())) {
// add it
androidTokenPerVariant.add(instance.getDeviceToken());
}
@@ -118,8 +119,13 @@ public class SenderServiceImpl implements SenderService {
String categoryFromInstance = instance.getCategory();
// Does the category match one of the submitted ones?
// Does the alias also match ??
- if (tokensPerCategory.get(categoryFromInstance) != null && message.getAliases().contains(instance.getAlias())) {
+ if (tokensPerCategory.get(categoryFromInstance) != null) {
+ String currentAlias = instance.getAlias();
+ // NO alias at all .....???
+ // alias matches......
+ if ((submittedAliases == null && currentAlias == null) || (submittedAliases.contains(currentAlias)) )
+
// add the token, to the matching category list:
tokensPerCategory.get(categoryFromInstance).add(instance.getDeviceToken());
}
|
Fix NPE when no alias is submitted...
|
aerogear_aerogear-unifiedpush-server
|
train
|
4dc801515687446accc77dc43eeea2da4140ad39
|
diff --git a/tests/spead2_bench.py b/tests/spead2_bench.py
index <HASH>..<HASH> 100755
--- a/tests/spead2_bench.py
+++ b/tests/spead2_bench.py
@@ -130,7 +130,6 @@ def measure_connection_once(args, rate, num_heaps, required_heaps):
stream = spead2.send.trollius.UdpStream(
thread_pool, args.host, args.port, config, args.send_buffer)
item_group = spead2.send.ItemGroup(
- descriptor_frequency=0,
flavour=spead2.Flavour(4, 64, args.addr_bits, 0))
for i in range(1):
item_group.add_item(id=None, name='Test item {}'.format(i),
|
Eliminate descriptors from benchmark script
|
ska-sa_spead2
|
train
|
8706760481cb8f1d7f016cc41de11bbee101f25c
|
diff --git a/pymagicc/api.py b/pymagicc/api.py
index <HASH>..<HASH> 100644
--- a/pymagicc/api.py
+++ b/pymagicc/api.py
@@ -1,7 +1,7 @@
import shutil
import subprocess
from os import listdir, makedirs
-from os.path import basename, dirname, exists, join, isfile
+from os.path import basename, dirname, exists, join, isfile, abspath
from tempfile import mkdtemp
import f90nml
@@ -95,6 +95,8 @@ class MAGICCBase(object):
if not exists(self.root_dir):
makedirs(self.root_dir)
+ exec_dir = basename(self.original_dir)
+
# Copy a subset of folders from the MAGICC `original_dir`
# Also copy anything which is in the root of the MAGICC distribution
# Assumes that the MAGICC binary is in a folder one level below the root
@@ -104,8 +106,11 @@ class MAGICCBase(object):
'bin',
'run'
]
+ # Check that the executable is in a valid sub directory
+ assert exec_dir in dirs_to_copy, 'binary must be in bin/ or run/ directory'
+
for d in dirs_to_copy:
- source_dir = join(self.original_dir, '..', d)
+ source_dir = abspath(join(self.original_dir, '..', d))
if exists(source_dir):
_copy_files(source_dir, join(self.root_dir, d))
@@ -144,7 +149,8 @@ class MAGICCBase(object):
:param only: If not None, only extract variables in this list
:return: Dict containing DataFrames for each of the extracted variables
"""
- command = [join(self.run_dir, self.binary_name)]
+ exec_dir = basename(self.original_dir)
+ command = [join(self.root_dir, exec_dir, self.binary_name)]
if not IS_WINDOWS \
and self.binary_name.endswith(".exe"): # pragma: no cover
diff --git a/tests/test_api.py b/tests/test_api.py
index <HASH>..<HASH> 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -123,3 +123,14 @@ def test_clean_value_nulls():
assert len(out_str) == len(expected)
for o, e in zip(out_str, expected):
assert o == e
+
+
+def test_incorrect_subdir():
+ config['EXECUTABLE'] = '/tmp/magicc'
+ magicc = MAGICC6()
+ try:
+ with pytest.raises(AssertionError):
+ magicc.create_copy()
+ finally:
+ del config.overrides['EXECUTABLE']
+ magicc.remove_temp_copy()
|
Enable magicc binary to be in either run or bin directory
|
openclimatedata_pymagicc
|
train
|
25b188440aecdb5482e815708d824c753d210edb
|
diff --git a/docker/auth/auth.py b/docker/auth/auth.py
index <HASH>..<HASH> 100644
--- a/docker/auth/auth.py
+++ b/docker/auth/auth.py
@@ -21,7 +21,7 @@ import six
from .. import errors
-INDEX_NAME = 'index.docker.io'
+INDEX_NAME = 'docker.io'
INDEX_URL = 'https://{0}/v1/'.format(INDEX_NAME)
DOCKER_CONFIG_FILENAME = os.path.join('.docker', 'config.json')
LEGACY_DOCKER_CONFIG_FILENAME = '.dockercfg'
@@ -41,7 +41,14 @@ def resolve_repository_name(repo_name):
'Invalid index name ({0}). Cannot begin or end with a'
' hyphen.'.format(index_name)
)
- return index_name, remote_name
+ return resolve_index_name(index_name), remote_name
+
+
+def resolve_index_name(index_name):
+ index_name = convert_to_hostname(index_name)
+ if index_name == 'index.'+INDEX_NAME:
+ index_name = INDEX_NAME
+ return index_name
def split_repo_name(repo_name):
@@ -62,7 +69,7 @@ def resolve_authconfig(authconfig, registry=None):
Returns None if no match was found.
"""
# Default to the public index server
- registry = convert_to_hostname(registry) if registry else INDEX_NAME
+ registry = resolve_index_name(registry) if registry else INDEX_NAME
log.debug("Looking for auth entry for {0}".format(repr(registry)))
if registry in authconfig:
@@ -70,7 +77,7 @@ def resolve_authconfig(authconfig, registry=None):
return authconfig[registry]
for key, config in six.iteritems(authconfig):
- if convert_to_hostname(key) == registry:
+ if resolve_index_name(key) == registry:
log.debug("Found {0}".format(repr(key)))
return config
diff --git a/tests/unit/auth_test.py b/tests/unit/auth_test.py
index <HASH>..<HASH> 100644
--- a/tests/unit/auth_test.py
+++ b/tests/unit/auth_test.py
@@ -35,25 +35,31 @@ class ResolveRepositoryNameTest(base.BaseTestCase):
def test_resolve_repository_name_hub_library_image(self):
self.assertEqual(
auth.resolve_repository_name('image'),
- ('index.docker.io', 'image'),
+ ('docker.io', 'image'),
)
def test_resolve_repository_name_dotted_hub_library_image(self):
self.assertEqual(
auth.resolve_repository_name('image.valid'),
- ('index.docker.io', 'image.valid')
+ ('docker.io', 'image.valid')
)
def test_resolve_repository_name_hub_image(self):
self.assertEqual(
auth.resolve_repository_name('username/image'),
- ('index.docker.io', 'username/image'),
+ ('docker.io', 'username/image'),
)
def test_explicit_hub_index_library_image(self):
self.assertEqual(
+ auth.resolve_repository_name('docker.io/image'),
+ ('docker.io', 'image')
+ )
+
+ def test_explicit_legacy_hub_index_library_image(self):
+ self.assertEqual(
auth.resolve_repository_name('index.docker.io/image'),
- ('index.docker.io', 'image')
+ ('docker.io', 'image')
)
def test_resolve_repository_name_private_registry(self):
@@ -228,6 +234,23 @@ class ResolveAuthTest(base.BaseTestCase):
)['username'],
'indexuser',
)
+
+ def test_resolve_registry_and_auth_explicit_hub(self):
+ image = 'docker.io/username/image'
+ self.assertEqual(
+ auth.resolve_authconfig(
+ self.auth_config, auth.resolve_repository_name(image)[0]
+ )['username'],
+ 'indexuser',
+ )
+
+ def test_resolve_registry_and_auth_explicit_legacy_hub(self):
+ image = 'index.docker.io/username/image'
+ self.assertEqual(
+ auth.resolve_authconfig(
+ self.auth_config, auth.resolve_repository_name(image)[0]
+ )['username'],
+ 'indexuser',
)
def test_resolve_registry_and_auth_private_registry(self):
|
Treat 'index.docker.io' repo names as 'docker.io'
|
docker_docker-py
|
train
|
556524e6b7188bd551126d8f0eebd74163d2a1ca
|
diff --git a/app/Catalog/Category/CategoryList.php b/app/Catalog/Category/CategoryList.php
index <HASH>..<HASH> 100644
--- a/app/Catalog/Category/CategoryList.php
+++ b/app/Catalog/Category/CategoryList.php
@@ -7,6 +7,9 @@ use Moltin\SDK\Facade\Product as Product;
class CategoryList
{
+ /**
+ * @var \Psr\Http\Message\ResponseInterface
+ */
private $response;
public function __invoke(
@@ -14,6 +17,7 @@ class CategoryList
\Psr\Http\Message\ResponseInterface $response
) {
$this->response = $response;
+
// Authenticate credentials
Moltin::Authenticate('ClientCredentials', [
'client_id' => getenv('MOLTIN_CLIENT_ID'),
@@ -39,8 +43,15 @@ class CategoryList
return $this->response;
}
- private function displayProductDetails($product)
+ private function displayProductDetails($product, $key)
{
- $this->response->write($product['sku']);
+ $this->response->write('<br />');
+ $this->response->write('ProductNumber: ' . $key . '<br />');
+ $this->response->write(
+ sprintf(
+ 'Sku: %s',
+ $product['sku']
+ )
+ );
}
}
\ No newline at end of file
|
Extend display product details to show product number in the list
|
KickAssCommerce_framework
|
train
|
05f0fdec92a3a436f7cc0c8400850670c8145c6f
|
diff --git a/lib/rest-ftp-daemon/jobs/transfer.rb b/lib/rest-ftp-daemon/jobs/transfer.rb
index <HASH>..<HASH> 100644
--- a/lib/rest-ftp-daemon/jobs/transfer.rb
+++ b/lib/rest-ftp-daemon/jobs/transfer.rb
@@ -128,19 +128,14 @@ module RestFtpDaemon
# Start transfer
transfer_started_at = Time.now
- @progress_at = 0
- @notified_at = transfer_started_at
+ @last_notify_at = transfer_started_at
# Start the transfer, update job status after each block transfer
set_status JOB_STATUS_UPLOADING
log_debug "JobTransfer.remote_upload source[#{source.path}] temp[#{@tempfile}]"
@remote.upload source, target, @tempfile do |transferred, name|
-
# Update transfer statistics
update_progress transferred, name
-
- # Touch my worker status
- touch_job
end
# Compute final bitrate
@@ -158,31 +153,31 @@ module RestFtpDaemon
# Update job info
percent0 = (100.0 * @transfer_sent / @transfer_total).round(0)
- set_info INFO_TRANFER_PROGRESS, percent0
+ set_info INFO_TRANFER_PROGRESS, percent0
# What's current time ?
now = Time.now
- # Update job status
- update_progress_jobinfo now, percent0, name
-
# Notify if requested
- update_progress_notify now, percent0, name
+ progress_notify now, percent0, name
+
+ # Touch my worker status
+ touch_job
end
private
- def update_progress_jobinfo now, percent0, name
+ def progress_notify now, percent0, name
# No delay provided ?
- return if JOB_UPDATE_INTERVAL.to_f.zero?
+ return if @config[:notify_after].nil?
# Still too early to notify again ?
- how_long_ago = (now.to_f - @progress_at.to_f)
- return unless how_long_ago > JOB_UPDATE_INTERVAL.to_f
+ how_long_ago = (now.to_f - @last_notify_at.to_f)
+ return unless how_long_ago > @config[:notify_after]
# Update bitrates
@current_bitrate = running_bitrate @transfer_sent
- set_info INFO_TRANFER_BITRATE, @current_bitrate.round(0)
+ set_info INFO_TRANFER_BITRATE, @current_bitrate.round(0)
# Log progress
stack = [
@@ -193,18 +188,6 @@ module RestFtpDaemon
stack2 = stack.map { |txt| ("%#{LOG_PIPE_LEN.to_i}s" % txt) }.join("\t")
log_debug "progress #{stack2} \t#{name}"
- # Remember when we last did it
- @progress_at = now
- end
-
- def update_progress_notify now, percent0, name
- # No delay provided ?
- return if @config[:notify_after].nil?
-
- # Still too early to notify again ?
- how_long_ago = (now.to_f - @notified_at.to_f)
- return unless how_long_ago > @config[:notify_after]
-
# Prepare and send notification
client_notify :progress, status: {
progress: percent0,
@@ -215,7 +198,7 @@ module RestFtpDaemon
}
# Remember when we last did it
- @notified_at = now
+ @last_notify_at = now
end
def get_bitrate delta_data, delta_time
|
transfer: only log updates when sending ready to send notifications, compute average bitrate between notifications
|
bmedici_rest-ftp-daemon
|
train
|
e423fd7264c4f145921e461037d571b35b6a9833
|
diff --git a/_postinstall.js b/_postinstall.js
index <HASH>..<HASH> 100755
--- a/_postinstall.js
+++ b/_postinstall.js
@@ -1,3 +1,5 @@
+#!/usr/bin/env node
+
// Broadcasts "Call for peace" message when package is installed in Russia, otherwise no-op
"use strict";
|
refactor: Add missing shebang to postinstall script
|
medikoo_es5-ext
|
train
|
c2d7b7361ac9ebfc63c0bda40f21f776a24906d5
|
diff --git a/src/java/com/threerings/media/util/DelayPath.java b/src/java/com/threerings/media/util/DelayPath.java
index <HASH>..<HASH> 100644
--- a/src/java/com/threerings/media/util/DelayPath.java
+++ b/src/java/com/threerings/media/util/DelayPath.java
@@ -22,15 +22,42 @@
package com.threerings.media.util;
import java.awt.Graphics2D;
+import java.awt.Point;
/**
* A convenience path that waits a specified amount of time.
*/
public class DelayPath extends TimedPath
{
+ /**
+ * Cause the current path to remain unchanged for the duration.
+ */
public DelayPath (long duration)
{
+ this(null, duration);
+ }
+
+ /**
+ * Move to the sprite to the supplied location then wait for the duration.
+ */
+ public DelayPath (int x, int y, long duration)
+ {
+ this(new Point(x, y), duration);
+ }
+
+ /**
+ * Move to the sprite to the supplied location then wait for the duration.
+ */
+ public DelayPath (Point source, long duration)
+ {
super(duration);
+ _source = source;
+ }
+
+ // documentation inherited
+ public void init (Pathable pable, long timestamp)
+ {
+ super.init(pable, timestamp);
}
// documentation inherited
@@ -42,8 +69,23 @@ public class DelayPath extends TimedPath
public boolean tick (Pathable pable, long tickstamp)
{
if (tickstamp >= _startStamp + _duration) {
+ if (_source != null) {
+ pable.setLocation(_source.x, _source.y);
+ }
pable.pathCompleted(tickstamp);
+ return (_source != null);
}
+
+ // If necessary, move the sprite to the supplied location
+ if (_source != null && (pable.getX() != _source.x ||
+ pable.getY() != _source.y)) {
+ pable.setLocation(_source.x, _source.y);
+ return true;
+ }
+
return false;
}
+
+ /** Source point. */
+ protected Point _source;
}
diff --git a/src/java/com/threerings/media/util/LineSegmentPath.java b/src/java/com/threerings/media/util/LineSegmentPath.java
index <HASH>..<HASH> 100644
--- a/src/java/com/threerings/media/util/LineSegmentPath.java
+++ b/src/java/com/threerings/media/util/LineSegmentPath.java
@@ -196,14 +196,14 @@ public class LineSegmentPath
pable.setLocation(node.loc.x, node.loc.y);
}
// and let the pathable know that we're done
- pable.pathCompleted(timestamp);
- return;
- }
+ pable.pathCompleted(timestamp);
+ return;
+ }
// and an enumeration of the path nodes
_niter = _nodes.iterator();
- // pretend like we were previously heading to our starting position
+ // pretend like we were previously heading to our starting position
_dest = getNextNode();
// begin traversing the path
|
Added the ability for DelayPath to set a location for the path.
Some whitespace cleanup.
git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@<I> <I>f4-<I>e9-<I>-aa3c-eee0fc<I>fb1
|
threerings_narya
|
train
|
03ad75e5e1a54e45cb1ef3aaace80c5ea52592f8
|
diff --git a/src/Accordion/accordion.spec.js b/src/Accordion/accordion.spec.js
index <HASH>..<HASH> 100644
--- a/src/Accordion/accordion.spec.js
+++ b/src/Accordion/accordion.spec.js
@@ -2,7 +2,7 @@
import React from 'react';
import { mount } from 'enzyme';
-import renderer from 'react-test-renderer';
+// import renderer from 'react-test-renderer';
import Accordion from './accordion';
import AccordionItem from '../AccordionItem/accordion-item';
@@ -163,17 +163,34 @@ describe('Accordion', () => {
});
// Needs more work:
- // it('works with multiple pre expanded accordion. Extra expands are just ignored.', () => {
- // const tree = renderer
- // .create(
- // <Accordion>
- // <AccordionItem expanded={true}>Fake Child</AccordionItem>
- // <AccordionItem expanded={true}>Fake Child</AccordionItem>
- // </Accordion>,
- // )
- // .toJSON();
- // expect(tree).toMatchSnapshot();
- // });
+ it('works with multiple pre expanded accordion. Extra expands are just ignored.', () => {
+ const hideBodyClassName = 'HIDE';
+ const wrapper = mount(
+ <Accordion accordion={true}>
+ <AccordionItem
+ expanded={true}
+ hideBodyClassName={hideBodyClassName}
+ >
+ Fake Child
+ </AccordionItem>
+ <AccordionItem
+ expanded={true}
+ hideBodyClassName={hideBodyClassName}
+ >
+ Fake Child
+ </AccordionItem>
+ </Accordion>,
+ );
+
+ expect(
+ wrapper
+ .instance()
+ .accordionStore.items.filter(item => item.expanded).length,
+ ).toEqual(1);
+ expect(
+ wrapper.findWhere(item => item.hasClass(hideBodyClassName)).length,
+ ).toEqual(1);
+ });
it('pre expanded accordion when accordion is false', () => {
const wrapper = mount(
|
Add test for 'works with multiple pre expanded accordion. Extra expands are just ignored.'
|
springload_react-accessible-accordion
|
train
|
c5921b6b86f9f10f54a2e9159193a8c887c8031d
|
diff --git a/modeshape-jcr/src/main/java/org/modeshape/jcr/query/JcrQueryResult.java b/modeshape-jcr/src/main/java/org/modeshape/jcr/query/JcrQueryResult.java
index <HASH>..<HASH> 100644
--- a/modeshape-jcr/src/main/java/org/modeshape/jcr/query/JcrQueryResult.java
+++ b/modeshape-jcr/src/main/java/org/modeshape/jcr/query/JcrQueryResult.java
@@ -42,6 +42,7 @@ import org.modeshape.jcr.query.NodeSequence.Restartable;
import org.modeshape.jcr.query.QueryResults.Columns;
import org.modeshape.jcr.query.engine.process.RestartableSequence;
import org.modeshape.jcr.query.engine.process.SecureSequence;
+import org.modeshape.jcr.value.Name;
/**
* The results of a query. This is not thread-safe because it relies upon JcrSession, which is not thread-safe. Also, although the
@@ -498,27 +499,29 @@ public class JcrQueryResult implements org.modeshape.jcr.api.query.QueryResult {
String propertyName = iterator.getPropertyNameForColumnName(columnName);
if (propertyName == null) return null;
- if (PseudoColumns.contains(propertyName, true)) {
- if (PseudoColumns.isPath(propertyName)) {
+ Name qName = iterator.context.getExecutionContext().getValueFactories().getNameFactory().create(propertyName);
+
+ if (PseudoColumns.contains(qName, true)) {
+ if (PseudoColumns.isPath(qName)) {
return iterator.jcrPath(cachedNode);
}
- if (PseudoColumns.isName(propertyName)) {
+ if (PseudoColumns.isName(qName)) {
return iterator.jcrName(cachedNode);
}
- if (PseudoColumns.isLocalName(propertyName)) {
+ if (PseudoColumns.isLocalName(qName)) {
return iterator.jcrLocalName(cachedNode);
}
- if (PseudoColumns.isDepth(propertyName)) {
+ if (PseudoColumns.isDepth(qName)) {
return iterator.jcrDepth(cachedNode);
}
- if (PseudoColumns.isId(propertyName)) {
+ if (PseudoColumns.isId(qName)) {
return iterator.jcrId(cachedNode);
}
- if (PseudoColumns.isScore(propertyName)) {
+ if (PseudoColumns.isScore(qName)) {
float score = batchAtRow.getScore(nodeIndex);
return iterator.jcrDouble(score);
}
- if (PseudoColumns.isUuid(propertyName)) {
+ if (PseudoColumns.isUuid(qName)) {
return iterator.jcrUuid(cachedNode);
}
}
|
MODE-<I> - Support fully-qualified pseudocolumn names in JCR queries
|
ModeShape_modeshape
|
train
|
7cd56f69f0c9de47cfe29172fff773a13fc53b43
|
diff --git a/elifetools/parseJATS.py b/elifetools/parseJATS.py
index <HASH>..<HASH> 100644
--- a/elifetools/parseJATS.py
+++ b/elifetools/parseJATS.py
@@ -906,7 +906,7 @@ def components(soup):
# There are only some parent tags we care about for components
# and only check two levels of parentage
- parent_nodenames = ["sub-article", "fig-group", "fig", "boxed-text"]
+ parent_nodenames = ["sub-article", "fig-group", "fig", "boxed-text", "table-wrap"]
parent_tag = first_parent(tag, parent_nodenames)
if parent_tag:
# For fig-group we actually want the first fig of the fig-group as the parent
|
table-wrap can have children too.
|
elifesciences_elife-tools
|
train
|
68af3ed311a55afb5553dba03b7890c86ee6bbd2
|
diff --git a/metanl/wordlist.py b/metanl/wordlist.py
index <HASH>..<HASH> 100644
--- a/metanl/wordlist.py
+++ b/metanl/wordlist.py
@@ -140,25 +140,32 @@ def multilingual_wordlist(langs, scale=1e9):
return merge_lists(weighted_lists)
-def get_frequency(word, lang, default_freq=0):
+def get_frequency(word, lang, default_freq=0, scale=1e9):
"""
Looks up a word's frequency in our preferred frequency list for the given
language.
- >>> get_frequency('normalization', 'en')
- 223058.0
- >>> get_frequency('Normalization', 'en')
- 223058.0
+ >>> get_frequency('the', 'en', scale=42)
+ 42.0
+ >>> int(get_frequency('normalization', 'en'))
+ 25673
+ >>> int(get_frequency('Normalization', 'en'))
+ 25673
>>> get_frequency('weirdification', 'en', 100.0)
100.0
"""
freqs = get_wordlist(lang)
+ factor = scale / freqs.max_freq()
if " " in word:
raise ValueError("get_frequency only can only look up single words, "
"but %r contains a space" % word)
- return freqs.get(preprocess_text(word).lower(), default_freq)
+ lookup = preprocess_text(word).lower()
+ if lookup not in freqs:
+ return default_freq
+ else:
+ return factor * freqs[lookup]
def multilingual_word_frequency(word, default_freq=0):
return get_frequency(word, 'multi', default_freq)
|
auto-scaling in get_frequency, so we won't have to always load a multilingual wordlist
|
commonsense_metanl
|
train
|
5f9e0d6ddf77ba661217238a5239ee2c739ac977
|
diff --git a/gwt-material/src/main/java/gwt/material/design/client/base/HasCounter.java b/gwt-material/src/main/java/gwt/material/design/client/base/HasCounter.java
index <HASH>..<HASH> 100644
--- a/gwt-material/src/main/java/gwt/material/design/client/base/HasCounter.java
+++ b/gwt-material/src/main/java/gwt/material/design/client/base/HasCounter.java
@@ -9,9 +9,9 @@ package gwt.material.design.client.base;
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
diff --git a/gwt-material/src/main/java/gwt/material/design/client/base/mixin/CounterMixin.java b/gwt-material/src/main/java/gwt/material/design/client/base/mixin/CounterMixin.java
index <HASH>..<HASH> 100644
--- a/gwt-material/src/main/java/gwt/material/design/client/base/mixin/CounterMixin.java
+++ b/gwt-material/src/main/java/gwt/material/design/client/base/mixin/CounterMixin.java
@@ -9,9 +9,9 @@ package gwt.material.design.client.base.mixin;
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
diff --git a/gwt-material/src/main/resources/gwt/material/design/public/css/overridecss.css b/gwt-material/src/main/resources/gwt/material/design/public/css/overridecss.css
index <HASH>..<HASH> 100644
--- a/gwt-material/src/main/resources/gwt/material/design/public/css/overridecss.css
+++ b/gwt-material/src/main/resources/gwt/material/design/public/css/overridecss.css
@@ -556,6 +556,13 @@ nav .nav-wrapper .collapsible-body {
ul.side-nav .sideBarBadge {
margin-top: 20px !important;
}
+
+nav ul a span.badge {
+ margin-left: 8px !important;
+ float: right;
+ margin-top: 20px;
+}
+
/** DROPDOWN **/
.dropdown-content {
max-height: 70vh !important;
|
Badges in NavBar, fixed some code scheme
|
GwtMaterialDesign_gwt-material
|
train
|
7ed554d7195dda7d6fa55e116670a6aabd48a32a
|
diff --git a/arcana/repository/directory.py b/arcana/repository/directory.py
index <HASH>..<HASH> 100644
--- a/arcana/repository/directory.py
+++ b/arcana/repository/directory.py
@@ -22,7 +22,7 @@ logger = logging.getLogger('arcana')
class DirectoryRepository(BaseRepository):
"""
- An 'Repository' class for data stored simply in file-system
+ A 'Repository' class for data stored simply in file-system
directories. Can be a single directory if it contains only one subject
and visit, otherwise if sub-directories are present (that aren't
recognised as single filesets) then they are assumed to be
@@ -210,39 +210,11 @@ class DirectoryRepository(BaseRepository):
all_records = []
for session_path, dirs, files in os.walk(self.root_dir):
relpath = op.relpath(session_path, self.root_dir)
- if relpath == '.':
- path_parts = []
- else:
- path_parts = relpath.split(op.sep)
- depth = len(path_parts)
- if depth == self._depth:
- # Load input data
- from_study = None
- elif (depth == (self._depth + 1) and
- self.PROV_DIR in dirs):
- # Load study output
- from_study = path_parts.pop()
- elif (depth < self._depth and
- any(not f.startswith('.') for f in files)):
- # Check to see if there are files in upper level
- # directories, which shouldn't be there (ignoring
- # "hidden" files that start with '.')
- raise ArcanaBadlyFormattedDirectoryRepositoryError(
- "Files ('{}') not permitted at {} level in local "
- "repository".format("', '".join(files),
- ('subject'
- if depth else 'project')))
- else:
- # Not a directory that contains data files or directories
+ path_parts = relpath.split(op.sep) if relpath != '.' else []
+ ids = self._extract_ids_from_path(path_parts, dirs, files)
+ if ids is None:
continue
- if len(path_parts) == 2:
- subj_id, visit_id = path_parts
- elif len(path_parts) == 1:
- subj_id = path_parts[0]
- visit_id = self.DEFAULT_SUBJECT_ID
- else:
- subj_id = self.DEFAULT_SUBJECT_ID
- visit_id = self.DEFAULT_VISIT_ID
+ subj_id, visit_id, from_study = ids
# Check for summaries and filtered IDs
if subj_id == self.SUMMARY_NAME:
subj_id = None
@@ -294,6 +266,38 @@ class DirectoryRepository(BaseRepository):
op.join(base_prov_dir, fname)))
return all_filesets, all_fields, all_records
+ def _extract_ids_from_path(self, path_parts, dirs, files):
+ depth = len(path_parts)
+ if depth == self._depth:
+ # Load input data
+ from_study = None
+ elif (depth == (self._depth + 1) and
+ self.PROV_DIR in dirs):
+ # Load study output
+ from_study = path_parts.pop()
+ elif (depth < self._depth and
+ any(not f.startswith('.') for f in files)):
+ # Check to see if there are files in upper level
+ # directories, which shouldn't be there (ignoring
+ # "hidden" files that start with '.')
+ raise ArcanaBadlyFormattedDirectoryRepositoryError(
+ "Files ('{}') not permitted at {} level in local "
+ "repository".format("', '".join(files),
+ ('subject'
+ if depth else 'project')))
+ else:
+ # Not a directory that contains data files or directories
+ return None
+ if len(path_parts) == 2:
+ subj_id, visit_id = path_parts
+ elif len(path_parts) == 1:
+ subj_id = path_parts[0]
+ visit_id = self.DEFAULT_SUBJECT_ID
+ else:
+ subj_id = self.DEFAULT_SUBJECT_ID
+ visit_id = self.DEFAULT_VISIT_ID
+ return subj_id, visit_id, from_study
+
def fileset_path(self, item, fname=None):
if fname is None:
fname = item.fname
|
slightly altered DirectoryRepository to allow BidsRepository to inherit
from it
|
MonashBI_arcana
|
train
|
de0ea3866370ec61581f910cf393a3cc97eba32f
|
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb
index <HASH>..<HASH> 100755
--- a/activerecord/lib/active_record/associations.rb
+++ b/activerecord/lib/active_record/associations.rb
@@ -1375,7 +1375,7 @@ module ActiveRecord
dependent_conditions = []
dependent_conditions << "#{reflection.primary_key_name} = \#{record.quoted_id}"
dependent_conditions << "#{reflection.options[:as]}_type = '#{base_class.name}'" if reflection.options[:as]
- dependent_conditions << sanitize_sql(reflection.options[:conditions]) if reflection.options[:conditions]
+ dependent_conditions << sanitize_sql(reflection.options[:conditions], reflection.quoted_table_name) if reflection.options[:conditions]
dependent_conditions << extra_conditions if extra_conditions
dependent_conditions = dependent_conditions.collect {|where| "(#{where})" }.join(" AND ")
dependent_conditions = dependent_conditions.gsub('@', '\@')
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index <HASH>..<HASH> 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -719,6 +719,12 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
assert Client.find(:all, :conditions => "firm_id=#{firm.id}").empty?
end
+ def test_dependence_for_associations_with_hash_condition
+ david = authors(:david)
+ post = posts(:thinking).id
+ assert_difference('Post.count', -1) { assert david.destroy }
+ end
+
def test_destroy_dependent_when_deleted_from_association
firm = Firm.find(:first)
assert_equal 2, firm.clients.size
diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb
index <HASH>..<HASH> 100644
--- a/activerecord/test/models/author.rb
+++ b/activerecord/test/models/author.rb
@@ -25,7 +25,7 @@ class Author < ActiveRecord::Base
has_many :comments_with_order_and_conditions, :through => :posts, :source => :comments, :order => 'comments.body', :conditions => "comments.body like 'Thank%'"
has_many :comments_with_include, :through => :posts, :source => :comments, :include => :post
- has_many :thinking_posts, :class_name => 'Post', :conditions => { :title => 'So I was thinking' }
+ has_many :thinking_posts, :class_name => 'Post', :conditions => { :title => 'So I was thinking' }, :dependent => :delete_all
has_many :welcome_posts, :class_name => 'Post', :conditions => { :title => 'Welcome to the weblog' }
has_many :comments_desc, :through => :posts, :source => :comments, :order => 'comments.id DESC'
diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb
index <HASH>..<HASH> 100644
--- a/activerecord/test/models/company.rb
+++ b/activerecord/test/models/company.rb
@@ -78,13 +78,6 @@ class DependentFirm < Company
has_many :companies, :foreign_key => 'client_of', :order => "id", :dependent => :nullify
end
-class ExclusivelyDependentFirm < Company
- has_one :account, :foreign_key => "firm_id", :dependent => :delete
- has_many :dependent_sanitized_conditional_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all, :conditions => "name = 'BigShot Inc.'"
- has_many :dependent_conditional_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all, :conditions => ["name = ?", 'BigShot Inc.']
- has_many :dependent_hash_conditional_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all, :conditions => {:name => 'BigShot Inc.'}
-end
-
class Client < Company
belongs_to :firm, :foreign_key => "client_of"
belongs_to :firm_with_basic_id, :class_name => "Firm", :foreign_key => "firm_id"
@@ -125,6 +118,12 @@ class Client < Company
end
end
+class ExclusivelyDependentFirm < Company
+ has_one :account, :foreign_key => "firm_id", :dependent => :delete
+ has_many :dependent_sanitized_conditional_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all, :conditions => "name = 'BigShot Inc.'"
+ has_many :dependent_conditional_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all, :conditions => ["name = ?", 'BigShot Inc.']
+ has_many :dependent_hash_conditional_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :order => "id", :dependent => :delete_all, :conditions => {:name => 'BigShot Inc.'}
+end
class SpecialClient < Client
end
|
Ensure :dependent => :delete_all works for association with hash conditions
|
rails_rails
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.