hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
a5fa8535917e4c2cb16392970602ef62ed210ad9
diff --git a/compiler/quilt/test/test_import.py b/compiler/quilt/test/test_import.py index <HASH>..<HASH> 100644 --- a/compiler/quilt/test/test_import.py +++ b/compiler/quilt/test/test_import.py @@ -483,6 +483,32 @@ class ImportTest(QuiltTestCase): pkg._set(['dataframes', 'memory'], pd.DataFrame()) with self.assertRaises(ValueError): assert pkg.dataframes.memory(asa=test_lambda) is testdata + + def test_load_by_hash(self): + """ + Tests loading two different versions of the same + package using command.load and specifying the package + hash. + """ + # Old Version + mydir = os.path.dirname(__file__) + build_path = os.path.join(mydir, './build.yml') + command.build('foo/package', build_path) + package = command.load('foo/package') + pkghash = package._package.get_hash() + # New Version + mydir = os.path.dirname(__file__) + build_path = os.path.join(mydir, './build_simple.yml') + command.build('foo/package', build_path) + command.ls() + + load_pkg_new = command.load('foo/package') + load_pkg_old = command.load('foo/package:h:%s' % pkghash) + assert load_pkg_old._package.get_hash() == pkghash + assert load_pkg_new.foo + with self.assertRaises(AttributeError): + load_pkg_new.dataframes + diff --git a/compiler/quilt/tools/command.py b/compiler/quilt/tools/command.py index <HASH>..<HASH> 100644 --- a/compiler/quilt/tools/command.py +++ b/compiler/quilt/tools/command.py @@ -1281,17 +1281,25 @@ def reset_password(team, username): def _load(package): info = parse_package_extended(package) - team, user, name = info.team, info.user, info.name - - pkgobj = PackageStore.find_package(team, user, name) + # TODO: support tags & versions. + if info.tag is not None: + raise CommandException("Loading packages by tag is not supported.") + if info.version is not None: + raise CommandException("Loading packages by version is not supported.") + + pkgobj = PackageStore.find_package(info.team, + info.user, + info.name, + pkghash=info.hash) if pkgobj is None: raise CommandException("Package {package} not found.".format(package=package)) node = _from_core_node(pkgobj, pkgobj.get_contents()) return node, pkgobj, info def load(pkginfo): - """functional interface to "from quilt.data.USER import PKG""" - # TODO: support hashes/versions/etc. + """ + functional interface to "from quilt.data.USER import PKG" + """ return _load(pkginfo)[0] def export(package, output_path='.', force=False, symlinks=False): diff --git a/compiler/quilt/tools/package.py b/compiler/quilt/tools/package.py index <HASH>..<HASH> 100644 --- a/compiler/quilt/tools/package.py +++ b/compiler/quilt/tools/package.py @@ -38,6 +38,8 @@ class Package(object): contents = self._load_contents(pkghash) self._contents = contents + if pkghash is not None: + assert self.get_hash() == pkghash def __getitem__(self, item): """Get a (core) node from this package. diff --git a/compiler/quilt/tools/store.py b/compiler/quilt/tools/store.py index <HASH>..<HASH> 100644 --- a/compiler/quilt/tools/store.py +++ b/compiler/quilt/tools/store.py @@ -119,7 +119,7 @@ class PackageStore(object): return store_dirs @classmethod - def find_package(cls, team, user, package, store_dir=None): + def find_package(cls, team, user, package, pkghash=None, store_dir=None): """ Finds an existing package in one of the package directories. """ @@ -127,7 +127,7 @@ class PackageStore(object): dirs = cls.find_store_dirs() for store_dir in dirs: store = PackageStore(store_dir) - pkg = store.get_package(team, user, package) + pkg = store.get_package(team, user, package, pkghash=pkghash) if pkg is not None: return pkg return None @@ -162,7 +162,7 @@ class PackageStore(object): # TODO: find a package instance other than 'latest', e.g. by # looking-up by hash, tag or version in the local store. - def get_package(self, team, user, package): + def get_package(self, team, user, package, pkghash=None): """ Gets a package from this store. """ @@ -174,7 +174,8 @@ class PackageStore(object): store=self, user=user, package=package, - path=path + path=path, + pkghash=pkghash, ) except PackageException: pass
Load by package hash (#<I>) ### Load by package hash Extend the load command to allow find package instances by their hash. Local tags and versions aren't currently supported so we should fail to warn the user instead of silently returning latest.
quiltdata_quilt
train
e7f21cf37c7e3d10fe4840e6a41f2dc83b3171e6
diff --git a/src/getAttributes.js b/src/getAttributes.js index <HASH>..<HASH> 100644 --- a/src/getAttributes.js +++ b/src/getAttributes.js @@ -21,7 +21,7 @@ function attributeEntryToString(attribute, context) { * ```js getAttributes({ tabindex: 0, - 'data-language': function (context) { return content.language; }, + 'data-language': function (context) { return context.language; }, 'data-otherStuff': 'value' }) // => ' tabindex="0" data-language="JavaScript" data-otherStuff="value"' ```
Fix context -> context typo in example comment
11ty_eleventy-plugin-syntaxhighlight
train
98cd01188e24134175482356965a7c10283b4c07
diff --git a/src/actions/ViewAction.php b/src/actions/ViewAction.php index <HASH>..<HASH> 100644 --- a/src/actions/ViewAction.php +++ b/src/actions/ViewAction.php @@ -59,7 +59,7 @@ class ViewAction extends Action public function run($id = null) { - $this->_id = $this->_id ?: $id ?: Yii::$app->request->get('id'); + $this->_id = $this->_id ?: $id ?: Yii::$app->request->get('id') ?: Yii::$app->request->post($this->collection->formName)['id']; $id = $this->_id; if (empty($id)) {
ViewAction can get ID param from post
hiqdev_hipanel-core
train
4ed37407327bf0c56f546c3a2f076e25e8efb575
diff --git a/src/test/java/com/moandjiezana/toml/SerializerTest.java b/src/test/java/com/moandjiezana/toml/SerializerTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/moandjiezana/toml/SerializerTest.java +++ b/src/test/java/com/moandjiezana/toml/SerializerTest.java @@ -3,6 +3,7 @@ package com.moandjiezana.toml; import org.junit.Test; import java.io.UnsupportedEncodingException; +import java.text.SimpleDateFormat; import java.util.*; import static org.junit.Assert.assertEquals; @@ -27,9 +28,8 @@ public class SerializerTest { o.aDouble = -5.43; o.aBoolean = false; - String theDate = "2015-05-31T08:44:03-07:00"; - Toml dateToml = new Toml().parse("a_date = " + theDate); - o.aDate = dateToml.getDate("a_date"); + o.aDate = new Date(); + String theDate = formatDate(o.aDate); String serialized = Toml.serializeFrom(o); String expected = "aString = \"hello\"\n" + @@ -42,6 +42,18 @@ public class SerializerTest { assertEquals(expected, serialized); } + private String formatDate(Date date) { + // Copying the date formatting code from DateSerializer isn't optimal, but + // I can't see any other way to check date serialization - the test gets + // run in multiple time zones, so we can't just hard-code a time zone. + String dateString = new SimpleDateFormat("yyyy-MM-dd'T'HH:m:ss").format(date); + Calendar calendar = new GregorianCalendar(); + int tzOffset = (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (60 * 1000); + dateString += String.format("%+03d:%02d", tzOffset / 60, tzOffset % 60); + + return dateString; + } + @Test public void serializesNestedMap() { class SubChild {
Fix Date serialization testing. The test can be run in any time zone, so always test with a Date instance from the local time zone where the test is being run.
mwanji_toml4j
train
d2b078e28af7fb69b8b3f279afb315335a5e0114
diff --git a/09_compare_best_designs.py b/09_compare_best_designs.py index <HASH>..<HASH> 100755 --- a/09_compare_best_designs.py +++ b/09_compare_best_designs.py @@ -207,8 +207,7 @@ class SequenceClusterMetric (Metric): return design.sequence_cluster def _cluster_by_k_mediods(self, designs, verbose=False): - num_designs = len(designs) - if num_designs < 2: return + raise NotImplementedError def _cluster_hierarchically(self, designs, verbose=False): import scipy.spatial.distance as sp_dist diff --git a/libraries/structures.py b/libraries/structures.py index <HASH>..<HASH> 100644 --- a/libraries/structures.py +++ b/libraries/structures.py @@ -234,6 +234,7 @@ def read_and_calculate(workspace, pdb_paths): def xyz_to_array(xyz): return np.array([float(x) for x in xyz]) + class IOError (IOError): no_stack_trace = True diff --git a/show_my_designs.py b/show_my_designs.py index <HASH>..<HASH> 100755 --- a/show_my_designs.py +++ b/show_my_designs.py @@ -10,6 +10,7 @@ class PipDesign (smd.Design): self._models = structures.load( self.directory, use_cache=use_cache, + require_io_dir=False, ) diff --git a/tools b/tools index <HASH>..<HASH> 160000 --- a/tools +++ b/tools @@ -1 +1 @@ -Subproject commit dc64d80a6a7b8c50f446c268c69d18015e4e3be1 +Subproject commit d93a2b8c2b3f70b598a38ac2af7bcf34e420fcc1
More gracefully handle a few corner cases.
Kortemme-Lab_pull_into_place
train
506c5562e4668fffa5449fa557e63a23c902047c
diff --git a/src/main/java/org/gwtbootstrap3/extras/toggleswitch/client/ui/base/ToggleSwitchBase.java b/src/main/java/org/gwtbootstrap3/extras/toggleswitch/client/ui/base/ToggleSwitchBase.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/gwtbootstrap3/extras/toggleswitch/client/ui/base/ToggleSwitchBase.java +++ b/src/main/java/org/gwtbootstrap3/extras/toggleswitch/client/ui/base/ToggleSwitchBase.java @@ -346,14 +346,13 @@ public class ToggleSwitchBase extends Widget implements HasSize<SizeType>, HasVa $wnd.jQuery(e).bootstrapSwitch(); var me = this; - $wnd.jQuery(e).on('switchChange', function (em, data) { - me.@org.gwtbootstrap3.extras.toggleswitch.client.ui.base.ToggleSwitchBase::onChange(Z)(data.value); + $wnd.jQuery(e).on('switchChange.bootstrapSwitch', function (em, state) { + me.@org.gwtbootstrap3.extras.toggleswitch.client.ui.base.ToggleSwitchBase::onChange(Z)(state); }); - }-*/; private native void switchDestroy(Element e) /*-{ - $wnd.jQuery(e).off('switchChange'); + $wnd.jQuery(e).off('switchChange.bootstrapSwitch'); $wnd.jQuery(e).bootstrapSwitch('destroy'); }-*/;
Use namespaced events and proper parameters in ToggleSwitch.switchInit. This fixes a regression in firing ValueChangedEvent after updating the version of the Bootstrap Switch library.
gwtbootstrap3_gwtbootstrap3-extras
train
67c95169c722a05c3201c72c9c886ab3a149cf39
diff --git a/sportsref/utils.py b/sportsref/utils.py index <HASH>..<HASH> 100644 --- a/sportsref/utils.py +++ b/sportsref/utils.py @@ -1,3 +1,6 @@ +from builtins import range +import ctypes +import multiprocessing as mp import re import time @@ -8,6 +11,11 @@ import requests import sportsref +THROTTLE_DELAY = 0.5 + +throttle_lock = mp.Lock() +last_request_time = mp.Value(ctypes.c_longdouble, + time.time() - 2 * THROTTLE_DELAY) @sportsref.decorators.memoize @sportsref.decorators.cache_html @@ -20,12 +28,17 @@ def get_html(url): :returns: a string of HTML. """ + # first, sleep until THROTTLE_DELAY secs have passed since last request + with throttle_lock: + wait_left = THROTTLE_DELAY - (time.time() - last_request_time.value) + if wait_left > 0: + time.sleep(wait_left) + K = 60*3 # K is length of next backoff (in seconds) - TOTAL_TIME = 0.4 # num of secs we we wait between last request & return html = None - numTries = 0 - while not html and numTries < 10: - numTries += 1 + num_tries = 0 + while not html and num_tries < 10: + num_tries += 1 start = time.time() try: response = requests.get(url) @@ -45,19 +58,18 @@ def get_html(url): else: print 'Waiting {} seconds...'.format(K) # sleep - for _ in xrange(K): - time.sleep(1) + time.sleep(K) # backoff gets doubled, capped at 1 hour K *= 2 K = min(K, 60*60) else: # Some other error code raise e - timeOnRequest = time.time() - start - timeRemaining = int(1000 * (TOTAL_TIME - timeOnRequest)) # in milliseconds - for _ in xrange(timeRemaining): - # wait one millisecond - time.sleep(0.001) + + # update last_request_time + with throttle_lock: + last_request_time.value = time.time() + return html
first attempt at multiprocessing throttling in get_html
mdgoldberg_sportsref
train
5cbaadb4f1ff140183269d80b7dc57c744e63d90
diff --git a/abl/vpath/base/fs.py b/abl/vpath/base/fs.py index <HASH>..<HASH> 100644 --- a/abl/vpath/base/fs.py +++ b/abl/vpath/base/fs.py @@ -1040,7 +1040,8 @@ class FileSystem(object): def walk(self, top, topdown=True, followlinks=True): names = self.listdir(top) - dirs, nondirs = [], [] + dirs = [] + nondirs = [] for name in names: if self.isdir(top / name): dirs.append(name) diff --git a/tests/test_memory.py b/tests/test_memory.py index <HASH>..<HASH> 100644 --- a/tests/test_memory.py +++ b/tests/test_memory.py @@ -316,16 +316,13 @@ class TestRemovalOfFilesAndDirs(TestCase): if p.exists(): p.remove() - with p.open("w") as outf: - outf.write("foo") + create_file(p, content="foo") mode = p.info().mode new_mode = mode | stat.S_IXUSR - p.info(dict(mode=new_mode)) - self.assertEqual( - p.info().mode, - new_mode, - ) + p.info(set_info=dict(mode=new_mode)) + self.assertEqual(p.info().mode, + new_mode) def test_removing_non_empty_dirs(self): @@ -333,13 +330,9 @@ class TestRemovalOfFilesAndDirs(TestCase): assert not p.exists() p.mkdir() - with (p / "some-file.txt").open("w") as outf: - outf.write("foobar") + create_file(p / "some-file.txt", content="foobar") - self.assertRaises( - OSError, - p.remove, - ) + self.assertRaises(OSError, p.remove) (p / "some-file.txt").remove() p.remove() @@ -347,7 +340,6 @@ class TestRemovalOfFilesAndDirs(TestCase): assert not p.exists() p.mkdir() - with (p / "some-file.txt").open("w") as outf: - outf.write("foobar") + create_file(p / "some-file.txt", content="foobar") p.remove(recursive=True)
Style and use create_file over code repetition
AbletonAG_abl.vpath
train
a844ffb36b756059aee54783e4207e7297eee75e
diff --git a/karma.conf.js b/karma.conf.js index <HASH>..<HASH> 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -13,7 +13,12 @@ module.exports = function (config) { // list of files / patterns to load in the browser files: [ - 'test/*Spec.js', + { + pattern: 'test/*Spec.js', + watched: false, + included: true, + served: true + }, 'node_modules/materialize-css/bin/materialize.js' ], @@ -39,9 +44,9 @@ module.exports = function (config) { reporters: ['mocha'], // reporter options - mochaReporter: { - showDiff: true - }, + // mochaReporter: { + // showDiff: true + // }, // web server port port: 9876,
Fixes karma bug that made the tests run twice (#<I>)
react-materialize_react-materialize
train
0d84de0340e5fddc726b907da2fb29b31905da08
diff --git a/src/main/java/com/couchbase/lite/support/Batcher.java b/src/main/java/com/couchbase/lite/support/Batcher.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/couchbase/lite/support/Batcher.java +++ b/src/main/java/com/couchbase/lite/support/Batcher.java @@ -200,12 +200,26 @@ public class Batcher<T> { } } + /* + * calculates the delay to use when scheduling the next batch of objects to process + * There is a balance required between clearing down the input queue as fast as possible + * and not exhausting downstream system resources such as sockets and http response buffers + * by processing too many batches concurrently. + */ private int delayToUse() { + + //initially set the delay to the default value for this Batcher int delayToUse = delay; + + //get the time interval since the last batch completed to the current system time long delta = (System.currentTimeMillis() - lastProcessedTime); + + //if the time interval is greater or equal to the default delay then set the + // delay so that the next batch gets scheduled to process immediately if (delta >= delay) { delayToUse = 0; } + return delayToUse; } }
issue couchbase/couchbase-lite-java/issues/<I> Added some explanatory comments around the calculation of the scheduler delay to use when submitting a batch job
couchbase_couchbase-lite-java-core
train
12571b6f308063d64a7e94eab9fd7921db036ba7
diff --git a/isvcs/mock.go b/isvcs/mock.go index <HASH>..<HASH> 100644 --- a/isvcs/mock.go +++ b/isvcs/mock.go @@ -408,7 +408,7 @@ func init() { End: "0s-ago", Start: "1h-ago", }, - YAxisLabel: "% CPU", + YAxisLabel: "% Used", ReturnSet: "EXACT", Type: "area", Tags: map[string][]string{"isvcname": []string{"zookeeper"}},
Change axis name back to match what the acceptance tests are looking for. I should not have changed this in the first place.
control-center_serviced
train
8f96155384f922d7b0464cb9ad9ba32e8b6acde4
diff --git a/docroot/modules/custom/ymca_camp_du_nord/src/Form/CdnFormFull.php b/docroot/modules/custom/ymca_camp_du_nord/src/Form/CdnFormFull.php index <HASH>..<HASH> 100644 --- a/docroot/modules/custom/ymca_camp_du_nord/src/Form/CdnFormFull.php +++ b/docroot/modules/custom/ymca_camp_du_nord/src/Form/CdnFormFull.php @@ -102,14 +102,19 @@ class CdnFormFull extends FormBase { $default_arrival_date = $dt->format('Y-m-d'); } else { + $now = new \DateTime('now', $tz); + $nowTimestamp = $now->format('U'); $nearest_date = $this->database->query( 'SELECT cstartdate.field_cdn_prd_start_date_value FROM {cdn_prs_product__field_cdn_prd_start_date} cstartdate LEFT JOIN {cdn_prs_product__field_cdn_prd_capacity_left} cleft ON cstartdate.entity_id = cleft.entity_id WHERE cleft.field_cdn_prd_capacity_left_value != 0 - AND cstartdate.field_cdn_prd_start_date_value >= (NOW() + INTERVAL :offset DAY) + AND cstartdate.field_cdn_prd_start_date_value >= (FROM_UNIXTIME(:now) + INTERVAL :offset DAY) ORDER BY cstartdate.field_cdn_prd_start_date_value ASC LIMIT 1', - [':offset' => self::START_DAYS_OFFSET] + [ + ':now' => $nowTimestamp, + ':offset' => self::START_DAYS_OFFSET, + ] ) ->fetchCol();
Replace NOW() with proper timestamp
ymcatwincities_openy
train
fae1884d23fada3c9c2fb9d2d7d08d20b888e7e1
diff --git a/lib/rules/padded-blocks.js b/lib/rules/padded-blocks.js index <HASH>..<HASH> 100644 --- a/lib/rules/padded-blocks.js +++ b/lib/rules/padded-blocks.js @@ -17,20 +17,6 @@ module.exports = function(context) { NEVER_MESSAGE = "Block must not be padded by blank lines."; /** - * Retrieves an array of all comments defined inside the given node. - * @param {ASTNode} node The AST node. - * @returns {ASTNode[]} An array of comment nodes. - */ - function getCommentsInNode(node) { - var allComments = context.getAllComments(); - - return allComments.filter(function(comment) { - return node.range[0] < comment.range[0] && - node.range[1] > comment.range[1]; - }); - } - - /** * Checks if the location of a node or token is before the location of another node or token * @param {ASTNode|Token} a The node or token to check if its location is before b. * @param {ASTNode|Token} b The node or token which will be compared with a. @@ -50,8 +36,15 @@ module.exports = function(context) { first = node.body[0], firstLine = first.loc.start.line, expectedFirstLine = blockStart + 2, - comments = getCommentsInNode(node), - firstComment = comments[0]; + leadingComments = (node.body[0].leadingComments || []).slice(), + firstComment; + + while (leadingComments.length > 0 && + leadingComments[0].loc.start.line <= node.loc.start.line) { + leadingComments.shift(); + } + + firstComment = leadingComments[0]; if (firstComment && isLocatedBefore(firstComment, first)) { firstLine = firstComment.loc.start.line; @@ -71,8 +64,15 @@ module.exports = function(context) { lastToken = context.getLastToken(last), lastLine = lastToken.loc.end.line, expectedLastLine = blockEnd - 2, - comments = getCommentsInNode(node), - lastComment = comments[comments.length - 1]; + trailingComments = (node.body[node.body.length - 1].trailingComments || []).slice(), + lastComment; + + while (trailingComments.length > 0 && + trailingComments[trailingComments.length - 1].loc.end.line >= node.loc.end.line) { + trailingComments.pop(); + } + + lastComment = trailingComments[trailingComments.length - 1]; if (lastComment && isLocatedBefore(lastToken, lastComment)) { lastLine = lastComment.loc.end.line; diff --git a/tests/lib/rules/padded-blocks.js b/tests/lib/rules/padded-blocks.js index <HASH>..<HASH> 100644 --- a/tests/lib/rules/padded-blocks.js +++ b/tests/lib/rules/padded-blocks.js @@ -30,6 +30,8 @@ ruleTester.run("padded-blocks", rule, { {code: "{\n\na();\n//comment\n\n}" }, {code: "{\n\na()\n//comment\n\n}" }, {code: "{\n\na = 1\n\n}" }, + {code: "{//comment\n\na();\n\n}" }, + {code: "{\n\na();\n\n/* comment */ }" }, {code: "{\na();\n}", options: ["never"]}, {code: "{\na();}", options: ["never"]}, {code: "{a();\n}", options: ["never"]},
Fix: Allow same-line comments in padded-blocks (fixes #<I>) This allows comments that occur on the same line as the opening or closing brace.
eslint_eslint
train
3fe0f7bdc2d6db9d5fa9b28318aa0558a1fe815d
diff --git a/src/RegExp.php b/src/RegExp.php index <HASH>..<HASH> 100644 --- a/src/RegExp.php +++ b/src/RegExp.php @@ -4,7 +4,7 @@ declare(strict_types = 1); namespace Innmind\Immutable; use Innmind\Immutable\Exception\{ - DomainException, + LogicException, InvalidRegex, }; @@ -15,7 +15,7 @@ final class RegExp private function __construct(string $pattern) { if (@\preg_match($pattern, '') === false) { - throw new DomainException($pattern, \preg_last_error()); + throw new LogicException($pattern, \preg_last_error()); } $this->pattern = $pattern; diff --git a/tests/RegExpTest.php b/tests/RegExpTest.php index <HASH>..<HASH> 100644 --- a/tests/RegExpTest.php +++ b/tests/RegExpTest.php @@ -7,7 +7,7 @@ use Innmind\Immutable\{ RegExp, Str, Map, - Exception\DomainException + Exception\LogicException }; use PHPUnit\Framework\TestCase; @@ -30,7 +30,7 @@ class RegExpTest extends TestCase public function testThrowWhenInvalidRegexp() { - $this->expectException(DomainException::class); + $this->expectException(LogicException::class); RegExp::of('/foo'); }
throw LogicException to explicit the fact that user must change his code
Innmind_Immutable
train
6846c327e120b88334853bcc947f522b2cd9e377
diff --git a/spec/unit/parser/scope.rb b/spec/unit/parser/scope.rb index <HASH>..<HASH> 100755 --- a/spec/unit/parser/scope.rb +++ b/spec/unit/parser/scope.rb @@ -43,7 +43,7 @@ describe Puppet::Parser::Scope do describe "and the variable is qualified" do before do @parser = Puppet::Parser::Parser.new() - @compiler = Puppet::Parser::Compiler.new(stub("node", :name => "foonode"), @parser) + @compiler = Puppet::Parser::Compiler.new(stub("node", :name => "foonode", :classes => []), @parser) @scope.compiler = @compiler @scope.parser = @parser end
Fixing some recently broken Scope tests
puppetlabs_puppet
train
2e95d263e1eb5f765edd9e7cf01b6060455d7a2c
diff --git a/src/baguetteBox.js b/src/baguetteBox.js index <HASH>..<HASH> 100644 --- a/src/baguetteBox.js +++ b/src/baguetteBox.js @@ -25,6 +25,7 @@ var baguetteBox = function(selector, userOptions) { var options = { captions: true, buttons: true, + async: false, preload: 2 }; // Update options object @@ -243,7 +244,8 @@ var baguetteBox = function(selector, userOptions) { image.onload = function() { var spinner = this.parentNode.getElementsByClassName('spinner')[0]; this.parentNode.removeChild(spinner); - callback(); + if(!options.async) + callback(); }; figure.innerHTML = '<div class="spinner">' + '<div class="double-bounce1"></div>' + @@ -254,6 +256,8 @@ var baguetteBox = function(selector, userOptions) { figcaption.innerHTML = imageCaption; figure.appendChild(figcaption); } + if(options.async) + callback(); } function showNextImage() {
New option to preload images asynchronously
feimosi_baguetteBox.js
train
48b4cbad45f25589a1d5e9086a19119fd00cfad7
diff --git a/dvc/analytics.py b/dvc/analytics.py index <HASH>..<HASH> 100644 --- a/dvc/analytics.py +++ b/dvc/analytics.py @@ -18,18 +18,16 @@ from dvc.repo import Repo from dvc.scm import SCM from dvc.utils import env2bool, is_binary, makedirs + logger = logging.getLogger(__name__) -def collect_and_send_report(arguments=None, return_code=None): +def collect_and_send_report(args=None, return_code=None): """ Query the system to fill a report and send it on a detached process. - - A temporary file is used as a mean of communication between the - current and detached process. """ report = { - "cmd_class": arguments.func.__name__, + "cmd_class": args.func.__name__ if hasattr(args, "func") else None, "cmd_return_code": return_code, "dvc_version": __version__, "is_binary": is_binary(), @@ -38,6 +36,8 @@ def collect_and_send_report(arguments=None, return_code=None): "user_id": find_or_create_user_id(), } + # A temporary file is used as a mean of communication between the + # current and detached process. with tempfile.NamedTemporaryFile(delete=False, mode="w") as fobj: json.dump(report, fobj) daemon(["analytics", fobj.name])
:nail_care: change naming and docstring
iterative_dvc
train
88e183d87adfb2bfc36584a6dc2c5ce5187b6a50
diff --git a/lib/logtrail.js b/lib/logtrail.js index <HASH>..<HASH> 100644 --- a/lib/logtrail.js +++ b/lib/logtrail.js @@ -1,7 +1,3 @@ -/* - * - */ - var stack = require('callsite'), path = require('path'), util = require('util'); @@ -79,13 +75,13 @@ Logtrail.prototype.logger = function (loglevel, args) { if (trace.length > 0) { line += path.relative(this.config.basedir, trace[0].getFileName()) + ':' + trace[0].getLineNumber() + ' '; } - line += args.join(' '); + line += joinArgs(' ', args); break; case 'error': case 'fatal': stream = process.stderr; - line += ' ['+loglevel+'] ' + args.join(', ') + "\n"; + line += ' ['+loglevel+'] ' + joinArgs(', ', args) + "\n"; trace.forEach(function (t) { line += util.format(' \033[36m%s\033[0m in %s:%d\033[0m' , t.getFunctionName() || 'anonymous' @@ -99,4 +95,15 @@ Logtrail.prototype.logger = function (loglevel, args) { stream.write(line+"\n"); }; +function joinArgs(join, args) { + var str = ''; + args.forEach(function (arg) { + str += join + if (typeof arg == 'object' || typeof arg == 'function') str += JSON.stringify(arg) + else str += arg + }); + + return str +} + module.exports = Logtrail;
Logging objects no longer produces [Object object]
CastawayLabs_logtrail
train
577783d86361358932879e3a57cbf7a6a52595a0
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/B2buaHelperImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/B2buaHelperImpl.java index <HASH>..<HASH> 100644 --- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/B2buaHelperImpl.java +++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/B2buaHelperImpl.java @@ -935,13 +935,13 @@ public class B2buaHelperImpl implements MobicentsB2BUAHelper, Serializable { final MobicentsSipSession originalSession = origRequestImpl.getSipSession(); final MobicentsSipSession session = newSipServletRequest.getSipSession(); - - sessionMap.put(originalSession.getKey(), session.getKey()); - sessionMap.put(session.getKey(), originalSession.getKey()); - dumpLinkedSessions(); + // B2buaHelperTest.testLinkSipSessions101 assumes the sessions shouldn't be linked together +// sessionMap.put(originalSession.getKey(), session.getKey()); +// sessionMap.put(session.getKey(), originalSession.getKey()); +// dumpLinkedSessions(); - originalRequestMap.put(newSipServletRequest, origRequestImpl); - originalRequestMap.put(origRequestImpl, newSipServletRequest); +// originalRequestMap.put(newSipServletRequest, origRequestImpl); +// originalRequestMap.put(origRequestImpl, newSipServletRequest); session.setB2buaHelper(this); originalSession.setB2buaHelper(this); diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipFactoryImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipFactoryImpl.java index <HASH>..<HASH> 100644 --- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipFactoryImpl.java +++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/message/SipFactoryImpl.java @@ -410,25 +410,32 @@ public class SipFactoryImpl implements MobicentsSipFactory, Externalizable { if(JainSipUtils.CONTACT_HEADER_METHODS.contains(newRequest.getMethod())) { String fromName = null; String displayName = origRequest.getFrom().getDisplayName(); - if(origRequest.getAddressHeader(ContactHeader.NAME).getURI() instanceof SipURI) { + if(origRequest != null && origRequest.getAddressHeader(ContactHeader.NAME) != null && + origRequest.getAddressHeader(ContactHeader.NAME).getURI() instanceof SipURI) { fromName = ((SipURI)origRequest.getFrom().getURI()).getUser(); } // Create the contact name address. ContactHeader contactHeader = null; // if a sip load balancer is present in front of the server, the contact header is the one from the sip lb // so that the subsequent requests can be failed over - if(useLoadBalancer) { - javax.sip.address.SipURI sipURI = addressFactory.createSipURI(fromName, loadBalancerToUse.getAddress().getHostAddress()); - sipURI.setHost(loadBalancerToUse.getAddress().getHostAddress()); - sipURI.setPort(loadBalancerToUse.getSipPort()); - sipURI.setTransportParam(JainSipUtils.findTransport(newRequest)); - javax.sip.address.Address contactAddress = addressFactory.createAddress(sipURI); - if(displayName != null && displayName.length() > 0) { - contactAddress.setDisplayName(displayName); + if(fromName != null) { + if(useLoadBalancer) { + javax.sip.address.SipURI sipURI = addressFactory.createSipURI(fromName, loadBalancerToUse.getAddress().getHostAddress()); + sipURI.setHost(loadBalancerToUse.getAddress().getHostAddress()); + sipURI.setPort(loadBalancerToUse.getSipPort()); + sipURI.setTransportParam(JainSipUtils.findTransport(newRequest)); + javax.sip.address.Address contactAddress = addressFactory.createAddress(sipURI); + if(displayName != null && displayName.length() > 0) { + contactAddress.setDisplayName(displayName); + } + contactHeader = headerFactory.createContactHeader(contactAddress); + } else { + contactHeader = JainSipUtils.createContactHeader(getSipNetworkInterfaceManager(), newRequest, displayName, fromName, null); } - contactHeader = headerFactory.createContactHeader(contactAddress); } else { - contactHeader = JainSipUtils.createContactHeader(getSipNetworkInterfaceManager(), newRequest, displayName, fromName, null); + if(logger.isDebugEnabled()) { + logger.debug("Unable to create Contact Header. It will be added later on send."); + } } if(contactHeader != null) {
Closes Issue #<I> Fix TCK test (cherry picked from commit <I>dbff<I>d<I>c3a4f6a<I>ddd7a3d6adbbd<I>) Conflicts: build/jsr<I>-tck/tck/conf/default.properties
RestComm_sip-servlets
train
b1a62cb7aafc85d14b72476a1dc8bc993e12a501
diff --git a/lib/fsExt.js b/lib/fsExt.js index <HASH>..<HASH> 100755 --- a/lib/fsExt.js +++ b/lib/fsExt.js @@ -24,6 +24,7 @@ module.exports = { rmdirRecursive: rmdirRecursive, requireAsync: requireAsync, requireSync: requireSync, + requireResetCache: requireResetCache, checkExistsName: checkExistsName, writeFile: writeFile, readFile: readFile, @@ -165,6 +166,14 @@ function unwatchAll(){ var _modules = {}; /** + * resets cached file content + * @param {String} filePath path + */ +function requireResetCache(filePath) { + delete _modules[filePath]; +} + +/** * async alternative to nodejs require, if opts.watch===true resolve module cache on file change * @param {String} filePath path * @param {Object} opts @@ -349,7 +358,10 @@ function writeFile(filePath, data, callback, count){ // callback(err) writeFile(filePath, data, callback, count + 1); }, 500); } - else callback(); + else { + delete _modules[filePath]; // delete internal cache if watched and cached + callback(); + } }); } diff --git a/package.json b/package.json index <HASH>..<HASH> 100755 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "nodee-utils", "preferGlobal": false, - "version": "1.2.1", + "version": "1.2.2", "author": "NODEE - Matus Szabo <matus@nodee.io>", "description": "set of useful helpers", "main": "./index.js", @@ -18,7 +18,7 @@ "shortid": "~2.2.2", "superagent": "5.0.2", "superagent-retry": "~0.6.0", - "jwt-simple": "0.5.1" + "jwt-simple": "0.5.6" }, "analyze": false, "devDependencies": {}, diff --git a/test/template.js b/test/template.js index <HASH>..<HASH> 100755 --- a/test/template.js +++ b/test/template.js @@ -148,7 +148,7 @@ it("model property throw error if not defined, and not only variable expression" assert.throws(function(){ var templateStr = "<hello>@undefinedVariable s @(definedParent.undefinedChild.undefinedChild - 1)</hello>"; var result = template.render(templateStr, { definedParent:'asdasd' }); - },'Cannot read property \'undefinedChild\' of undefined'); + }, new TypeError('Cannot read property \'undefinedChild\' of undefined')); }); it("define and use function", function () { @@ -161,7 +161,7 @@ it("compile throws error when trying to get global vars inside template", functi assert.throws(function(){ var templateStr = "<hello>@setTimeout(function(){ console.warn('setTimeout from inside template'); })</hello>"; var result = template.render(templateStr, { definedParent:'asdasd' }); - },'setTimeout is not a function'); + }, new TypeError('setTimeout is not a function')); }); it("html comments", function () {
fixed: tests in node > <I>
nodee-apps_utils
train
6ad276be4e4047f39200067ca6ad56cdcbf45d9e
diff --git a/executable.js b/executable.js index <HASH>..<HASH> 100644 --- a/executable.js +++ b/executable.js @@ -3,7 +3,7 @@ module.exports = function (process, stat) { if (stat.uid == process.getuid() && stat.mode & 010) return true if (process.getgroups && process.getgroups().some(function (gid) { return gid == stat.gid - }) && stat.mode & 100) return true - if (process.getgid() == stat.gid && stat.mode & 100) return true + }) && stat.mode & 0100) return true + if (process.getgid() == stat.gid && stat.mode & 0100) return true return false } diff --git a/t/proof/executable.t.js b/t/proof/executable.t.js index <HASH>..<HASH> 100644 --- a/t/proof/executable.t.js +++ b/t/proof/executable.t.js @@ -16,8 +16,8 @@ require('../..')(5, function (assert) { assert(executable(null, { mode: 001 }), 'other execute') assert(executable(process, { mode: 010, uid: 700 }), 'uid execute') - assert(executable(process, { mode: 100, gid: 33 }), 'groups execute') - assert(executable(process, { mode: 100, gid: 10 }), 'gid execute') + assert(executable(process, { mode: 0100, gid: 33 }), 'groups execute') + assert(executable(process, { mode: 0100, gid: 10 }), 'gid execute') assert(!executable(process, { mode: 002, gid: 19 }), 'cannot execute') // LESSON:
Corrected a number so all modes are octals.
bigeasy_proof
train
4519ca62be680deba7b1b3a8c569c89177abcd4d
diff --git a/lib/sandbox.js b/lib/sandbox.js index <HASH>..<HASH> 100644 --- a/lib/sandbox.js +++ b/lib/sandbox.js @@ -39,6 +39,6 @@ exports.navigator = { } exports.console = console - exports.process = process +process.console = console diff --git a/lib/sea.js b/lib/sea.js index <HASH>..<HASH> 100644 --- a/lib/sea.js +++ b/lib/sea.js @@ -26,6 +26,7 @@ function runSeaJS(filepath) { global.define = process.define delete process.seajs delete process.define + delete process.console } function request(data) {
Expose console to sandbox
seajs_seajs
train
1432d77963ee82ea018bde1d0b4f7ec4a5c5595b
diff --git a/internal/service/ec2/instance_test.go b/internal/service/ec2/instance_test.go index <HASH>..<HASH> 100644 --- a/internal/service/ec2/instance_test.go +++ b/internal/service/ec2/instance_test.go @@ -306,6 +306,33 @@ func TestAccEC2Instance_EBSBlockDevice_invalidThroughputForVolumeType(t *testing }) } +// TestAccEC2Instance_EBSBlockDevice_RootBlockDevice_removed verifies block device mappings +// removed outside terraform no longer result in a panic. +// Reference: https://github.com/hashicorp/terraform-provider-aws/issues/20821 +func TestAccEC2Instance_EBSBlockDevice_RootBlockDevice_removed(t *testing.T) { + var instance ec2.Instance + resourceName := "aws_instance.test" + + resource.ParallelTest(t, resource.TestCase{ + PreCheck: func() { acctest.PreCheck(t) }, + ErrorCheck: acctest.ErrorCheck(t, ec2.EndpointsID), + Providers: acctest.Providers, + CheckDestroy: testAccCheckInstanceDestroy, + Steps: []resource.TestStep{ + { + Config: testAccInstanceConfigEBSAndRootBlockDevice, + Check: resource.ComposeTestCheckFunc( + testAccCheckInstanceExists(resourceName, &instance), + // Instance must be stopped before detaching a root block device + testAccCheckStopInstance(&instance), + testAccCheckDetachVolumes(&instance), + ), + ExpectNonEmptyPlan: true, + }, + }, + }) +} + func TestAccEC2Instance_RootBlockDevice_kmsKeyARN(t *testing.T) { var instance ec2.Instance kmsKeyResourceName := "aws_kms_key.test" @@ -3854,6 +3881,37 @@ func testAccCheckStopInstance(instance *ec2.Instance) resource.TestCheckFunc { } } +func testAccCheckDetachVolumes(instance *ec2.Instance) resource.TestCheckFunc { + return func(s *terraform.State) error { + client := acctest.Provider.Meta().(*conns.AWSClient) + conn := client.EC2Conn + + for _, bd := range instance.BlockDeviceMappings { + if bd.Ebs != nil && bd.Ebs.VolumeId != nil { + name := aws.StringValue(bd.DeviceName) + volID := aws.StringValue(bd.Ebs.VolumeId) + instanceID := aws.StringValue(instance.InstanceId) + + // Make sure in correct state before detaching + if err := tfec2.WaitVolumeAttachmentAttached(conn, name, volID, instanceID); err != nil { + return err + } + + r := tfec2.ResourceVolumeAttachment() + d := r.Data(nil) + d.Set("device_name", name) + d.Set("volume_id", volID) + d.Set("instance_id", instanceID) + + if err := r.Delete(d, client); err != nil { + return err + } + } + } + return nil + } +} + func TestInstanceHostIDSchema(t *testing.T) { actualSchema := tfec2.ResourceInstance().Schema["host_id"] expectedSchema := &schema.Schema{ @@ -5045,6 +5103,27 @@ resource "aws_instance" "test" { } `) +var testAccInstanceConfigEBSAndRootBlockDevice = acctest.ConfigCompose( + acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), + fmt.Sprintf(` +resource "aws_instance" "test" { + ami = data.aws_ami.amzn-ami-minimal-hvm-ebs.id + + instance_type = "t2.medium" + + root_block_device { + volume_type = "gp2" + volume_size = 9 + delete_on_termination = true + } + + ebs_block_device { + device_name = "/dev/sdb" + volume_size = 9 + } +} +`)) + func testAccInstanceConfigBlockDeviceTagsVolumeTags() string { return acctest.ConfigCompose(acctest.ConfigLatestAmazonLinuxHvmEbsAmi(), ` resource "aws_instance" "test" { diff --git a/internal/service/ec2/wait.go b/internal/service/ec2/wait.go index <HASH>..<HASH> 100644 --- a/internal/service/ec2/wait.go +++ b/internal/service/ec2/wait.go @@ -1521,3 +1521,19 @@ func WaitEBSSnapshotTierArchive(conn *ec2.EC2, id string) (*ec2.SnapshotTierStat return detail.(*ec2.SnapshotTierStatus), nil } } + +// WaitVolumeAttachmentAttached waits for a VolumeAttachment to return Attached +func WaitVolumeAttachmentAttached(conn *ec2.EC2, name, volumeID, instanceID string) error { + stateConf := &resource.StateChangeConf{ + Pending: []string{ec2.VolumeAttachmentStateAttaching}, + Target: []string{ec2.VolumeAttachmentStateAttached}, + Refresh: volumeAttachmentStateRefreshFunc(conn, name, volumeID, instanceID), + Timeout: 5 * time.Minute, + Delay: 10 * time.Second, + MinTimeout: 3 * time.Second, + } + + _, err := stateConf.WaitForState() + + return err +}
tests/instance: add test to verify code change
terraform-providers_terraform-provider-aws
train
c0df83938f32b32b963faec6c90952202ff344c2
diff --git a/lib/mongo/collection.rb b/lib/mongo/collection.rb index <HASH>..<HASH> 100644 --- a/lib/mongo/collection.rb +++ b/lib/mongo/collection.rb @@ -341,6 +341,7 @@ module Mongo :coll_name => name, :write_concern => write_concern, :bypass_document_validation => !!options[:bypass_document_validation], + :options => options, :id_generator => client.options[:id_generator] ).execute(next_primary.context) end
RUBY-<I>: Pass the options to insert operation
mongodb_mongo-ruby-driver
train
c185b990dc2d192ab733178ac8b7625bf3d47dd1
diff --git a/lhc/parallel/cpu/distribute.py b/lhc/parallel/cpu/distribute.py index <HASH>..<HASH> 100755 --- a/lhc/parallel/cpu/distribute.py +++ b/lhc/parallel/cpu/distribute.py @@ -69,7 +69,7 @@ class Distributor: self.__sleep = sleep infile = open('/proc/cpuinfo') - self.__mx_cpus = len([line for line in infile if line.startswith('processor')]) + self.__max_cpus = len([line for line in infile if line.startswith('processor')]) infile.close() def distribute(self, n_jobs, indir, args):
Minor changes when looking for maximum CPUs
childsish_sofia
train
40599b93d1b2a9165d5418eef510b0d202c690dd
diff --git a/src/main/java/com/feedzai/commons/sql/abstraction/engine/DatabaseEngine.java b/src/main/java/com/feedzai/commons/sql/abstraction/engine/DatabaseEngine.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/feedzai/commons/sql/abstraction/engine/DatabaseEngine.java +++ b/src/main/java/com/feedzai/commons/sql/abstraction/engine/DatabaseEngine.java @@ -137,12 +137,10 @@ public interface DatabaseEngine extends AutoCloseable { * * @param view The view name. * @throws DatabaseEngineException If something goes wrong while dropping the view. - * @implNote This method has a default to not create a breaking change. - * @since 2.5.3 + * + * @since 2.6.0 */ - default void dropView(final String view) throws DatabaseEngineException { - // NoOp - } + void dropView(final String view) throws DatabaseEngineException; /** * Persists a given entry. Persisting a query implies executing the statement.
Remove default implementation of dropView method since next release will be a minor
feedzai_pdb
train
a2bb75569ab1c88d3c6babca0041f2ea548afac2
diff --git a/lib/svtplay_dl/service/viaplay.py b/lib/svtplay_dl/service/viaplay.py index <HASH>..<HASH> 100644 --- a/lib/svtplay_dl/service/viaplay.py +++ b/lib/svtplay_dl/service/viaplay.py @@ -135,6 +135,7 @@ class Viaplay(Service, OpenGraphThumbMixin): if self.options.output_auto: directory = os.path.dirname(self.options.output) self.options.service = "tv3play" + self.options.service = "viafree" basename = self._autoname(dataj) title = "%s-%s-%s" % (basename, vid, self.options.service) if len(directory):
viafree: Change autonaming from tv3play to viafree Change part autogenerated file names from tv3play to viafree
spaam_svtplay-dl
train
df2b86300d733b3fc9f61ad31322641986c514bb
diff --git a/nomad/structs/funcs.go b/nomad/structs/funcs.go index <HASH>..<HASH> 100644 --- a/nomad/structs/funcs.go +++ b/nomad/structs/funcs.go @@ -24,6 +24,19 @@ func RemoveAllocs(alloc []*Allocation, remove []string) []*Allocation { return alloc } +// FilterTerminalAllocs filters out all allocations in a terminal state +func FilterTerminalAllocs(allocs []*Allocation) []*Allocation { + n := len(allocs) + for i := 0; i < n; i++ { + if allocs[i].TerminalStatus() { + allocs[i], allocs[n-1] = allocs[n-1], nil + i-- + n-- + } + } + return allocs[:n] +} + // PortsOvercommited checks if any ports are over-committed. // This does not handle CIDR subsets, and computes for the entire // CIDR block currently. diff --git a/nomad/structs/funcs_test.go b/nomad/structs/funcs_test.go index <HASH>..<HASH> 100644 --- a/nomad/structs/funcs_test.go +++ b/nomad/structs/funcs_test.go @@ -19,6 +19,23 @@ func TestRemoveAllocs(t *testing.T) { } } +func TestFilterTerminalALlocs(t *testing.T) { + l := []*Allocation{ + &Allocation{ID: "foo", Status: AllocStatusPending}, + &Allocation{ID: "bar", Status: AllocStatusEvict}, + &Allocation{ID: "baz", Status: AllocStatusComplete}, + &Allocation{ID: "zip", Status: AllocStatusPending}, + } + + out := FilterTerminalAllocs(l) + if len(out) != 2 { + t.Fatalf("bad: %#v", out) + } + if out[0].ID != "foo" && out[1].ID != "zip" { + t.Fatalf("bad: %#v", out) + } +} + func TestPortsOvercommitted(t *testing.T) { r := &Resources{ Networks: []*NetworkResource{ diff --git a/nomad/structs/structs.go b/nomad/structs/structs.go index <HASH>..<HASH> 100644 --- a/nomad/structs/structs.go +++ b/nomad/structs/structs.go @@ -651,6 +651,7 @@ const ( AllocStatusComplete = "complete" AllocStatusDead = "dead" AllocStatusFailed = "failed" + AllocStatusEvict = "evict" ) // Allocation is used to allocate the placement of a task group to a node. @@ -695,7 +696,7 @@ type Allocation struct { // will no longer transition. func (a *Allocation) TerminalStatus() bool { switch a.Status { - case AllocStatusComplete, AllocStatusDead, AllocStatusFailed: + case AllocStatusComplete, AllocStatusDead, AllocStatusFailed, AllocStatusEvict: return true default: return false
nomad: adding evict state for allocs
hashicorp_nomad
train
fc2c3dfe1ca202f9f8d7a3ea3d4391c7cb0c3924
diff --git a/tests/test_connector.py b/tests/test_connector.py index <HASH>..<HASH> 100644 --- a/tests/test_connector.py +++ b/tests/test_connector.py @@ -28,13 +28,19 @@ class HttpConnectionTests(unittest.TestCase): self.request = mock.Mock() self.transport = mock.Mock() self.protocol = mock.Mock() - self.loop = mock.Mock() + self.loop = asyncio.new_event_loop() + asyncio.set_event_loop(None) + + def tearDown(self): + self.loop.close() @unittest.skipUnless(PY_34, "Requires Python 3.4+") def test_del(self): conn = Connection( self.connector, self.key, self.request, self.transport, self.protocol, self.loop) + exc_handler = unittest.mock.Mock() + self.loop.set_exception_handler(exc_handler) with self.assertWarns(ResourceWarning): del conn @@ -43,6 +49,11 @@ class HttpConnectionTests(unittest.TestCase): self.transport, self.protocol, should_close=True) + msg = {'client_connection': unittest.mock.ANY, # conn was deleted + 'message': 'Unclosed connection'} + if self.loop.get_debug(): + msg['source_traceback'] = unittest.mock.ANY + exc_handler.assert_called_with(self.loop, msg) def test_close(self): conn = Connection(
Improve test for Connection.__del__
aio-libs_aiohttp
train
bb7cf6c3d09c9b69c9a385094c0fbf50c1982ade
diff --git a/blueocean-plugin/src/test/java/io/jenkins/blueocean/service/embedded/PipelineApiTest.java b/blueocean-plugin/src/test/java/io/jenkins/blueocean/service/embedded/PipelineApiTest.java index <HASH>..<HASH> 100644 --- a/blueocean-plugin/src/test/java/io/jenkins/blueocean/service/embedded/PipelineApiTest.java +++ b/blueocean-plugin/src/test/java/io/jenkins/blueocean/service/embedded/PipelineApiTest.java @@ -449,6 +449,41 @@ public class PipelineApiTest { } @Test + public void getPipelineJobAbortTest() throws Exception { + WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1"); + + job1.setDefinition(new CpsFlowDefinition("" + + "node {" + + " stage ('Build1'); " + + " sh('sleep 60') " + + " stage ('Test1'); " + + " echo ('Testing'); " + + "}")); + + WorkflowRun b1 = job1.scheduleBuild2(0).waitForStart(); + for (int i = 0; i < 10; i++) { + b1.doStop(); + if (b1.getResult() != null) { + break; + } + Thread.sleep(1000); + } + j.assertBuildStatus(Result.ABORTED, b1); + + RestAssured.given().log().all().get("/organizations/jenkins/pipelines/pipeline1/runs/1") + .then().log().all() + .statusCode(200) + .body("id", Matchers.equalTo(b1.getId())) + .body("pipeline", Matchers.equalTo(b1.getParent().getName())) + .body("organization", Matchers.equalTo("jenkins")) + .body("state", Matchers.equalTo("FINISHED")) + .body("result", Matchers.equalTo("ABORTED")) + .body("startTime", Matchers.equalTo( + new SimpleDateFormat(JsonConverter.DATE_FORMAT_STRING).format(new Date(b1.getStartTimeInMillis())))); + } + + + @Test public void getPipelineJobRunNodeLogTest() throws Exception { WorkflowJob job1 = j.jenkins.createProject(WorkflowJob.class, "pipeline1");
UX-<I># Added test for ABORTED status check
jenkinsci_blueocean-plugin
train
29e11727f79929e65292d139e0e9b40188a4dfa7
diff --git a/lib/elasticsearch/drain/autoscaling.rb b/lib/elasticsearch/drain/autoscaling.rb index <HASH>..<HASH> 100644 --- a/lib/elasticsearch/drain/autoscaling.rb +++ b/lib/elasticsearch/drain/autoscaling.rb @@ -41,6 +41,17 @@ module Elasticsearch find_instances_in_asg find_private_ips end + + # Sets the MinSize of an AutoScalingGroup + # + # @option [FixNum] count (0) The new MinSize of the AutoScalingGroup + # @return [Struct] Empty response from the sdk + def min_count(count = 0) + @asg_client.update_auto_scaling_group( + auto_scaling_group_name: asg, + min_size: count + ) + end end end end
CORE-<I> Add method to set the min count of an asg
rapid7_elasticsearch-drain
train
ccaa67edfc5edd1b3b04bbbfbd4be0d51575ae9c
diff --git a/plugins/UserCountry/templates/admin.js b/plugins/UserCountry/templates/admin.js index <HASH>..<HASH> 100755 --- a/plugins/UserCountry/templates/admin.js +++ b/plugins/UserCountry/templates/admin.js @@ -116,7 +116,7 @@ $(document).ready(function () { function (response) { if (response.error) { // on error, show error & stop downloading - $('#' + thisId).fadeOut(1000, function () { + $('#geoipdb-screen2-download').fadeOut(1000, function () { $('#manage-geoip-dbs').html(response.error); }); }
fixed small js error occuring if geoip download failed
matomo-org_matomo
train
27750f088fda6b1e9b3d514c273dbc493e8ae5d1
diff --git a/gemini.py b/gemini.py index <HASH>..<HASH> 100644 --- a/gemini.py +++ b/gemini.py @@ -209,13 +209,15 @@ def create_trial(res_one, res_other, file_one, file_other, "url": res_one.url, "status_code": res_one.status_code, "byte": len(res_one.content), - "response_sec": to_sec(res_one.elapsed) + "response_sec": to_sec(res_one.elapsed), + "content_type": res_one.headers.get("content-type") }, "other": { "url": res_other.url, "status_code": res_other.status_code, "byte": len(res_other.content), - "response_sec": to_sec(res_other.elapsed) + "response_sec": to_sec(res_other.elapsed), + "content_type": res_other.headers.get("content-type") } } if file_one is not None: diff --git a/modules/models.py b/modules/models.py index <HASH>..<HASH> 100644 --- a/modules/models.py +++ b/modules/models.py @@ -141,11 +141,12 @@ class Trial(OwlMixin): class ResponseSummary(OwlMixin): def __init__(self, url: str, status_code: int = None, byte: int = None, response_sec: int = None, - file: Optional[str] = None): + content_type: str = None, file: Optional[str] = None): self.url: str = url self.status_code: Optional[int] = status_code self.byte: Optional[int] = byte self.response_sec: Optional[int] = response_sec + self.content_type: Optional[str] = content_type self.file: Optional[str] = file
:new: Add content type to report
tadashi-aikawa_jumeaux
train
4d2f4ad06719341faa0bc2df5568c6354d66fc3c
diff --git a/tests/test_current_charts.py b/tests/test_current_charts.py index <HASH>..<HASH> 100644 --- a/tests/test_current_charts.py +++ b/tests/test_current_charts.py @@ -14,7 +14,6 @@ class Base: def testDate(self): self.assertIsNotNone(self.chart.date) - self.assertEqual(self.chart.nextDate, "") def testTitle(self): self.assertEqual(self.chart.title, self.expectedTitle) diff --git a/tests/test_dates.py b/tests/test_dates.py index <HASH>..<HASH> 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -15,29 +15,6 @@ class DateTest(unittest.TestCase): chart = billboard.ChartData("hot-100", date="2019-12-31") self.assertEqual(chart.date, "2020-01-04") - def testPreviousNext(self): - """Checks that the date, previousDate, and nextDate attributes are parsed - from the HTML, not computed. Specifically, we shouldn't assume charts are - always published seven days apart, since (as this example demonstrates) - this is not true. - """ - chart = billboard.ChartData("hot-100", date="1962-01-06") - self.assertEqual(chart.date, "1962-01-06") - self.assertEqual(chart.nextDate, "1962-01-13") - self.assertEqual(chart.previousDate, "1961-12-25") - - chart = billboard.ChartData("hot-100", date="1961-12-25") - self.assertEqual(chart.date, "1961-12-25") - self.assertEqual(chart.nextDate, "1962-01-06") - self.assertEqual(chart.previousDate, "1961-12-18") - - def testNoPrevious(self): - """Checks that previousDate is empty when there is no previous chart.""" - chart = billboard.ChartData("country-songs", date="1958-10-20") - self.assertEqual(chart.date, "1958-10-20") - self.assertEqual(chart.nextDate, "1958-10-27") - self.assertEqual(chart.previousDate, "") - def testDatetimeDate(self): """Checks that ChartData correctly handles datetime objects as the date parameter. diff --git a/tests/test_historical_charts.py b/tests/test_historical_charts.py index <HASH>..<HASH> 100644 --- a/tests/test_historical_charts.py +++ b/tests/test_historical_charts.py @@ -22,8 +22,6 @@ class Base: self.assertEqual(self.chart.name, reference["name"]) self.assertEqual(self.chart.title, reference["title"]) self.assertEqual(self.chart.date, reference["date"]) - self.assertEqual(self.chart.previousDate, reference["previousDate"]) - self.assertEqual(self.chart.nextDate, reference["nextDate"]) self.assertEqual(len(self.chart.entries), len(reference["entries"])) for chartEntry, referenceEntry in zip(self.chart.entries, reference["entries"]):
Remove tests dealing with previousDate and nextDate, since they are broken (and hard to fix)
guoguo12_billboard-charts
train
6cabcd66de4f0d6d8ca71dc16bb444af7a4b6abd
diff --git a/app/assets/javascripts/social_networking/controllers/profile-controller.js b/app/assets/javascripts/social_networking/controllers/profile-controller.js index <HASH>..<HASH> 100644 --- a/app/assets/javascripts/social_networking/controllers/profile-controller.js +++ b/app/assets/javascripts/social_networking/controllers/profile-controller.js @@ -25,7 +25,7 @@ ProfileCtrl.prototype.update_profile_icon = function(icon_name, controller) { controller.iconSrc = icon_name; controller._profiles.update(controller).then(function(profile) { - controller.profile = profile; + controller.profile.iconSrc = profile.iconSrc; }); $('#icon-selection-button').click(); };
Fixed an issue that caused the profile name to disappear upon icon update.
NU-CBITS_social_networking
train
265135c46502e1d7d2f3f5c6db15dac0e8fc5000
diff --git a/test/has_scope_test.rb b/test/has_scope_test.rb index <HASH>..<HASH> 100644 --- a/test/has_scope_test.rb +++ b/test/has_scope_test.rb @@ -16,8 +16,8 @@ class TreesController < ApplicationController has_scope :paginate_blank, type: :hash, allow_blank: true has_scope :paginate_default, type: :hash, default: { page: 1, per_page: 10 }, only: :edit has_scope :args_paginate, type: :hash, using: [:page, :per_page] - has_scope :args_paginate_blank, type: :hash, using: [:page, :per_page], allow_blank: true - has_scope :args_paginate_default, type: :hash, using: [:page, :per_page], default: { page: 1, per_page: 10 }, only: :edit + has_scope :args_paginate_blank, using: [:page, :per_page], allow_blank: true + has_scope :args_paginate_default, using: [:page, :per_page], default: { page: 1, per_page: 10 }, only: :edit has_scope :categories, type: :array has_scope :title, in: :q has_scope :content, in: :q
Remove extraneous type, help verify `hash` is not necessary for `using`
plataformatec_has_scope
train
d9042e78013f3377580966bf5a3092ccfa7848c0
diff --git a/lib/codemirror.js b/lib/codemirror.js index <HASH>..<HASH> 100644 --- a/lib/codemirror.js +++ b/lib/codemirror.js @@ -7454,7 +7454,7 @@ extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); }), extendSelections: docMethodOp(function(heads, options) { - extendSelections(this, clipPosArray(this, heads, options)); + extendSelections(this, clipPosArray(this, heads), options); }), extendSelectionsBy: docMethodOp(function(f, options) { extendSelections(this, map(this.sel.ranges, f), options);
Fix options of extendSelections.
codemirror_CodeMirror
train
5df6a8d7a1b8e5a31c9d067376f94699d81811a5
diff --git a/unit_object.py b/unit_object.py index <HASH>..<HASH> 100644 --- a/unit_object.py +++ b/unit_object.py @@ -698,7 +698,9 @@ def _get_system_unit_string(dimensions, base_units): def _define_unit(registry, symbol, value, tex_repr=None, offset=None): from yt.units.yt_array import YTQuantity if not isinstance(value, YTQuantity): - raise RuntimeError("\"value\" must be a YTQuantity!") + raise RuntimeError("The \"value\" argument must be a YTQuantity!") + if symbol in registry: + raise RuntimeError("The symbol \"%s\" is already in the unit registry!" % symbol) base_value = float(value.in_base(unit_system='cgs-ampere')) registry.add(symbol, base_value, value.units.dimensions, tex_repr=tex_repr, offset=offset)
Don’t overwrite units we already have --HG-- branch : yt
yt-project_unyt
train
2c1833bdb4606629eaac2c5b01d9921ef0b506f6
diff --git a/course/report/log/lib.php b/course/report/log/lib.php index <HASH>..<HASH> 100644 --- a/course/report/log/lib.php +++ b/course/report/log/lib.php @@ -73,22 +73,17 @@ function print_mnet_log_selector_form($hostid, $course, $selecteduser=0, $select } } - // Get all the hosts that we SSO with - $sql = "SELECT DISTINCT - h.id, - h.name, - s.name as servicename - FROM - {$CFG->prefix}mnet_host h - LEFT OUTER JOIN - {$CFG->prefix}mnet_host2service hs ON - (h.id=hs.hostid AND hs.subscribe!=0) - LEFT OUTER JOIN - {$CFG->prefix}mnet_service2rpc sr ON - sr.serviceid=hs.serviceid - LEFT OUTER JOIN - {$CFG->prefix}mnet_service s ON - (sr.serviceid=s.id AND s.name='sso')"; + // Get all the hosts that have log records + $sql = "select distinct + h.id, + h.name + from + {$CFG->prefix}mnet_host h, + {$CFG->prefix}mnet_log l + where + h.id = l.hostid + order by + h.name"; $hosts = get_records_sql($sql); foreach($hosts as $host) {
Mnet: Bugfix: Revised query to find hosts we SSO with: MDL-<I>
moodle_moodle
train
86d7213139c1f80a50ca1f920d4332ab3b2398eb
diff --git a/tg_react/__init__.py b/tg_react/__init__.py index <HASH>..<HASH> 100644 --- a/tg_react/__init__.py +++ b/tg_react/__init__.py @@ -1,2 +1,2 @@ from .settings import * -__version__ = '0.4.1' +__version__ = '0.4.2' diff --git a/tg_react/management/commands/makemessages.py b/tg_react/management/commands/makemessages.py index <HASH>..<HASH> 100644 --- a/tg_react/management/commands/makemessages.py +++ b/tg_react/management/commands/makemessages.py @@ -118,7 +118,7 @@ class ParseJsTranslations(object): in_quotes = not in_quotes elif c == ',': if not in_quotes: - args.append(out[-1]) + args.append(out[:-1]) out = '' if out:
Fix issue with multiarg gettext calls
thorgate_tg-react
train
f1a5b8ced99d450883c92d5645a83aa7a2bcdbd6
diff --git a/tests/test_check_function.py b/tests/test_check_function.py index <HASH>..<HASH> 100644 --- a/tests/test_check_function.py +++ b/tests/test_check_function.py @@ -500,3 +500,10 @@ def test_test_function_v2_no_sig(): s.check_function("numpy.arange", signature=False) with pytest.raises(InstructorError): s.check_function("numpy.arange") + + +def test_function_call_in_return(): + code = "def my_func(a): return my_func_in_return(b)" + sct = "Ex().check_function_def('my_func').check_body().check_function('my_func_in_return', signature=False)" + res = helper.run({"DC_CODE": code, "DC_SOLUTION": code, "DC_SCT": sct}) + assert res["correct"]
Add test for function calls in return statements
datacamp_pythonwhat
train
9d00ba5b961903e1ecde863fe8752799205e67e4
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,28 @@ builder.config({ }); ``` +### Overriding Fetch + +The framework fetch function can be overridden in order to provide the source for a file manually. This is useful if you want to pre-process the source of a file before using the builder. + +```javascript +var mySource = 'import * from foo; var foo = "bar";'; // get source as a string +builder.bundle('foo.js', { + fetch: function (load, fetch) { + if (load.name.indexOf('foo.js') !== -1) { + return mySource; + } else { + // fall back to the normal fetch method + return fetch(load); + } + } +}); +``` + +The `load` variable describes the file that is trying to be loaded. This is called once for every file that is trying to be fetched, including dependencies. + +The `fetch` function should return a string. + ### Bundle Arithmetic Both `builder.build` and `builder.buildStatic` support bundle arithmetic expressions. This allows for the easy construction of custom bundles. diff --git a/lib/builder.js b/lib/builder.js index <HASH>..<HASH> 100644 --- a/lib/builder.js +++ b/lib/builder.js @@ -415,9 +415,7 @@ Builder.prototype.bundle = function(expressionOrTree, outFile, opts) { self.fetch = opts.fetch; self.loader.fetch = function (load) { var args = Array.prototype.slice.call(arguments, 0); - args.push(function () { - return loaderFetch.apply(self.loader, args); - }); + args.push(loaderFetch.bind(self.loader)); var source = (self.fetch || loaderFetch).apply(self.loader, args); diff --git a/test/test-build.js b/test/test-build.js index <HASH>..<HASH> 100644 --- a/test/test-build.js +++ b/test/test-build.js @@ -43,11 +43,11 @@ function doTests(transpiler) { builder.reset(); builder.config({ transpiler: transpiler }); return builder.bundle('foo.js', { - fetch: function (load, pass) { + fetch: function (load, fetch) { if (load.name.indexOf('foo.js') !== -1) { return fs.readFileSync('test/fixtures/test-tree/amd-1.js', 'utf8'); } else { - return pass(); + return fetch(load); } } });
Update the fetch pass in function. Update readme.
systemjs_builder
train
b275bc223617aaeb7e9ec7d3f68fa47f887e904b
diff --git a/barge-rpc-proto/src/test/java/org/robotninjas/barge/GroupOfCounters.java b/barge-rpc-proto/src/test/java/org/robotninjas/barge/GroupOfCounters.java index <HASH>..<HASH> 100644 --- a/barge-rpc-proto/src/test/java/org/robotninjas/barge/GroupOfCounters.java +++ b/barge-rpc-proto/src/test/java/org/robotninjas/barge/GroupOfCounters.java @@ -66,7 +66,18 @@ public class GroupOfCounters extends ExternalResource implements StateTransition } public void commitToLeader(byte[] bytes) throws RaftException, InterruptedException { - counters.get(0).commit(bytes); + int leader = getLeader(); + counters.get(leader).commit(bytes); + } + + private int getLeader() { + for (int i = 0; i < counters.size(); i++) { + SimpleCounterMachine counter = counters.get(i); + if (counter.isLeader()) { + return i; + } + } + throw new IllegalStateException("Unable to find leader"); } /** diff --git a/barge-rpc-proto/src/test/java/org/robotninjas/barge/SimpleCounterMachine.java b/barge-rpc-proto/src/test/java/org/robotninjas/barge/SimpleCounterMachine.java index <HASH>..<HASH> 100644 --- a/barge-rpc-proto/src/test/java/org/robotninjas/barge/SimpleCounterMachine.java +++ b/barge-rpc-proto/src/test/java/org/robotninjas/barge/SimpleCounterMachine.java @@ -106,4 +106,8 @@ public class SimpleCounterMachine implements StateMachine { }).probe(timeout); } + public boolean isLeader() { + return service.isLeader(); + } + }
Don't assume leader is #0 in integration tests
mgodave_barge
train
b21bf6169880c0e50778ba1a8076e179610b6fec
diff --git a/hcl/hclsyntax/expression.go b/hcl/hclsyntax/expression.go index <HASH>..<HASH> 100644 --- a/hcl/hclsyntax/expression.go +++ b/hcl/hclsyntax/expression.go @@ -604,7 +604,9 @@ func (e *IndexExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { diags = append(diags, collDiags...) diags = append(diags, keyDiags...) - return hcl.Index(coll, key, &e.SrcRange) + val, diags := hcl.Index(coll, key, &e.SrcRange) + setDiagEvalContext(diags, e, ctx) + return val, diags } func (e *IndexExpr) Range() hcl.Range {
hclsyntax: Annotate diags from IndexExpr with source expr information
hashicorp_hcl
train
483421dbbf0cbf98671ddf58f7043995facc7ef7
diff --git a/src/js/BottomNavigations/__tests__/BottomNavigation.js b/src/js/BottomNavigations/__tests__/BottomNavigation.js index <HASH>..<HASH> 100644 --- a/src/js/BottomNavigations/__tests__/BottomNavigation.js +++ b/src/js/BottomNavigations/__tests__/BottomNavigation.js @@ -14,7 +14,7 @@ import Dialog from '../../Dialogs/Dialog'; describe('BottomNavigation', () => { it('should inherit the dialog\'s renderNode context', () => { const links = [{ label: '' }, { label: '' }, { label: '' }]; - const dialog = renderIntoDocument(<Dialog><BottomNavigation links={links} /></Dialog>); + const dialog = renderIntoDocument(<Dialog id="test"><BottomNavigation links={links} /></Dialog>); const bottomNav = findRenderedComponentWithType(dialog, BottomNavigation); expect(bottomNav.context.renderNode).toBe(dialog.getChildContext().renderNode); }); diff --git a/src/js/Dialogs/__tests__/DialogContainer.js b/src/js/Dialogs/__tests__/DialogContainer.js index <HASH>..<HASH> 100644 --- a/src/js/Dialogs/__tests__/DialogContainer.js +++ b/src/js/Dialogs/__tests__/DialogContainer.js @@ -127,7 +127,7 @@ describe('DialogContainer', () => { }); it('should inherit the dialog\'s renderNode context', () => { - const dialog = renderIntoDocument(<Dialog><DialogContainer {...PROPS} /></Dialog>); + const dialog = renderIntoDocument(<Dialog id="test"><DialogContainer {...PROPS} /></Dialog>); const container = findRenderedComponentWithType(dialog, DialogContainer); expect(container.context.renderNode).toBe(dialog.getChildContext().renderNode); }); diff --git a/src/js/Drawers/__tests__/Drawer.js b/src/js/Drawers/__tests__/Drawer.js index <HASH>..<HASH> 100644 --- a/src/js/Drawers/__tests__/Drawer.js +++ b/src/js/Drawers/__tests__/Drawer.js @@ -15,15 +15,15 @@ import DialogContainer from '../../Dialogs/DialogContainer'; describe('Drawer', () => { it('should inherit the dialog\'s renderNode context', () => { - const dialog = renderIntoDocument(<Dialog><Drawer /></Dialog>); + const dialog = renderIntoDocument(<Dialog id="test"><Drawer /></Dialog>); const drawer = findRenderedComponentWithType(dialog, Drawer); expect(drawer.context.renderNode).toBe(dialog.getChildContext().renderNode); }); it('should inerhit and pass the dialog\'s renderNode context', () => { const dialog = renderIntoDocument( - <Dialog> - <Drawer defaultVisible> + <Dialog id="test"> + <Drawer defaultVisible id="test-2"> <DialogContainer id="nested-dialog" visible onHide={jest.fn()} /> </Drawer> </Dialog> diff --git a/src/js/NavigationDrawers/__tests__/NavigationDrawer.js b/src/js/NavigationDrawers/__tests__/NavigationDrawer.js index <HASH>..<HASH> 100644 --- a/src/js/NavigationDrawers/__tests__/NavigationDrawer.js +++ b/src/js/NavigationDrawers/__tests__/NavigationDrawer.js @@ -49,7 +49,7 @@ describe('NavigationDrawer', () => { }); it('should inherit the dialog\'s renderNode context', () => { - const dialog = renderIntoDocument(<Dialog><NavigationDrawer /></Dialog>); + const dialog = renderIntoDocument(<Dialog id="test"><NavigationDrawer /></Dialog>); const drawer = findRenderedComponentWithType(dialog, NavigationDrawer); expect(drawer.context.renderNode).toBe(dialog.getChildContext().renderNode); }); diff --git a/src/js/Snackbars/__tests__/SnackbarContainer.js b/src/js/Snackbars/__tests__/SnackbarContainer.js index <HASH>..<HASH> 100644 --- a/src/js/Snackbars/__tests__/SnackbarContainer.js +++ b/src/js/Snackbars/__tests__/SnackbarContainer.js @@ -94,7 +94,7 @@ describe('SnackbarContainer', () => { }); it('should inherit the dialog\'s renderNode context', () => { - const dialog = renderIntoDocument(<Dialog><SnackbarContainer {...PROPS} /></Dialog>); + const dialog = renderIntoDocument(<Dialog id="test"><SnackbarContainer {...PROPS} /></Dialog>); const snackbar = findRenderedComponentWithType(dialog, SnackbarContainer); expect(snackbar.context.renderNode).toBe(dialog.getChildContext().renderNode); });
Updated nested dialog tests to include ids
mlaursen_react-md
train
633bec8b38635e7d78aaa0e4ea8f1a8cdb85050e
diff --git a/src/ocLazyLoad.js b/src/ocLazyLoad.js index <HASH>..<HASH> 100644 --- a/src/ocLazyLoad.js +++ b/src/ocLazyLoad.js @@ -940,8 +940,8 @@ }); } - if(initModules.length === 0) { - throw 'No module found during bootstrap, unable to init ocLazyLoad'; + if(modulesToLoad.length === 0 && !((window.jasmine || window.mocha) && angular.isDefined(angular.mock))) { + console.error('No module found during bootstrap, unable to init ocLazyLoad. You should always use the ng-app directive or angular.boostrap when you use ocLazyLoad.'); } var addReg = function addReg(moduleName) {
fix: don't throw for karma Fixes #<I>
ocombe_ocLazyLoad
train
ad7e1bd3be5be9383fbd274475b3cc5ae343c9b2
diff --git a/lib/sshkit/formatters/pretty.rb b/lib/sshkit/formatters/pretty.rb index <HASH>..<HASH> 100644 --- a/lib/sshkit/formatters/pretty.rb +++ b/lib/sshkit/formatters/pretty.rb @@ -12,7 +12,7 @@ module SSHKit return if obj.verbosity < SSHKit.config.output_verbosity unless obj.started? - original_output << level(obj.verbosity) + uuid(obj) + "Running #{c.yellow(c.bold(String(obj)))} on #{c.yellow(obj.host.to_s)}\n" + original_output << level(obj.verbosity) + uuid(obj) + "Running #{c.yellow(c.bold(String(obj)))} on #{c.blue(obj.host.to_s)}\n" if SSHKit.config.output_verbosity = Logger::DEBUG original_output << level(Logger::DEBUG) + uuid(obj) + c.white("Command: #{c.blue(obj.to_command)}") + "\n" end
Print host in blue in the pretty formatter
capistrano_sshkit
train
47daa2155a388d0ebe2d71fa0a524ba4f33e63e0
diff --git a/better_apidoc.py b/better_apidoc.py index <HASH>..<HASH> 100644 --- a/better_apidoc.py +++ b/better_apidoc.py @@ -147,6 +147,16 @@ def create_module_file(package, module, opts): write_file(makename(package, module), text, opts) +def _get_documenter(app, member, mod): + try: # Sphinx >= 2.0 + return get_documenter(app=app, obj=member, parent=mod) + except TypeError: # Sphinx < 2.0 does not accept kwargs + try: # Sphinx 1.7, 1.8 + return get_documenter(app, member, mod) + except (TypeError, ValueError): # Sphinx < 1.7 + return get_documenter(member, mod) + + def _get_members( mod, typ=None, include_imported=False, out_format='names', in_list=None, known_refs=None): @@ -170,7 +180,7 @@ def _get_members( """Check if mod.member is of the desired typ""" if inspect.ismodule(member): return False - documenter = get_documenter(app=APP, obj=member, parent=mod) + documenter = _get_documenter(APP, member, mod) if typ is None: return True if typ == getattr(documenter, 'objtype', None): @@ -215,7 +225,7 @@ def _get_members( if not (include_imported or is_local(mod, member, name)): continue if out_format in ['table', 'refs']: - documenter = get_documenter(app=APP, obj=member, parent=mod) + documenter = _get_documenter(APP, member, mod) role = roles.get(documenter.objtype, 'obj') ref = _get_member_ref_str( name, obj=member, role=role,
Fix calls to get_documenter for any Sphinx version between <I> and <I> Sphinx changed `get_documenter` four times, with different combinations of two or three arguments and accepting and not accepting keyword arguments. This should work for all of them. Closes #<I>
goerz_better-apidoc
train
be11788d723bacbe25a61bd19e5bff24d67f2429
diff --git a/lib/build/development/build_server.rb b/lib/build/development/build_server.rb index <HASH>..<HASH> 100644 --- a/lib/build/development/build_server.rb +++ b/lib/build/development/build_server.rb @@ -5,7 +5,6 @@ module RhoDevelopment def build_partial_bundles_for_all_subscribers Configuration::enabled_subscribers.each { |each| self.build_partial_bundle_for_platform(each.normalized_platform_name) - self.copy_platform_bundle_to_web_server_root(each.normalized_platform_name, Configuration::partial_bundle_name) } end @@ -18,12 +17,12 @@ module RhoDevelopment def build_full_bundle_for_subscriber(aSubscriber) RhoDevelopment.setup(Configuration::development_directory, aSubscriber.normalized_platform_name) RhoDevelopment.make_full_bundle + self.copy_platform_bundle_to_web_server_root(aSubscriber.normalized_platform_name, Configuration::full_bundle_name) end def build_full_bundles_for_all_subscribers Configuration::enabled_subscribers.each { |each| self.build_full_bundle_for_subscriber(each) - self.copy_platform_bundle_to_web_server_root(each.normalized_platform_name, Configuration::full_bundle_name) } end
[Live Update]: fix for filename of downloading bundle
rhomobile_rhodes
train
2470947e01ee130d22404a53757b5d00b4900247
diff --git a/test/test_helper.rb b/test/test_helper.rb index <HASH>..<HASH> 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -49,7 +49,7 @@ BASE_TEST_CLASS = if defined?(Minitest::Test) module Declarative def test(name, &block) - define_method("test #{name}", &block) + define_method("test_ #{name}", &block) end end
Make dynamic test names start with test_ Minitest checks for methods names starting with "test_", not just "test" (i.e. there is an underscore). This appears to be a change a in recent version.
haml_haml
train
b044d6778c6843b7d27f42ca65868760d0759b03
diff --git a/tests/test.changes.js b/tests/test.changes.js index <HASH>..<HASH> 100644 --- a/tests/test.changes.js +++ b/tests/test.changes.js @@ -639,19 +639,18 @@ adapters.map(function (adapter) { db.post({ test: 'adoc' }); }); - it('Kill database while listening to continuous changes', function (done) { + // TODO: https://github.com/daleharvey/pouchdb/issues/1460 + it.skip('Kill database while listening to continuous changes', function (done) { var db = new PouchDB(dbs.name); var count = 0; - var changes = db.changes({ + db.changes({ complete: function (err, result) { done(); }, onChange: function (change) { count += 1; if (count === 1) { - PouchDB.destroy(dbs.name, function () { - changes.cancel(); - }); + PouchDB.destroy(dbs.name); } }, continuous: true
(#<I>) - Skip currently broken test for changes + db deletion
pouchdb_pouchdb
train
28618eac7e8dfa31b68bce2b56901b51c6ac5eb0
diff --git a/example/simple.js b/example/simple.js index <HASH>..<HASH> 100644 --- a/example/simple.js +++ b/example/simple.js @@ -25,17 +25,17 @@ var reg_form = forms.create({ required: true, validators: [validators.matchField('password')] }), - personal: fields.object({ - name: fields.string({required: true}), - email: fields.email({required: true}), - address: fields.object({ - address1: fields.string({required: true}), - address2: fields.string(), - city: fields.string({required: true}), - state: fields.string({required: true}), - zip: fields.number({required: true}) - }) - }) + personal: { + name: fields.string({required: true, label: 'Name'}), + email: fields.email({required: true, label: 'Email'}), + address: { + address1: fields.string({required: true, label: 'Address 1'}), + address2: fields.string({label: 'Address 2'}), + city: fields.string({required: true, label: 'City'}), + state: fields.string({required: true, label: 'State'}), + zip: fields.number({required: true, label: 'ZIP'}) + } + } }); http.createServer(function (req, res) { diff --git a/lib/forms.js b/lib/forms.js index <HASH>..<HASH> 100644 --- a/lib/forms.js +++ b/lib/forms.js @@ -14,6 +14,10 @@ exports.validators = require('./validators'); exports.create = function (fields) { Object.keys(fields).forEach(function (k) { + // if it's not a field object, create an object field. + if(typeof fields[k].toHTML !== 'function' && typeof fields[k] == 'object') { + fields[k] = exports.fields.object(fields[k]); + } fields[k].name = k; }); var f = {
take object literals as nested fields
caolan_forms
train
d75f21b51b63179c9604b16e37e747e357b63ab2
diff --git a/raven/base.py b/raven/base.py index <HASH>..<HASH> 100644 --- a/raven/base.py +++ b/raven/base.py @@ -636,7 +636,13 @@ class Client(object): **kwargs) # should this event be sampled? - if self._random.random() < self.sample_rate: + sample_rate = self.sample_rate + try: + sample_rate = float(extra['sample_rate']) + except (TypeError, KeyError, ValueError): + pass + + if self._random.random() < sample_rate: self.send(**data) self._local_state.last_event_id = data['event_id'] diff --git a/tests/base/tests.py b/tests/base/tests.py index <HASH>..<HASH> 100644 --- a/tests/base/tests.py +++ b/tests/base/tests.py @@ -551,6 +551,44 @@ class ClientTest(TestCase): expected = {'logger': "u'test'", 'foo': "u'bar'"} self.assertEquals(event['extra'], expected) + def test_sample_rate(self): + self.client.sample_rate = 0.0 + self.client.captureMessage(message='test') + self.assertEquals(len(self.client.events), 0) + + def test_sample_rate_per_message(self): + self.client.extra = { + 'foo': 'bar', + } + self.client.sample_rate = 1 + self.client.captureMessage(message='test', extra={'sample_rate': 0.0}) + self.assertEquals(len(self.client.events), 0) + + self.client.sample_rate = 0 + self.client.captureMessage(message='test', extra={'sample_rate': 1.0}) + self.assertEquals(len(self.client.events), 1) + event = self.client.events.pop(0) + if not PY2: + expected = {'sample_rate': 1.0, 'foo': "'bar'"} + else: + expected = {'sample_rate': 1.0, 'foo': "u'bar'"} + self.assertEquals(event['extra'], expected) + + def test_sample_rate_per_message_is_resilient_to_bad_values(self): + self.client.sample_rate = 0 + + # sample_rate is not a number + self.client.captureMessage(message='test', extra={'sample_rate': 'foo'}) + self.assertEquals(len(self.client.events), 0) + + # sample_rate is not present + self.client.captureMessage(message='test', extra={'foo': '1.0'}) + self.assertEquals(len(self.client.events), 0) + + # sample_rate can be cast into a float + self.client.captureMessage(message='test', extra={'sample_rate': '1.0'}) + self.assertEquals(len(self.client.events), 1) + def test_transport_registration(self): client = Client('http://public:secret@example.com/1', transport=HTTPTransport)
Add provision to sample per message - If `sample_rate` is present in the `extra` kwarg, use that value to overwrite the client's sample_rate. This allows event-level granularity for sampling
getsentry_raven-python
train
5eaddd862ea6b0c39ac9ecef070a8a94befd6e56
diff --git a/lib/bugsnag.rb b/lib/bugsnag.rb index <HASH>..<HASH> 100644 --- a/lib/bugsnag.rb +++ b/lib/bugsnag.rb @@ -47,7 +47,7 @@ module Bugsnag @logged_ready = false unless defined?(@logged_ready) if configuration.api_key && !@logged_ready - log "Bugsnag exception handler #{VERSION} ready, api_key=#{configuration.api_key}" + log "Bugsnag exception handler #{VERSION} ready" @logged_ready = true end end
Remove API key from ‘handler ready’ message The API key is potentially sensitive if logs are handled through a third-party service. Fixes #<I>
bugsnag_bugsnag-ruby
train
7187f787eb7d6afa22588e61466d9eb606531006
diff --git a/app/lib/Core/Repository/Content.php b/app/lib/Core/Repository/Content.php index <HASH>..<HASH> 100755 --- a/app/lib/Core/Repository/Content.php +++ b/app/lib/Core/Repository/Content.php @@ -25,6 +25,7 @@ class Content extends Repository $params = $params + [ 'types' => null, + 'subtypes' => null, 'createDateMin' => null, 'createDateMax' => null, 'modifyDateMin' => null, @@ -32,7 +33,7 @@ class Content extends Repository 'createUsers' => null, 'statuses' => null, ]; - + if (isset($params['types'])) { $types = $this->_parseTypes($params['types']); $lines = []; @@ -46,7 +47,12 @@ class Content extends Repository $lines[] = "({$line})"; $i++; } - $query->andWhere(implode(' OR ', $lines)); + $query->andWhere(implode(' OR ', $lines)); + } + if (isset($params['subtypes'])) { + $query + ->andWhere("c.subtype IN (:subtypes)") + ->setParameter('subtypes', $params['subtypes']); } if (isset($params['createDateMin'])) {
Ability to filter content queries by subtypes.
jacksleight_chalk
train
1d75da5203bdfaa47e920f5d749b85abff5f07f7
diff --git a/sentry_sdk/tracing.py b/sentry_sdk/tracing.py index <HASH>..<HASH> 100644 --- a/sentry_sdk/tracing.py +++ b/sentry_sdk/tracing.py @@ -583,22 +583,23 @@ class Transaction(Span): decision, `traces_sample_rate` will be used. """ + # if the user has forced a sampling decision by passing a `sampled` + # value when starting the transaction, go with that + if self.sampled is not None: + return + hub = self.hub or sentry_sdk.Hub.current client = hub.client - options = (client and client.options) or {} transaction_description = "{op}transaction <{name}>".format( op=("<" + self.op + "> " if self.op else ""), name=self.name ) - # nothing to do if there's no client or if tracing is disabled - if not client or not has_tracing_enabled(options): + # nothing to do if there's no client + if not client: self.sampled = False return - # if the user has forced a sampling decision by passing a `sampled` - # value when starting the transaction, go with that - if self.sampled is not None: - return + options = client.options # we would have bailed already if neither `traces_sampler` nor # `traces_sample_rate` were defined, so one of these should work; prefer @@ -662,16 +663,6 @@ class Transaction(Span): ) -def has_tracing_enabled(options): - # type: (Dict[str, Any]) -> bool - """ - Returns True if either traces_sample_rate or traces_sampler is - non-zero/defined, False otherwise. - """ - - return bool(options.get("traces_sample_rate") or options.get("traces_sampler")) - - def _is_valid_sample_rate(rate): # type: (Any) -> bool """ diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ def get_file_text(file_name): with open(os.path.join(here, file_name)) as in_file: return in_file.read() - + setup( name="sentry-sdk", version="0.19.4", @@ -31,7 +31,7 @@ setup( }, description="Python client for Sentry (https://sentry.io)", long_description=get_file_text("README.md"), - long_description_content_type='text/markdown', + long_description_content_type="text/markdown", packages=find_packages(exclude=("tests", "tests.*")), # PEP 561 package_data={"sentry_sdk": ["py.typed"]}, diff --git a/tests/tracing/test_integration_tests.py b/tests/tracing/test_integration_tests.py index <HASH>..<HASH> 100644 --- a/tests/tracing/test_integration_tests.py +++ b/tests/tracing/test_integration_tests.py @@ -47,12 +47,15 @@ def test_basic(sentry_init, capture_events, sample_rate): @pytest.mark.parametrize("sampled", [True, False, None]) -def test_continue_from_headers(sentry_init, capture_events, sampled): - sentry_init(traces_sample_rate=1.0) +@pytest.mark.parametrize( + "sample_rate", [0.0, 1.0] +) # ensure sampling decision is actually passed along via headers +def test_continue_from_headers(sentry_init, capture_events, sampled, sample_rate): + sentry_init(traces_sample_rate=sample_rate) events = capture_events() # make a parent transaction (normally this would be in a different service) - with start_transaction(name="hi"): + with start_transaction(name="hi", sampled=True if sample_rate == 0 else None): with start_span() as old_span: old_span.sampled = sampled headers = dict(Hub.current.iter_trace_propagation_headers()) @@ -84,7 +87,7 @@ def test_continue_from_headers(sentry_init, capture_events, sampled): scope.transaction = "ho" capture_message("hello") - if sampled is False: + if sampled is False or (sample_rate == 0 and sampled is None): trace1, message = events assert trace1["transaction"] == "hi"
fix: Fix sample decision propagation via headers (#<I>)
getsentry_sentry-python
train
ab404bc7ee4e628465b23691143dc433e1b00823
diff --git a/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java b/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java index <HASH>..<HASH> 100644 --- a/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java +++ b/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java @@ -29,6 +29,7 @@ package org.opencms.ade.containerpage.client; import org.opencms.ade.containerpage.client.ui.CmsContainerPageElementPanel; import org.opencms.ade.containerpage.client.ui.CmsGroupContainerElementPanel; +import org.opencms.ade.containerpage.client.ui.groupeditor.CmsInheritanceContainerEditor; import org.opencms.ade.containerpage.shared.CmsContainerElement; import org.opencms.ade.containerpage.shared.CmsContainerElementData; import org.opencms.ade.publish.client.CmsPublishDialog; @@ -241,6 +242,9 @@ public class CmsContainerpageHandler extends A_CmsToolbarHandler { Map<String, String> fieldValues, Set<String> editedFields) { + if (CmsInheritanceContainerEditor.getInstance() != null) { + CmsInheritanceContainerEditor.getInstance().onSettingsEdited(); + } m_controller.reloadElementWithSettings( elementWidget, elementBean.getClientId(), diff --git a/src-gwt/org/opencms/ade/containerpage/client/ui/groupeditor/CmsInheritanceContainerEditor.java b/src-gwt/org/opencms/ade/containerpage/client/ui/groupeditor/CmsInheritanceContainerEditor.java index <HASH>..<HASH> 100644 --- a/src-gwt/org/opencms/ade/containerpage/client/ui/groupeditor/CmsInheritanceContainerEditor.java +++ b/src-gwt/org/opencms/ade/containerpage/client/ui/groupeditor/CmsInheritanceContainerEditor.java @@ -86,6 +86,9 @@ public class CmsInheritanceContainerEditor extends A_CmsGroupEditor { /** A flag which indicates whether the inheritance configuration needs to be updated. */ private boolean m_changedInheritanceInfo; + + /** Flag which indicates whether the settings of an inheritance group element have been edited. */ + private boolean m_editedSettings; /** The description input. */ private CmsTextBox m_inputDescription; @@ -178,6 +181,14 @@ public class CmsInheritanceContainerEditor extends A_CmsGroupEditor { } /** + * Method which should be called after the settings of an element in the inheritance containerhave been edited.<p> + */ + public void onSettingsEdited() { + + m_editedSettings = true; + } + + /** * Either removes the locally configured element or hides the inherited element.<p> * * @param elementWidget the element widget @@ -371,6 +382,7 @@ public class CmsInheritanceContainerEditor extends A_CmsGroupEditor { List<CmsContainerElement> elements = new ArrayList<CmsContainerElement>(); boolean moved = m_moveHandler.isDropped(); m_changedInheritanceInfo |= moved; + m_changedInheritanceInfo |= m_editedSettings; for (Widget widget : getGroupContainerWidget()) { if (widget instanceof CmsContainerPageElementPanel) { CmsContainerPageElementPanel elementWidget = (CmsContainerPageElementPanel)widget;
Fixed bug with saving changed settings of inheritance groups.
alkacon_opencms-core
train
17176f79cc7d87420c42fda37cb155f6924710da
diff --git a/lib/util/formatting.js b/lib/util/formatting.js index <HASH>..<HASH> 100644 --- a/lib/util/formatting.js +++ b/lib/util/formatting.js @@ -99,18 +99,24 @@ } function enumerateModesBetween(cm, line, start, end) { - var outer = cm.getMode(); + var outer = cm.getMode(), text = cm.getLine(line); + if (end == null) end = text.length; if (!outer.innerMode) return [{from: start, to: end, mode: outer}]; - var init = CodeMirror.innerMode(outer, cm.getTokenAt({line: line, ch: start}).state); - var state = init.state, mode = init.mode; - var found = [], stream = new CodeMirror.StringStream(cm.getLine(line)); + var state = cm.getTokenAt({line: line, ch: start}).state; + var mode = CodeMirror.innerMode(outer, state).mode; + var found = [], stream = new CodeMirror.StringStream(text); stream.pos = stream.start = start; for (;;) { outer.token(stream, state); - var cur = CodeMirror.innerMode(outer, state).mode; + var curMode = CodeMirror.innerMode(outer, state).mode; if (curMode != mode) { - found.push({from: start, to: stream.pos, mode: mode}); - start = stream.pos; + var cut = stream.start; + // Crappy heuristic to deal with the fact that a change in + // mode can occur both at the end and the start of a token, + // and we don't know which it was. + if (mode.name == "xml" && text.charAt(stream.pos - 1) == ">") cut = stream.pos; + found.push({from: start, to: cut, mode: mode}); + start = cut; mode = curMode; } if (stream.pos >= end) break; @@ -167,7 +173,7 @@ var text = cm.getRange(f, t); for (var i = 0; i < modes.length; ++i) { var part = modes.length > 1 ? text.slice(modes[i].from, modes[i].to) : text; - if (i) mangled += "\n"; + if (mangled) mangled += "\n"; if (modes[i].mode.autoFormatLineBreaks) { mangled += modes[i].mode.autoFormatLineBreaks(part); } else mangled += text; @@ -181,6 +187,7 @@ } for (var cur = from.line + 1; cur <= end; ++cur) cm.indentLine(cur, "smart"); + cm.setSelection(from, cm.getCursor(false)); }); }); })();
[util/formatting] Fix a bunch of bugs That's what you get when you test with the published version, rather than the one you're actually editing.
codemirror_CodeMirror
train
93d6818a075eca03ad376fd01f796652abde4bf0
diff --git a/test/test_validate.py b/test/test_validate.py index <HASH>..<HASH> 100644 --- a/test/test_validate.py +++ b/test/test_validate.py @@ -26,6 +26,7 @@ except ImportError: sys.stdout, sys.stderr = oldio +import logging import os import unittest import shutil @@ -53,6 +54,39 @@ class TempdirGuard(object): shutil.rmtree(self.path) # always clean up on exit +class CaptureLogger(object): + """Context manager to capture `logging` streams + + Args: + - logger: 'logging` logger object + - string_buff: StringIO object to put the log output to + + Results: + The captured output is available via the object passed in as string_buf + + """ + + def __init__(self, logger, string_buf): + self.logger = logger + self.string_buf = string_buf + self.handler = logging.StreamHandler(self.string_buf) + self.old_handlers = [] + self.old_level = None + + def __enter__(self): + self.logger.level = logging.DEBUG + self.logger.handlers = [] + self.logger.addHandler(self.handler) + self.old_handlers = self.logger.handlers + self.old_level = self.logger.level + return self + + def __exit__(self, *exc): + self.logger.removeHandler(self.handler) + self.logger.handlers = self.old_handlers + self.logger.level = self.old_level + + class TestUMLGenerateDirectiveBase(unittest.TestCase): """ A collection of tests for the UMLGenerateDirective object """ @@ -251,12 +285,26 @@ class TestLogFixture(TestUMLGenerateDirectiveBase): instance = self.gen() - with StringIO() as buf, redirect_stdout(buf): + with StringIO() as buf, redirect_stdout(buf), CaptureLogger( + logging.getLogger(), buf + ): with self.assertRaises(test.mock_subprocess.CalledProcessError): test.mock_subprocess.failing_call("") + + # nothing should be logged to stdout or put to logs self.assertEqual(buf.getvalue(), "") - with StringIO() as buf, redirect_stdout(buf): + with StringIO() as buf, redirect_stdout(buf), CaptureLogger( + logging.getLogger(), buf + ): with self.assertRaises(test.mock_subprocess.CalledProcessError): instance.run() - self.assertEqual(buf.getvalue(), "dummy output\n") + + expected_output = ( + "sphinx-pyreverse: Running: pyreverse --output png --project " + "noexist_module noexist_module\n" + "pyreverse-log: dummy output\n" + ) + + # nothing should be printed to stdout or the logger + self.assertEqual(buf.getvalue(), expected_output)
Fixes unit tests after log output changes
alendit_sphinx-pyreverse
train
275cf68c1e1212d4281a547e695b2435177896cc
diff --git a/Minimal-J_Example/src/main/java/ch/openech/mj/example/AddBookEditor.java b/Minimal-J_Example/src/main/java/ch/openech/mj/example/AddBookEditor.java index <HASH>..<HASH> 100644 --- a/Minimal-J_Example/src/main/java/ch/openech/mj/example/AddBookEditor.java +++ b/Minimal-J_Example/src/main/java/ch/openech/mj/example/AddBookEditor.java @@ -11,21 +11,16 @@ import ch.openech.mj.example.model.Book; public class AddBookEditor extends Editor<Book> { @Override - public Book newInstance() { - return new Book(); + public IForm<Book> createForm() { + return new BookForm(true); } - + @Override public void validate(Book object, List<ValidationMessage> resultList) { // nothing to validate } @Override - public IForm<Book> createForm() { - return new BookForm(true); - } - - @Override public boolean save(Book book) { try { ExamplePersistence.getInstance().book().insert(book); diff --git a/Minimal-J_Example/src/main/java/ch/openech/mj/example/BookViewPage.java b/Minimal-J_Example/src/main/java/ch/openech/mj/example/BookViewPage.java index <HASH>..<HASH> 100644 --- a/Minimal-J_Example/src/main/java/ch/openech/mj/example/BookViewPage.java +++ b/Minimal-J_Example/src/main/java/ch/openech/mj/example/BookViewPage.java @@ -2,9 +2,9 @@ package ch.openech.mj.example; import java.sql.SQLException; -import ch.openech.mj.application.ObjectViewPage; import ch.openech.mj.edit.form.IForm; import ch.openech.mj.example.model.Book; +import ch.openech.mj.page.ObjectViewPage; import ch.openech.mj.page.PageContext; public class BookViewPage extends ObjectViewPage<Book> {
Don't override newInstance in Editor if not necessary
BrunoEberhard_minimal-j
train
291c0fe3f6f4a95ab9a26601a1258f88ecd04db4
diff --git a/src/core/dom-lib/balalaika.js b/src/core/dom-lib/balalaika.js index <HASH>..<HASH> 100755 --- a/src/core/dom-lib/balalaika.js +++ b/src/core/dom-lib/balalaika.js @@ -11,7 +11,7 @@ define([ }; $.i = function(s, context) { - fn.push.apply(this, !s ? fn : s.nodeType || s == window ? [s] : "" + s === s ? /</.test(s) ? ((i = document.createElement(context || 'div')).innerHTML = s, i.children) : (context && $(context)[0] || document).querySelectorAll(s) : /f/.test(typeof s) ? /c/.test(document.readyState) ? s() : $(document).on('DOMContentLoaded', s) : s.length ? s : [s]); + fn.push.apply(this, !s ? fn : s.nodeType || s == window ? [s] : "" + s === s ? /</.test(s) ? ((i = document.createElement(context || 'div')).innerHTML = s, i.children) : (context && $(context)[0] || document).querySelectorAll(s) : /f/.test(typeof s) ? /c/.test(document.readyState) ? s() : $(document).on('DOMContentLoaded', s) : 'length' in s ? s : [s]); }; $.i[l = 'prototype'] = ($.extend = function(obj) {
allow to use any objects in balalaika (little fix)
matreshkajs_matreshka
train
0fa1eba4cde3884632d4affb3675222023bd9820
diff --git a/src/main/java/com/redhat/contentspec/processor/ContentSpecParser.java b/src/main/java/com/redhat/contentspec/processor/ContentSpecParser.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/redhat/contentspec/processor/ContentSpecParser.java +++ b/src/main/java/com/redhat/contentspec/processor/ContentSpecParser.java @@ -33,6 +33,7 @@ import com.redhat.contentspec.entities.InjectionOptions; import com.redhat.contentspec.utils.ContentSpecUtilities; import com.redhat.contentspec.utils.logging.ErrorLogger; import com.redhat.contentspec.utils.logging.ErrorLoggerManager; +import com.redhat.ecs.commonstructures.Pair; import com.redhat.ecs.commonutils.CollectionUtilities; import com.redhat.ecs.commonutils.StringUtilities; import com.redhat.topicindex.rest.entities.interfaces.RESTUserV1; @@ -149,6 +150,42 @@ public class ContentSpecParser } /** + * Gets a list of Topic ID's that are used in a Content Specification. + * The list only includes topics that don't reference a revision of a + * topic. + * + * @return A List of topic ID's. + */ + public List<Integer> getReferencedLatestTopicIds() + { + final List<Integer> ids = new ArrayList<Integer>(); + for(final String topicId: specTopics.keySet()) + { + final SpecTopic specTopic = specTopics.get(topicId); + if (specTopic.getDBId() != 0 && specTopic.getRevision() == null) ids.add(specTopic.getDBId()); + } + return ids; + } + + /** + * Gets a list of Topic ID's that are used in a Content Specification. + * The list only includes topics that reference a topic revision rather + * then the latest topic revision. + * + * @return A List of topic ID's. + */ + public List<Pair<Integer, Integer>> getReferencedRevisionTopicIds() + { + final List<Pair<Integer, Integer>> ids = new ArrayList<Pair<Integer, Integer>>(); + for(final String topicId: specTopics.keySet()) + { + final SpecTopic specTopic = specTopics.get(topicId); + if (specTopic.getDBId() != 0 && specTopic.getRevision() != null) ids.add(new Pair<Integer, Integer>(specTopic.getDBId(), specTopic.getRevision())); + } + return ids; + } + + /** * Get the Content Specification object that represents a Content Specification * * @return The Content Specification object representation. diff --git a/src/main/java/com/redhat/contentspec/processor/ContentSpecProcessor.java b/src/main/java/com/redhat/contentspec/processor/ContentSpecProcessor.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/redhat/contentspec/processor/ContentSpecProcessor.java +++ b/src/main/java/com/redhat/contentspec/processor/ContentSpecProcessor.java @@ -18,6 +18,7 @@ import com.redhat.contentspec.rest.RESTWriter; import com.redhat.contentspec.rest.utils.TopicPool; import com.redhat.contentspec.utils.logging.ErrorLogger; import com.redhat.contentspec.utils.logging.ErrorLoggerManager; +import com.redhat.ecs.commonstructures.Pair; import com.redhat.ecs.commonutils.CollectionUtilities; import com.redhat.ecs.commonutils.ExceptionUtilities; import com.redhat.ecs.constants.CommonConstants; @@ -147,10 +148,36 @@ public class ContentSpecProcessor implements ShutdownAbleApp return false; } - // Download the list of topics in one go to reduce I/O overhead - LOG.info("Attempting to download all topics..."); - reader.getTopicsByIds(csp.getReferencedTopicIds(), csp.getContentSpec().getLocale() != null && !csp.getContentSpec().getLocale().equals(CommonConstants.DEFAULT_LOCALE)); - + if (!csp.getReferencedLatestTopicIds().isEmpty()) + { + // Download the list of topics in one go to reduce I/O overhead + LOG.info("Attempting to download all the latest topics..."); + reader.getTopicsByIds(csp.getReferencedLatestTopicIds(), csp.getContentSpec().getLocale() != null && !csp.getContentSpec().getLocale().equals(CommonConstants.DEFAULT_LOCALE)); + } + + final List<Pair<Integer, Integer>> referencedRevisionTopicIds = csp.getReferencedRevisionTopicIds(); + if (!referencedRevisionTopicIds.isEmpty()) + { + LOG.info("Attempting to download all the revision topics..."); + + final int showPercent = 5; + final float total = referencedRevisionTopicIds.size(); + float current = 0; + int lastPercent = 0; + + for (final Pair<Integer, Integer> topicToRevision : referencedRevisionTopicIds) + { + reader.getTopicById(topicToRevision.getFirst(), topicToRevision.getSecond()); + + ++current; + final int percent = Math.round(current / total * 100); + if (percent - lastPercent >= showPercent) + { + lastPercent = percent; + log.info("\tDownloading revision topics " + percent + "% Done"); + } + } + } // Check if the app should be shutdown if (isShuttingDown.get()) { @@ -188,7 +215,7 @@ public class ContentSpecProcessor implements ShutdownAbleApp return false; } - LOG.info("Saving the Content Specification..."); + LOG.info("Saving the Content Specification to the server..."); if (saveContentSpec(csp.getContentSpec(), csp.getSpecTopics(), editing)) { log.info(ProcessorConstants.INFO_SUCCESSFUL_SAVE_MSG);
Updated some log messages and changed the processor to pull revisions down before validating.
pressgang-ccms_PressGangCCMSContentSpecProcessor
train
2ffd50ecb4d3f900f75552f2554a66b0a5c14ad5
diff --git a/src/CustomElements.php b/src/CustomElements.php index <HASH>..<HASH> 100644 --- a/src/CustomElements.php +++ b/src/CustomElements.php @@ -8,6 +8,7 @@ namespace MadeYourDay\RockSolidCustomElements; +use Doctrine\DBAL\DBALException; use MadeYourDay\RockSolidCustomElements\Template\CustomTemplate; /** @@ -1153,10 +1154,15 @@ class CustomElements } } - $themes = \Database::getInstance() - ->prepare('SELECT name, templates FROM tl_theme') - ->execute() - ->fetchAllAssoc(); + try { + $themes = \Database::getInstance() + ->prepare('SELECT name, templates FROM tl_theme') + ->execute() + ->fetchAllAssoc(); + } + catch (DBALException $e) { + $themes = array(); + } $themeNamesByTemplateDir = array(); foreach ($themes as $theme) { if ($theme['templates']) {
Fixed #<I> bug with missing database connection
madeyourday_contao-rocksolid-custom-elements
train
cd374292f4fd2b8093caf4b74afa3b1d6130cdac
diff --git a/Lib/Sakonnin/CommonFunctions.php b/Lib/Sakonnin/CommonFunctions.php index <HASH>..<HASH> 100644 --- a/Lib/Sakonnin/CommonFunctions.php +++ b/Lib/Sakonnin/CommonFunctions.php @@ -45,7 +45,7 @@ trait CommonFunctions // address $body = ''; - if (isset($options['provide_link'])) { + if (isset($options['provide_link']) && $options['provide_link']) { $router = $this->getRouter(); $url = $router->generate('message_show', array('id' => $message->getId()), true); $body .= "Link to this message: " . $url . "\n\n";
I have to drop isset some day.
thomasez_BisonLabSakonninBundle
train
235e36fce8e345caf4d2ce0e6780889bf517aa7e
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -39,6 +39,8 @@ REQUIREMENTS = [ 'cloudpickle', 'ipykernel<5; python_version<"3"', 'ipykernel>=5.1.3; python_version>="3"', + 'ipython<6; python_version<"3"', + 'ipython>=7.6.0; python_version>="3"', 'jupyter-client>=5.3.4', 'pyzmq>=17', 'wurlitzer>=1.0.3;platform_system!="Windows"',
Add explicit dependency on IPython This will better allows us to control the things we import from it
spyder-ide_spyder-kernels
train
f0326ac44e6dc4c01d80ee9a206a84bf58a3e9ed
diff --git a/python_modules/dagster-test/dagster_test/fixtures/docker_compose.py b/python_modules/dagster-test/dagster_test/fixtures/docker_compose.py index <HASH>..<HASH> 100644 --- a/python_modules/dagster-test/dagster_test/fixtures/docker_compose.py +++ b/python_modules/dagster-test/dagster_test/fixtures/docker_compose.py @@ -9,7 +9,7 @@ import pytest from .utils import BUILDKITE -@pytest.fixture +@pytest.fixture(scope="module") def docker_compose_cm(test_directory): @contextmanager def docker_compose( diff --git a/python_modules/dagster-test/dagster_test/fixtures/utils.py b/python_modules/dagster-test/dagster_test/fixtures/utils.py index <HASH>..<HASH> 100644 --- a/python_modules/dagster-test/dagster_test/fixtures/utils.py +++ b/python_modules/dagster-test/dagster_test/fixtures/utils.py @@ -16,7 +16,7 @@ def retrying_requests(): yield session -@pytest.fixture +@pytest.fixture(scope="module") def test_directory(request): yield os.path.dirname(request.fspath)
make some docker-compose fixtures module-scoped (#<I>) Summary: These allow you to have fixtures that only run docker-compose once per module Test Plan: BK Reviewers: jmsanders
dagster-io_dagster
train
bd6f52e467bc3bff78c426cf70e0700d77272a75
diff --git a/lxd/backup.go b/lxd/backup.go index <HASH>..<HASH> 100644 --- a/lxd/backup.go +++ b/lxd/backup.go @@ -353,7 +353,19 @@ func backupCreateTarball(s *state.State, path string, backup backup) error { } if compress != "none" { - compressedPath, err := compressFile(backupPath, compress) + infile, err := os.Open(backupPath) + if err != nil { + return err + } + defer infile.Close() + + compressed, err := os.Create(backupPath + ".compressed") + if err != nil { + return err + } + defer compressed.Close() + + err = compressFile(compress, infile, compressed) if err != nil { return err } @@ -363,7 +375,7 @@ func backupCreateTarball(s *state.State, path string, backup backup) error { return err } - err = os.Rename(compressedPath, backupPath) + err = os.Rename(compressed.Name(), backupPath) if err != nil { return err } diff --git a/lxd/images.go b/lxd/images.go index <HASH>..<HASH> 100644 --- a/lxd/images.go +++ b/lxd/images.go @@ -129,7 +129,7 @@ func unpackImage(imagefname string, destpath string, sType storageType, runningI return nil } -func compressFile(path string, compress string) (string, error) { +func compressFile(compress string, infile io.Reader, outfile io.Writer) error { reproducible := []string{"gzip"} args := []string{"-c"} @@ -137,24 +137,11 @@ func compressFile(path string, compress string) (string, error) { args = append(args, "-n") } - args = append(args, path) cmd := exec.Command(compress, args...) - - outfile, err := os.Create(path + ".compressed") - if err != nil { - return "", err - } - - defer outfile.Close() + cmd.Stdin = infile cmd.Stdout = outfile - err = cmd.Run() - if err != nil { - os.Remove(outfile.Name()) - return "", err - } - - return outfile.Name(), nil + return cmd.Run() } /* @@ -223,7 +210,21 @@ func imgPostContInfo(d *Daemon, r *http.Request, req api.ImagesPost, builddir st } if compress != "none" { - compressedPath, err = compressFile(tarfile.Name(), compress) + tarfile, err = os.Open(tarfile.Name()) + if err != nil { + return nil, err + } + defer tarfile.Close() + + compressedPath = tarfile.Name() + ".compressed" + + compressed, err := os.Create(compressedPath) + if err != nil { + return nil, err + } + defer compressed.Close() + + err = compressFile(compress, tarfile, compressed) if err != nil { return nil, err } diff --git a/lxd/patches.go b/lxd/patches.go index <HASH>..<HASH> 100644 --- a/lxd/patches.go +++ b/lxd/patches.go @@ -3154,7 +3154,19 @@ func patchMoveBackups(name string, d *Daemon) error { } // Compress it - compressedPath, err := compressFile(backupPath, "xz") + infile, err := os.Open(backupPath) + if err != nil { + return err + } + defer infile.Close() + + compressed, err := os.Create(backupPath + ".compressed") + if err != nil { + return err + } + defer compressed.Close() + + err = compressFile("xz", infile, compressed) if err != nil { return err } @@ -3164,7 +3176,7 @@ func patchMoveBackups(name string, d *Daemon) error { return err } - err = os.Rename(compressedPath, backupPath) + err = os.Rename(compressed.Name(), backupPath) if err != nil { return err }
lxd/images: change compressFile to take io.Reader and io.Writer This is part 1 of a series of patches to add better progress tracking support for export and import. By using Reader and Writer rather than filename for compressing the caller can provide a tracking reader/writer for progress.
lxc_lxd
train
86b60309afca69455938316329fda7ac73c78660
diff --git a/Gemfile b/Gemfile index <HASH>..<HASH> 100644 --- a/Gemfile +++ b/Gemfile @@ -5,4 +5,5 @@ gem 'jumpstart' group :test do require 'test/unit' require 'shoulda' + require 'rr' end diff --git a/test/helper.rb b/test/helper.rb index <HASH>..<HASH> 100755 --- a/test/helper.rb +++ b/test/helper.rb @@ -1,13 +1,14 @@ require 'rubygems' require 'test/unit' require 'shoulda' +require 'rr' $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'jumpstart' class Test::Unit::TestCase - + include RR::Adapters::TestUnit end module JumpStart diff --git a/test/jumpstart/test_base.rb b/test/jumpstart/test_base.rb index <HASH>..<HASH> 100755 --- a/test/jumpstart/test_base.rb +++ b/test/jumpstart/test_base.rb @@ -89,21 +89,17 @@ class TestJumpstartBase < Test::Unit::TestCase end # TODO Looks like testing methods that call gets is going to be tough this way. Look at using a mocking tool like 'RR' - # should "load the jumpstart menu if the specified yaml config file does not exist" do - # FileUtils.delete_dir_contents("#{JumpStart::ROOT_PATH}/test/destination_dir") - # @test_project_2b = JumpStart::Base.new(["test_jumpstart_project", "a_name_that_does_not_exist"]) - # @test_project_2b.instance_variable_set(:@jumpstart_templates_path, "#{JumpStart::ROOT_PATH}/test/test_jumpstart_templates") - # @test_project_2b.instance_variable_set(:@default_template_name, "test_template_2") - # @test_project_2b.instance_variable_set(:@template_name, "a_name_that_does_not_exist") - # @test_project_2b.instance_variable_set(:@template_path, "#{JumpStart::ROOT_PATH}/test/test_jumpstart_templates/test_template_2") - # input = StringIO.new("yo\n") - # output = StringIO.new - # @test_project_2b.input = input - # @test_project_2b.output = output - # @test_project_2b.set_config_file_options - # assert_equal "jumpstart_options", @test_project_2b.instance_eval {set_config_file_options; __callee__} - # assert_equal "s", output.puts - # end + should "load the jumpstart menu if the specified yaml config file does not exist" do + FileUtils.delete_dir_contents("#{JumpStart::ROOT_PATH}/test/destination_dir") + @test_project_2b = JumpStart::Base.new(["test_jumpstart_project"]) + @test_project_2b.instance_variable_set(:@jumpstart_templates_path, "#{JumpStart::ROOT_PATH}/test/test_jumpstart_templates") + @test_project_2b.instance_variable_set(:@default_template_name, "test_template_2") + @test_project_2b.instance_variable_set(:@template_name, "a_name_that_does_not_exist") + @test_project_2b.instance_variable_set(:@template_path, "#{JumpStart::ROOT_PATH}/test/test_jumpstart_templates/test_template_2") + stub(@test_project_2b).jumpstart_menu + @test_project_2b.set_config_file_options + assert_received(@test_project_2b) {|x| x.jumpstart_menu} + end end
added rr mocking framework for tests and wrote another test for JumpStart::Base#set_config_file_options
i0n_jumpstart
train
9d21b03f68e471d43c0222db667ee2b4b4329634
diff --git a/tango/test_context.py b/tango/test_context.py index <HASH>..<HASH> 100644 --- a/tango/test_context.py +++ b/tango/test_context.py @@ -374,10 +374,12 @@ class DeviceTestContext(MultiDeviceTestContext): self.device_name = device_name self.device = self.server = None - def get_device_access(self): + def get_device_access(self, device_name=None): """Return the full device name.""" + if device_name is None: + device_name = self.device_name return super(DeviceTestContext, self).get_device_access( - self.device_name) + device_name) def connect(self): super(DeviceTestContext, self).connect()
Add extra argument to DeviceTestContext.get_device_access DeviceTestContext.get_device_access interfere with the MultiDeviceTestContext.get_device_access (base class) method. They both should have a common API. Even if it does not have too much sense to pass a device_name in DeviceTestContext.get_device_access do it to avoid problems.
tango-controls_pytango
train
4de34363169526e0fd2b30f639c2d6cb4b19ea8e
diff --git a/lib/broker-agent.js b/lib/broker-agent.js index <HASH>..<HASH> 100755 --- a/lib/broker-agent.js +++ b/lib/broker-agent.js @@ -22,28 +22,31 @@ function BrokerAgent(client, responseTopic) { this.requests = {}; var self = this; - this.client.createReceiver(this.replyTo, function(err, message) { - if (!!err) { - return Object.keys(self.requests).forEach(function(request) { - self.requests[request](err); + this.client.createReceiver(this.replyTo) + .then(function(receiver) { + receiver.on('message', function(message) { + var correlationId = message.properties.correlationId; + if (correlationId === undefined || correlationId === null) { + debug('message lacks correlation-id'); + return; + } + + if (!self.requests.hasOwnProperty(correlationId)) { + debug('invalid correlation-id'); + return; + } + + // complete request + self.requests[correlationId](null, message); + delete self.requests[correlationId]; }); - } - - var correlationId = message.properties.correlationId; - if (correlationId === undefined || correlationId === null) { - debug('message lacks correlation-id'); - return; - } - - if (!self.requests.hasOwnProperty(correlationId)) { - debug('invalid correlation-id'); - return; - } - // complete request - self.requests[correlationId](null, message); - delete self.requests[correlationId]; - }); + receiver.on('error', function(err) { + return Object.keys(self.requests).forEach(function(request) { + self.requests[request](err); + }); + }); + }); } BrokerAgent.prototype._sendRequest = function(opcode, content) {
refactor(BrokerAgent): use new createReceiver semantics
mbroadst_node-qmf2
train
0c2ee91bbef8339b80be759ade565319b2a28513
diff --git a/DataFixtures/LoadRequiredData.php b/DataFixtures/LoadRequiredData.php index <HASH>..<HASH> 100644 --- a/DataFixtures/LoadRequiredData.php +++ b/DataFixtures/LoadRequiredData.php @@ -59,6 +59,20 @@ class LoadRequiredData extends AbstractFixture implements ContainerAwareInterfac $adminMessageOt->setType(0); $adminMessageOt->setVisibleInDesktop(true); $om->persist($adminMessageOt); + $userRepo = $om->getRepository('ClarolineCoreBundle:User'); + $users = $userRepo->findAllEnabledUsers(); + + foreach ($users as $user) { + $messageOt = new OrderedTool(); + $messageOt->setName('message'); + $messageOt->setTool($messageTool); + $messageOt->setUser($user); + $messageOt->setLocked(false); + $messageOt->setOrder(1); + $messageOt->setType(0); + $messageOt->setVisibleInDesktop(true); + $om->persist($messageOt); + } } else { $messageTool->setPlugin($messagePlugin); $om->persist($messageTool);
[MessageBundle] Display message tool for every users at plugin installation
claroline_Distribution
train
4ace9868407c6eefea6834b399982206dc947ecd
diff --git a/packages/mangojuice-core/src/Process.js b/packages/mangojuice-core/src/Process.js index <HASH>..<HASH> 100644 --- a/packages/mangojuice-core/src/Process.js +++ b/packages/mangojuice-core/src/Process.js @@ -265,7 +265,7 @@ export class Process { emit(event, arg) { const handlers = this.eventHandlers && this.eventHandlers[event]; - maybeForEach(handlers, handler => handler(arg)); + return maybeMap(handlers, handler => handler(arg)); } mapChildren(model, iterator, iterKeys) { @@ -379,8 +379,8 @@ export class Process { // Run subscriptions if model updated if (modelUpdated) { this.logger.onEmitSubscriptions(cmd, this.model); - this.emit(MODEL_UPDATED_EVENT, cmd); - this.rootProc.emit(CHILD_MODEL_UPDATED_EVENT, cmd); + resPromise.add(this.emit(MODEL_UPDATED_EVENT, cmd)); + resPromise.add(this.rootProc.emit(CHILD_MODEL_UPDATED_EVENT, cmd)); } this.logger.onEndExec(cmd, this.model);
add subscribe handler commands to result promise of cmd exec
mangojuicejs_mangojuice
train
f3e3be617728daaac3e2885bcaced7033a394c2c
diff --git a/spyder/widgets/mixins.py b/spyder/widgets/mixins.py index <HASH>..<HASH> 100644 --- a/spyder/widgets/mixins.py +++ b/spyder/widgets/mixins.py @@ -477,6 +477,8 @@ class BaseEditMixin(object): findflag = QTextDocument.FindFlag() if not forward: findflag = findflag | QTextDocument.FindBackward + if case: + findflag = findflag | QTextDocument.FindCaseSensitively moves = [QTextCursor.NoMove] if forward: moves += [QTextCursor.NextWord, QTextCursor.Start]
Adds a flag to use case sensitive search/replace.
spyder-ide_spyder
train
ee8ae0e147897349a43445fce7cc6abe081bb996
diff --git a/charmhelpers/contrib/openstack/neutron.py b/charmhelpers/contrib/openstack/neutron.py index <HASH>..<HASH> 100644 --- a/charmhelpers/contrib/openstack/neutron.py +++ b/charmhelpers/contrib/openstack/neutron.py @@ -50,7 +50,7 @@ def determine_dkms_package(): if kernel_version() >= (3, 13): return [] else: - return ['openvswitch-datapath-dkms'] + return [headers_package(), 'openvswitch-datapath-dkms'] # legacy @@ -70,7 +70,7 @@ def quantum_plugins(): relation_prefix='neutron', ssl_dir=QUANTUM_CONF_DIR)], 'services': ['quantum-plugin-openvswitch-agent'], - 'packages': [[headers_package()] + determine_dkms_package(), + 'packages': [determine_dkms_package(), ['quantum-plugin-openvswitch-agent']], 'server_packages': ['quantum-server', 'quantum-plugin-openvswitch'], @@ -111,7 +111,7 @@ def neutron_plugins(): relation_prefix='neutron', ssl_dir=NEUTRON_CONF_DIR)], 'services': ['neutron-plugin-openvswitch-agent'], - 'packages': [[headers_package()] + determine_dkms_package(), + 'packages': [determine_dkms_package(), ['neutron-plugin-openvswitch-agent']], 'server_packages': ['neutron-server', 'neutron-plugin-openvswitch'], @@ -155,7 +155,7 @@ def neutron_plugins(): relation_prefix='neutron', ssl_dir=NEUTRON_CONF_DIR)], 'services': [], - 'packages': [[headers_package()] + determine_dkms_package(), + 'packages': [determine_dkms_package(), ['neutron-plugin-cisco']], 'server_packages': ['neutron-server', 'neutron-plugin-cisco'], @@ -174,7 +174,7 @@ def neutron_plugins(): 'neutron-dhcp-agent', 'nova-api-metadata', 'etcd'], - 'packages': [[headers_package()] + determine_dkms_package(), + 'packages': [determine_dkms_package(), ['calico-compute', 'bird', 'neutron-dhcp-agent', @@ -219,7 +219,7 @@ def neutron_plugins(): relation_prefix='neutron', ssl_dir=NEUTRON_CONF_DIR)], 'services': [], - 'packages': [[headers_package()] + determine_dkms_package()], + 'packages': [determine_dkms_package()], 'server_packages': ['neutron-server', 'python-neutron-plugin-midonet'], 'server_services': ['neutron-server'] diff --git a/tests/contrib/openstack/test_neutron_utils.py b/tests/contrib/openstack/test_neutron_utils.py index <HASH>..<HASH> 100644 --- a/tests/contrib/openstack/test_neutron_utils.py +++ b/tests/contrib/openstack/test_neutron_utils.py @@ -34,9 +34,11 @@ class NeutronTests(unittest.TestCase): @patch.object(neutron, 'kernel_version') def test_determine_dkms_package_old_kernel(self, _kernel_version): + self.check_output.return_value = b'3.4.0-19-generic' _kernel_version.return_value = (3, 10) dkms_package = neutron.determine_dkms_package() - self.assertEquals(dkms_package, ['openvswitch-datapath-dkms']) + self.assertEquals(dkms_package, ['linux-headers-3.4.0-19-generic', + 'openvswitch-datapath-dkms']) @patch.object(neutron, 'kernel_version') def test_determine_dkms_package_new_kernel(self, _kernel_version):
Tie install of headers package directly to use of DKMS packages for OVS
juju_charm-helpers
train
206541a12cac8827c5c05a268c35bf7362f09fed
diff --git a/backup/moodle2/backup_xml_transformer.class.php b/backup/moodle2/backup_xml_transformer.class.php index <HASH>..<HASH> 100644 --- a/backup/moodle2/backup_xml_transformer.class.php +++ b/backup/moodle2/backup_xml_transformer.class.php @@ -159,7 +159,7 @@ class backup_xml_transformer extends xml_contenttransformer { // Add the module ones. Each module supporting moodle2 backups MUST have it $mods = core_component::get_plugin_list('mod'); foreach ($mods as $mod => $moddir) { - if (plugin_supports('mod', $mod, FEATURE_BACKUP_MOODLE2)) { + if (plugin_supports('mod', $mod, FEATURE_BACKUP_MOODLE2) && class_exists('backup_' . $mod . '_activity_task')) { $encoders['backup_' . $mod . '_activity_task'] = 'encode_content_links'; } }
MDL-<I> core_backup: Add class_exists check for backup_<mod>_activity_task
moodle_moodle
train
5ac9f77a65f69e951dcc2dd48c5a0d1fb9ef8157
diff --git a/kie-internal/src/main/java/org/kie/internal/query/AbstractQueryBuilderImpl.java b/kie-internal/src/main/java/org/kie/internal/query/AbstractQueryBuilderImpl.java index <HASH>..<HASH> 100644 --- a/kie-internal/src/main/java/org/kie/internal/query/AbstractQueryBuilderImpl.java +++ b/kie-internal/src/main/java/org/kie/internal/query/AbstractQueryBuilderImpl.java @@ -5,6 +5,9 @@ import org.kie.internal.query.data.QueryData; public abstract class AbstractQueryBuilderImpl<T> { protected QueryData queryData = new QueryData(); + { + queryData.getQueryContext().setCount(0); + } public QueryData getQueryData() { return queryData;
BZ-<I> - Paging does not work for REST query operations (cherry picked from commit <I>b1dfa<I>a<I>f<I>f6b<I>f<I>d)
kiegroup_droolsjbpm-knowledge
train
c288c76ce9bf990ef1919230bf858504b112f745
diff --git a/common/configtx/template.go b/common/configtx/template.go index <HASH>..<HASH> 100644 --- a/common/configtx/template.go +++ b/common/configtx/template.go @@ -1,5 +1,5 @@ /* -Copyright IBM Corp. 2016 All Rights Reserved. +Copyright IBM Corp. 2017 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/common/configtx/template_test.go b/common/configtx/template_test.go index <HASH>..<HASH> 100644 --- a/common/configtx/template_test.go +++ b/common/configtx/template_test.go @@ -1,5 +1,5 @@ /* -Copyright IBM Corp. 2016 All Rights Reserved. +Copyright IBM Corp. 2017 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/common/configtx/test/helper.go b/common/configtx/test/helper.go index <HASH>..<HASH> 100644 --- a/common/configtx/test/helper.go +++ b/common/configtx/test/helper.go @@ -1,5 +1,5 @@ /* -Copyright IBM Corp. 2016 All Rights Reserved. +Copyright IBM Corp. 2017 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/common/genesis/genesis.go b/common/genesis/genesis.go index <HASH>..<HASH> 100644 --- a/common/genesis/genesis.go +++ b/common/genesis/genesis.go @@ -1,5 +1,5 @@ /* -Copyright IBM Corp. 2016 All Rights Reserved. +Copyright IBM Corp. 2017 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/common/genesis/genesis_test.go b/common/genesis/genesis_test.go index <HASH>..<HASH> 100644 --- a/common/genesis/genesis_test.go +++ b/common/genesis/genesis_test.go @@ -1,5 +1,5 @@ /* -Copyright IBM Corp. 2016 All Rights Reserved. +Copyright IBM Corp. 2017 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/orderer/tools/configtemplate/main.go b/orderer/tools/configtemplate/main.go index <HASH>..<HASH> 100644 --- a/orderer/tools/configtemplate/main.go +++ b/orderer/tools/configtemplate/main.go @@ -1,5 +1,5 @@ /* -Copyright IBM Corp. 2016 All Rights Reserved. +Copyright IBM Corp. 2017 All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
Fix copyright in CR series This CR fixes the copyright date on some new files introduced in the following changesets. <URL>
hyperledger_fabric
train
58794d1e75105639dc7bfbd87d172adcbfcddccd
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -19,22 +19,19 @@ EE.prototype.listeners = function (type) { EE.prototype.emit = function (type, args) { var i = 0 , byType = this.listeners(type) - , star - , withType - - for (i = 0; i < byType.length; i++) { - byType[i].apply(this, args) - } - + , star = this.listeners('*') + , withType = [type].concat(args) if (type !== '*') { - star = this.listeners('*') - withType = [type].concat(args) - for (i = 0; i < star.length; i++) { - star[i].apply(this, withType) + for (i = 0; i < byType.length; i++) { + byType[i].apply(this, args) } } + for (i = 0; i < star.length; i++) { + star[i].apply(this, withType) + } + this.par.emit(type, args) return this diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nee", - "version": "1.0.0", + "version": "1.1.0", "description": "Novel Event Emitter.", "main": "index.js", "scripts": { diff --git a/test.js b/test.js index <HASH>..<HASH> 100644 --- a/test.js +++ b/test.js @@ -75,14 +75,14 @@ test('wildcard', function (t) { function testWild (ee, name) { var total = 0 - , expected = 3 + , expected = 4 + , expectedPaths = [ 'foo', 'foo', 'bar', '*' ] - t.test(name, function (t) { - - t.plan(2) + t.test('wild ' + name, function (t) { // glob - ee.on('*', function (a, b) { + ee.on('*', function (path, a) { + t.equal(path, expectedPaths[total], 'Fired with path ' + path) total += 1 if (total >= expected) t.equal(total, expected, 'Correct number of "*" calls') }) @@ -96,6 +96,9 @@ test('wildcard', function (t) { ee.emit('foo', [2]) .emit('bar', [1, 2]) + .emit('*', [1, 2]) + + t.end() }) }
More consistent behavior when emitting '*'
nrn_nee
train
a99624bcf8520a917f4dbf3baf813201eede95f0
diff --git a/collatex-tools/src/main/java/eu/interedition/collatex/http/CollateResource.java b/collatex-tools/src/main/java/eu/interedition/collatex/http/CollateResource.java index <HASH>..<HASH> 100644 --- a/collatex-tools/src/main/java/eu/interedition/collatex/http/CollateResource.java +++ b/collatex-tools/src/main/java/eu/interedition/collatex/http/CollateResource.java @@ -42,7 +42,6 @@ import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -82,7 +81,7 @@ public class CollateResource { } @GET - public Response index(@Context Request request, @Context UriInfo uriInfo) throws IOException { + public Response index(@Context Request request) throws IOException { return stream(request, "index.html"); } @@ -95,8 +94,8 @@ public class CollateResource { @Path("collate") @GET - public Response redirectToIndex(@Context HttpHeaders hh, @Context UriInfo uriInfo) throws NoSuchMethodException { - return corsSupport(hh, Response.seeOther(uriInfo.getBaseUriBuilder().path("/").build())).build(); + public Response redirectToIndex(@Context HttpHeaders hh) throws NoSuchMethodException { + return corsSupport(hh, Response.noContent()).build(); } @Path("collate")
HTTP Service: remove redirects (defunct in proxy setting)
interedition_collatex
train
a216565a2358b15b20fabf13f1f0a308f228fdcf
diff --git a/kaybee/__init__.py b/kaybee/__init__.py index <HASH>..<HASH> 100644 --- a/kaybee/__init__.py +++ b/kaybee/__init__.py @@ -19,6 +19,12 @@ def setup(app: Sphinx): kb, sphinx_app, env, docname) ) + app.connect('env-before-read-docs', + lambda sphinx_app, env, + docnames: EventAction.call_env_before_read_docs( + kb, sphinx_app, env, docnames) + ) + return dict( version=__version__, parallel_read_safe=False diff --git a/kaybee/plugins/events.py b/kaybee/plugins/events.py index <HASH>..<HASH> 100644 --- a/kaybee/plugins/events.py +++ b/kaybee/plugins/events.py @@ -58,26 +58,30 @@ class EventAction(dectate.Action): @classmethod def call_purge_doc(cls, kb_app, sphinx_app, env, docname): - """ On env-purge-doc, commit registry and do callbacks """ + """ On env-purge-doc, do callbacks """ for callback in EventAction.get_callbacks(kb_app, 'env-purge-doc'): callback(kb_app, sphinx_app, env, docname) - # @classmethod - # def call_env_before_read_docs(app, env, docnames): - # """ On env-read-docs, commit registry and do callbacks""" - # - # if not hasattr(env, 'site'): - # config = getattr(app.config, 'kaybee_config') - # if config: - # env.site = Site(config) - # - # template_bridge = app.builder.templates - # - # # Add _templates in the conf directory - # confdir = os.path.join(app.confdir, '_templates') - # template_bridge.loaders.append(SphinxFileSystemLoader(confdir)) - # - # for callback in EventAction.get_callbacks(kb, 'env-before-read-docs'): - # callback(kb, app, env, docnames) - # + @classmethod + def call_env_before_read_docs(cls, kb_app, sphinx_app, env, docnames): + """ On env-read-docs, do callbacks""" + + for callback in EventAction.get_callbacks(kb_app, + 'env-before-read-docs'): + callback(kb_app, sphinx_app, env, docnames) + + # if not hasattr(env, 'site'): + # config = getattr(app.config, 'kaybee_config') + # if config: + # env.site = Site(config) + # + # template_bridge = app.builder.templates + # + # # Add _templates in the conf directory + # confdir = os.path.join(app.confdir, '_templates') + # template_bridge.loaders.append(SphinxFileSystemLoader(confdir)) + # + # for callback in EventAction.get_callbacks(kb, + # 'env-before-read-docs'): + # callback(kb, app, env, docnames) diff --git a/tests/unit/plugins/test_plugin_events.py b/tests/unit/plugins/test_plugin_events.py index <HASH>..<HASH> 100644 --- a/tests/unit/plugins/test_plugin_events.py +++ b/tests/unit/plugins/test_plugin_events.py @@ -32,6 +32,15 @@ def purgedoc_event(kb_app): yield handle_purgedoc +@pytest.fixture() +def before_read_docs_event(kb_app): + @kb_app.event('env-before-read-docs', 'somescope') + def handle_beforereaddocs(kb_app, sphinx_app, env, docnames): + sphinx_app['flag'] = 765 + + yield handle_beforereaddocs + + class TestPluginEvents: def test_import(self): assert 'EventAction' == EventAction.__name__ @@ -82,3 +91,15 @@ class TestPluginEvents: 'env-purge-doc') assert 'handle_purgedoc' == callbacks[0].__name__ assert 876 == sphinx_app['flag'] + + def test_before_read_docs(self, kb_app, before_read_docs_event): + dectate.commit(kb_app) + sphinx_app = dict() + env = dict() + docnames = [] + EventAction.call_env_before_read_docs(kb_app, sphinx_app, env, + docnames) + callbacks = EventAction.get_callbacks(kb_app, + 'env-before-read-docs') + assert 'handle_beforereaddocs' == callbacks[0].__name__ + assert 765 == sphinx_app['flag']
new: dev: implement Sphinx env-before-read-docs event dispatcher.
pauleveritt_kaybee
train
22b00f7f6fa29fb52541d206462431258b769397
diff --git a/go/vt/topo/topoproto/tablet.go b/go/vt/topo/topoproto/tablet.go index <HASH>..<HASH> 100644 --- a/go/vt/topo/topoproto/tablet.go +++ b/go/vt/topo/topoproto/tablet.go @@ -155,6 +155,19 @@ func ParseTabletType(param string) (topodatapb.TabletType, error) { return topodatapb.TabletType(value), nil } +// ParseTabletTypes parses the tablet type into the enum +func ParseTabletTypes(param string) ([]topodatapb.TabletType, error) { + var sourceTabletTypes []topodatapb.TabletType + for _, typeStr := range strings.Split(param, ",") { + t, err := ParseTabletType(typeStr) + if err != nil { + return nil, fmt.Errorf("unknown tablet type: %v", typeStr) + } + sourceTabletTypes = append(sourceTabletTypes, t) + } + return sourceTabletTypes, nil +} + // TabletTypeLString returns a lower case version of the tablet type, // or "unknown" if not known. func TabletTypeLString(tabletType topodatapb.TabletType) string { diff --git a/go/vt/vttablet/tabletmanager/binlog_players.go b/go/vt/vttablet/tabletmanager/binlog_players.go index <HASH>..<HASH> 100644 --- a/go/vt/vttablet/tabletmanager/binlog_players.go +++ b/go/vt/vttablet/tabletmanager/binlog_players.go @@ -312,14 +312,14 @@ func (bpc *BinlogPlayerController) Iteration() (err error) { return fmt.Errorf("not starting because flag '%v' is set", binlogplayer.BlpFlagDontStart) } - sourceTabletType, err := topoproto.ParseTabletType(*sourceTabletTypeStr) + sourceTabletTypes, err := topoproto.ParseTabletTypes(*sourceTabletTypeStr) if err != nil { - return fmt.Errorf("unknown tablet type: %v", *sourceTabletTypeStr) + log.Fatalf("unknown tablet type: %v", *sourceTabletTypeStr) } - // wait for the tablet set (usefull for the first run at least, fast for next runs) - if err := bpc.tabletStatsCache.WaitForTablets(bpc.ctx, bpc.cell, bpc.sourceShard.Keyspace, bpc.sourceShard.Shard, []topodatapb.TabletType{sourceTabletType}); err != nil { - return fmt.Errorf("error waiting for tablets for %v %v %v: %v", bpc.cell, bpc.sourceShard.String(), sourceTabletType, err) + // wait for the tablet set (useful for the first run at least, fast for next runs) + if err := bpc.tabletStatsCache.WaitForTablets(bpc.ctx, bpc.cell, bpc.sourceShard.Keyspace, bpc.sourceShard.Shard, sourceTabletTypes); err != nil { + return fmt.Errorf("error waiting for tablets for %v %v %v: %v", bpc.cell, bpc.sourceShard.String(), sourceTabletTypes, err) } // Find the server list from the health check. @@ -327,9 +327,13 @@ func (bpc *BinlogPlayerController) Iteration() (err error) { // not return non-serving tablets. We must include non-serving tablets because // REPLICA source tablets may not be serving anymore because their traffic was // already migrated to the destination shards. - addrs := discovery.RemoveUnhealthyTablets(bpc.tabletStatsCache.GetTabletStats(bpc.sourceShard.Keyspace, bpc.sourceShard.Shard, sourceTabletType)) + var addrs []discovery.TabletStats + for _, sourceTabletType := range sourceTabletTypes { + typeAddrs := discovery.RemoveUnhealthyTablets(bpc.tabletStatsCache.GetTabletStats(bpc.sourceShard.Keyspace, bpc.sourceShard.Shard, sourceTabletType)) + addrs = append(addrs, typeAddrs...) + } if len(addrs) == 0 { - return fmt.Errorf("can't find any healthy source tablet for %v %v %v", bpc.cell, bpc.sourceShard.String(), sourceTabletType) + return fmt.Errorf("can't find any healthy source tablet for %v %v %v", bpc.cell, bpc.sourceShard.String(), sourceTabletTypes) } newServerIndex := rand.Intn(len(addrs)) tablet := addrs[newServerIndex].Tablet
Support multiple tablet types as binlog player source
vitessio_vitess
train
6929615c4c2a6c786d1fce09197efc5d81e72a14
diff --git a/src/test/java/org/jpmml/lightgbm/ClassificationTest.java b/src/test/java/org/jpmml/lightgbm/ClassificationTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/jpmml/lightgbm/ClassificationTest.java +++ b/src/test/java/org/jpmml/lightgbm/ClassificationTest.java @@ -82,7 +82,7 @@ public class ClassificationTest extends LightGBMTest { @Test public void evaluateRFAudit() throws Exception { - evaluate("RFClassification", "Audit"); + evaluate("RFClassification", "Audit", new RealNumberEquivalence(4)); } @Test
Fixed the build for JDK <I>
jpmml_jpmml-lightgbm
train
c96ea2a095d7a41b6aac717673a45e48dc7cbe4d
diff --git a/app/helpers/effective_datatables_helper.rb b/app/helpers/effective_datatables_helper.rb index <HASH>..<HASH> 100644 --- a/app/helpers/effective_datatables_helper.rb +++ b/app/helpers/effective_datatables_helper.rb @@ -71,7 +71,10 @@ module EffectiveDatatablesHelper end def datatables_admin_path? - (attributes[:admin_path] || request.referer.chomp('/').end_with?('/admin')) rescue false + @datatables_admin_path ||= ( + referer = request.referer.to_s.downcase.chomp('/') + '/' + (attributes[:admin_path] || referer.include?('/admin/')) rescue false + ) end # TODO: Improve on this
Fix in datatables_admin_path?
code-and-effect_effective_datatables
train
06c4745ebf90ed5f329a163dc50d27b4d34b6aab
diff --git a/branches/development/5.4.1/concrete/libraries/block_view.php b/branches/development/5.4.1/concrete/libraries/block_view.php index <HASH>..<HASH> 100644 --- a/branches/development/5.4.1/concrete/libraries/block_view.php +++ b/branches/development/5.4.1/concrete/libraries/block_view.php @@ -294,7 +294,7 @@ defined('C5_EXECUTE') or die(_("Access Denied.")); print $outputContent; } else if ($template) { - if ($view == 'view' && $this->controller->cacheBlockOutput()) { + if ($view == 'view' && $this->controller->cacheBlockOutput() && ($obj instanceof Block)) { ob_start(); }
fixing issue with output buffering and blocks and full page cache git-svn-id: <URL>
concrete5_concrete5
train
1ebf591ebeded3c49966f81b4be12208424c89fc
diff --git a/lib/dragonfly/job.rb b/lib/dragonfly/job.rb index <HASH>..<HASH> 100644 --- a/lib/dragonfly/job.rb +++ b/lib/dragonfly/job.rb @@ -368,7 +368,7 @@ module Dragonfly # Misc def store(opts={}) - app.store(result, opts.merge(:meta => meta)) + app.store(result, opts_for_store.merge(opts)) end def inspect @@ -441,6 +441,10 @@ module Dragonfly def last_step_of_type(type) steps.select{|s| s.is_a?(type) }.last end + + def opts_for_store + {:meta => meta, :mime_type => mime_type} + end end end diff --git a/spec/dragonfly/job_spec.rb b/spec/dragonfly/job_spec.rb index <HASH>..<HASH> 100644 --- a/spec/dragonfly/job_spec.rb +++ b/spec/dragonfly/job_spec.rb @@ -977,13 +977,13 @@ describe Dragonfly::Job do @app.generator.add(:test){ ["Toes", {:name => 'doogie.txt'}] } @job = @app.generate(:test) end - it "should store its data along with the meta" do + it "should store its data along with the meta and mime_type" do @job.meta[:eggs] = 'doolally' - @app.datastore.should_receive(:store).with(a_temp_object_with_data("Toes"), :meta => {:name => 'doogie.txt', :eggs => 'doolally'}) + @app.datastore.should_receive(:store).with(a_temp_object_with_data("Toes"), :mime_type => 'text/plain', :meta => {:name => 'doogie.txt', :eggs => 'doolally'}) @job.store end it "should add extra opts" do - @app.datastore.should_receive(:store).with(a_temp_object_with_data("Toes"), :meta => {:name => 'doogie.txt'}, :path => 'blah') + @app.datastore.should_receive(:store).with(a_temp_object_with_data("Toes"), :mime_type => 'text/plain', :meta => {:name => 'doogie.txt'}, :path => 'blah') @job.store(:path => 'blah') end end
Job#store now passes in the mime type as well as meta
markevans_dragonfly
train
cfc78d1cca8089a380f593086a0a87dd5226e7e7
diff --git a/spec/rubygems/doc_manager_spec.rb b/spec/rubygems/doc_manager_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rubygems/doc_manager_spec.rb +++ b/spec/rubygems/doc_manager_spec.rb @@ -1,5 +1,6 @@ require File.dirname(__FILE__) + '/../spec_helper' require File.join(YARD::ROOT, 'rubygems_plugin') +require 'fileutils' describe Gem::DocManager do before do
Require fileutils for specs
lsegal_yard
train
149f0a864030d138c6d51e2d03d49f32253886e1
diff --git a/app/assets/javascripts/admin/views/fields/attachment_field.js b/app/assets/javascripts/admin/views/fields/attachment_field.js index <HASH>..<HASH> 100644 --- a/app/assets/javascripts/admin/views/fields/attachment_field.js +++ b/app/assets/javascripts/admin/views/fields/attachment_field.js @@ -5,6 +5,7 @@ var AttachmentFieldView = Backbone.View.extend({ this.$label = this.$(".attachment-field-label"); this.$icon = this.$(".icon"); this.$preview = this.$(".attachment-field-preview"); + this.refreshLabel(); }, activateFileInput: function(event) {
Render the attachment label on init
Threespot_tolaria
train
241ea7707b57510d2f09c831b1c743bdb448e892
diff --git a/gate/gate.py b/gate/gate.py index <HASH>..<HASH> 100644 --- a/gate/gate.py +++ b/gate/gate.py @@ -129,7 +129,7 @@ class Factory(): def generate_tex_file(self): self.tex_content = """\documentclass{article} \usepackage{circuitikz} -\usepackage[width=122mm,left=12mm,paperwidth=1000mm,height=1000mm,top=12mm,paperheight=1000mm]{geometry} +\usepackage[width=5000mm,left=12mm,paperwidth=5000mm,height=3000mm,top=12mm,paperheight=3000mm]{geometry} \\begin{document} \\begin{circuitikz} @@ -138,7 +138,7 @@ class Factory(): \\node (o0) at (1,0) {$O_0$}; \draw (nand1.out) -- (o0); """ - self.logic_parser(self.best,0,0,self.gate) + self.logic_parser(self.best,0,0,self.gate,self.best_depth) self.tex_content += """ \end{circuitikz} @@ -148,22 +148,21 @@ class Factory(): with open("factory.tex", "w") as tex_file: tex_file.write(self.tex_content) - def logic_parser(self,expression,x,y,gate): - print expression + def logic_parser(self,expression,x,y,gate,fix): if isinstance(expression[0], tuple): self.gate += 1 - self.tex_content += "\n\\node[nand port] at ("+ str(x-2) +","+ str(y+1) +") (nand"+ str(self.gate) +") {$g"+ str(self.gate) +"$};" + self.tex_content += "\n\\node[nand port] at ("+ str(x-0.5*math.sqrt(self.gate)) +","+ str(y+2+2*fix) +") (nand"+ str(self.gate) +") {$g"+ str(self.gate) +"$};" self.tex_content += "\n\draw (nand"+ str(self.gate) +".out) -- (nand"+ str(gate) +".in 1);" - self.logic_parser(expression[0],x-2,y+1,self.gate) + self.logic_parser(expression[0],x-0.5*math.sqrt(self.gate),y+2+2*fix,self.gate,fix/2) else: self.tex_content += "\n\\node (i"+ str(expression[0]) +") at ("+ str(x-2) +","+ str(y+0.3) +") {$I_{"+ str(expression[0]) +"}$};" self.tex_content += "\n\draw (i"+ str(expression[0]) +") -- (nand"+ str(gate) +".in 1);" if isinstance(expression[1], tuple): self.gate += 1 - self.tex_content += "\n\\node[nand port] at ("+ str(x-2) +","+ str(y-1) +") (nand"+ str(self.gate) +") {$g"+ str(self.gate) +"$};" + self.tex_content += "\n\\node[nand port] at ("+ str(x-0.5*math.sqrt(self.gate)) +","+ str(y-2-2*fix) +") (nand"+ str(self.gate) +") {$g"+ str(self.gate) +"$};" self.tex_content += "\n\draw (nand"+ str(self.gate) +".out) -- (nand"+ str(gate) +".in 2);" - self.logic_parser(expression[1],x-2,y-1,self.gate) + self.logic_parser(expression[1],x-0.5*math.sqrt(self.gate),y-2-2*fix,self.gate,fix/2) else: self.tex_content += "\n\\node (i"+ str(expression[1]) +") at ("+ str(x-2) +","+ str(y-0.3) +") {$I_{"+ str(expression[1]) +"}$};" self.tex_content += "\n\draw (i"+ str(expression[1]) +") -- (nand"+ str(gate) +".in 2);"
Reduce the number of overlapping logic gates in the TeX output
mertyildiran_GateFactory
train
863478a8cff8d9642607381274bf9f1fff569788
diff --git a/lib/turtle.io.js b/lib/turtle.io.js index <HASH>..<HASH> 100644 --- a/lib/turtle.io.js +++ b/lib/turtle.io.js @@ -1460,15 +1460,20 @@ TurtleIO.prototype.start = function ( config, err ) { }); // Starting server - if ( config.ssl.cert !== null && config.ssl.key !== null ) { - self.server = https.createServer( $.merge( config.ssl, {port: config.port, host: config.ip} ), function ( req, res ) { - self.route( req, res ); - } ).listen( config.port, config.ip ); + if ( self.server === null ) { + if ( config.ssl.cert !== null && config.ssl.key !== null ) { + self.server = https.createServer( $.merge( config.ssl, {port: config.port, host: config.ip} ), function ( req, res ) { + self.route( req, res ); + } ).listen( config.port, config.ip ); + } + else { + self.server = http.createServer( function ( req, res ) { + self.route( req, res ); + } ).listen( config.port, config.ip ); + } } else { - self.server = http.createServer( function ( req, res ) { - self.route( req, res ); - } ).listen( config.port, config.ip ); + self.server.listen( config.port, config.ip ); } console.log( "Started turtle.io on port " + config.port ); @@ -1524,10 +1529,13 @@ TurtleIO.prototype.stop = function () { this.handlers = {all: {regex: [], routes: [], hosts: {}}, "delete": {regex: [], routes: [], hosts: {}}, get: {regex: [], routes: [], hosts: {}}, patch: {regex: [], routes: [], hosts: {}}, post: {regex: [], routes: [], hosts: {}}, put: {regex: [], routes: [], hosts: {}}}; this.pages = {all: {}}; this.sessions = {}; - this.server = null; this.vhosts = []; this.watching = {}; + if ( this.server !== null ) { + this.server.close(); + } + console.log( "Stopped turtle.io on port " + port ); return this; diff --git a/src/start.js b/src/start.js index <HASH>..<HASH> 100644 --- a/src/start.js +++ b/src/start.js @@ -63,15 +63,20 @@ TurtleIO.prototype.start = function ( config, err ) { }); // Starting server - if ( config.ssl.cert !== null && config.ssl.key !== null ) { - self.server = https.createServer( $.merge( config.ssl, {port: config.port, host: config.ip} ), function ( req, res ) { - self.route( req, res ); - } ).listen( config.port, config.ip ); + if ( self.server === null ) { + if ( config.ssl.cert !== null && config.ssl.key !== null ) { + self.server = https.createServer( $.merge( config.ssl, {port: config.port, host: config.ip} ), function ( req, res ) { + self.route( req, res ); + } ).listen( config.port, config.ip ); + } + else { + self.server = http.createServer( function ( req, res ) { + self.route( req, res ); + } ).listen( config.port, config.ip ); + } } else { - self.server = http.createServer( function ( req, res ) { - self.route( req, res ); - } ).listen( config.port, config.ip ); + self.server.listen( config.port, config.ip ); } console.log( "Started turtle.io on port " + config.port ); diff --git a/src/stop.js b/src/stop.js index <HASH>..<HASH> 100644 --- a/src/stop.js +++ b/src/stop.js @@ -12,10 +12,13 @@ TurtleIO.prototype.stop = function () { this.handlers = {all: {regex: [], routes: [], hosts: {}}, "delete": {regex: [], routes: [], hosts: {}}, get: {regex: [], routes: [], hosts: {}}, patch: {regex: [], routes: [], hosts: {}}, post: {regex: [], routes: [], hosts: {}}, put: {regex: [], routes: [], hosts: {}}}; this.pages = {all: {}}; this.sessions = {}; - this.server = null; this.vhosts = []; this.watching = {}; + if ( this.server !== null ) { + this.server.close(); + } + console.log( "Stopped turtle.io on port " + port ); return this;
Fixing start/stop/restart tests
avoidwork_turtle.io
train
d4336d82b7f4d2906fcdb833acb727c70f11c279
diff --git a/lib/core/util.js b/lib/core/util.js index <HASH>..<HASH> 100644 --- a/lib/core/util.js +++ b/lib/core/util.js @@ -47,12 +47,13 @@ function destroy (stream, err) { } } +const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)s/ function parseKeepAliveTimeout (headers) { for (let n = 0; n < headers.length; n += 2) { const key = headers[n + 0] if (key.length === 10 && key.toLowerCase() === 'keep-alive') { - const timeout = parseInt(headers[n + 1].split('timeout=', 2)[1]) - return timeout ? timeout * 1000 : undefined + const m = headers[n + 1].match(KEEPALIVE_TIMEOUT_EXPR) + return m ? parseInt(m[1]) * 1000 : null } } }
perf: parseKeepAliveTimeout The regex version is fastest.
mcollina_undici
train
b01b54996b78f16b6862301c7a2fae64c4fa2953
diff --git a/lib/Pagon/App.php b/lib/Pagon/App.php index <HASH>..<HASH> 100644 --- a/lib/Pagon/App.php +++ b/lib/Pagon/App.php @@ -819,11 +819,11 @@ class App extends EventEmitter } if ($route && !$route instanceof \Exception) { - $this->router->set('?' . $type, $route); + $this->router->set('_' . $type, $route); } else { ob_get_level() && ob_clean(); ob_start(); - if (!$this->router->handle('?' . $type, array($route))) { + if (!$this->router->handle('_' . $type, array($route))) { echo $this->injectors['errors'][$type][1]; } $this->halt($this->injectors['errors'][$type][0], ob_get_clean());
Change error route prefix from unicode char to "_"
hfcorriez_pagon
train
2d335a16f795baad69a12a3e6df4fdee1c02fe8d
diff --git a/version/version.go b/version/version.go index <HASH>..<HASH> 100644 --- a/version/version.go +++ b/version/version.go @@ -14,7 +14,7 @@ const Version = "1.5.0" // A pre-release marker for the version. If this is "" (empty string) // then it means that it is a final release. Otherwise, this is a pre-release // such as "dev" (in development), "beta", "rc1", etc. -const VersionPrerelease = "dev" +const VersionPrerelease = "" func FormattedVersion() string { var versionString bytes.Buffer diff --git a/website/config.rb b/website/config.rb index <HASH>..<HASH> 100644 --- a/website/config.rb +++ b/website/config.rb @@ -2,7 +2,7 @@ set :base_url, "https://www.packer.io/" activate :hashicorp do |h| h.name = "packer" - h.version = "1.4.5" + h.version = "1.5.0" h.github_slug = "hashicorp/packer" h.website_root = "website" end
cut packer release <I>
hashicorp_packer
train
1c0ccc4c43c0e92e09939be0e04c8f284ff4d942
diff --git a/packages/neos-ui-editors/src/EditorEnvelope/index.js b/packages/neos-ui-editors/src/EditorEnvelope/index.js index <HASH>..<HASH> 100644 --- a/packages/neos-ui-editors/src/EditorEnvelope/index.js +++ b/packages/neos-ui-editors/src/EditorEnvelope/index.js @@ -136,7 +136,7 @@ export default class EditorEnvelope extends PureComponent { return ( <Tooltip renderInline className={style.envelope__helpmessage}> - {helpMessage ? <ReactMarkdown source={translatedHelpMessage} /> : ''} + {helpMessage ? <ReactMarkdown source={translatedHelpMessage} linkTarget="_blank" /> : ''} {helpThumbnail ? <img alt={label} src={helpThumbnailSrc} className={style.envelope__helpThumbnail} /> : ''} </Tooltip> ); diff --git a/packages/neos-ui/src/Containers/Modals/SelectNodeType/nodeTypeGroupPanel.js b/packages/neos-ui/src/Containers/Modals/SelectNodeType/nodeTypeGroupPanel.js index <HASH>..<HASH> 100644 --- a/packages/neos-ui/src/Containers/Modals/SelectNodeType/nodeTypeGroupPanel.js +++ b/packages/neos-ui/src/Containers/Modals/SelectNodeType/nodeTypeGroupPanel.js @@ -98,7 +98,7 @@ class NodeTypeGroupPanel extends PureComponent { <I18n id={label} fallback={label}/> </span> {thumbnail ? <img alt={label} src={thumbnail} className={style.helpThumbnail} /> : ''} - <ReactMarkdown source={message} /> + <ReactMarkdown source={message} linkTarget="_blank" /> </div> <IconButton className={style.helpMessage__closeButton} icon="times" onClick={onCloseHelpMessage} />
BUGFIX: Open links in new window (#<I>)
neos_neos-ui
train
454822ef34d378a640937cdb4b6cb088b1c42842
diff --git a/packages/wpcom.js/lib/site.plugin.js b/packages/wpcom.js/lib/site.plugin.js index <HASH>..<HASH> 100644 --- a/packages/wpcom.js/lib/site.plugin.js +++ b/packages/wpcom.js/lib/site.plugin.js @@ -42,25 +42,25 @@ class SitePlugin { } /** - * config the plugin + * Update the plugin configuration * * @param {Object} [query] - query object parameter - * @param {Object} config - plugin config object + * @param {Object} body - plugin body object * @param {Function} [fn] - callback function * @return {Promise} Promise */ - config( query, config, fn ) { - return this.wpcom.req.put( this.pluginPath, query, config, fn ); + update( query, body, fn ) { + return this.wpcom.req.put( this.pluginPath, query, body, fn ); }; /** - * Update the plugin + * Update the plugin version * * @param {Object} [query] - query object parameter * @param {Function} [fn] - callback function * @return {Promise} Promise */ - update( query, fn ) { + updateVersion( query, fn ) { return this.wpcom.req.put( `${ this.pluginPath }/update`, query, fn ); }; @@ -88,50 +88,50 @@ class SitePlugin { /** * Activate the plugin - * This method is a shorthand of config() + * This method is a shorthand of update() * * @param {Object} [query] - query object parameter * @param {Function} [fn] - callback function * @return {Promise} Promise */ activate( query, fn ) { - return this.config( query, { active: true }, fn ); + return this.update( query, { active: true }, fn ); }; /** * Deactivate the plugin - * This method is a shorthand of config() + * This method is a shorthand of update() * * @param {Object} [query] - query object parameter * @param {Function} [fn] - callback function * @return {Promise} Promise */ deactivate( query, fn ) { - return this.config( query, { active: false }, fn ); + return this.update( query, { active: false }, fn ); } /** * Enable plugin autoupdate - * This method is a shorthand of config() + * This method is a shorthand of update() * * @param {Object} [query] - query object parameter * @param {Function} [fn] - callback function * @return {Promise} Promise */ enableAutoupdate( query, fn ) { - return this.config( query, { autoupdate: true }, fn ); + return this.update( query, { autoupdate: true }, fn ); } /** * Disable plugin autoupdate - * This method is a shorthand of config() + * This method is a shorthand of update() * * @param {Object} [query] - query object parameter * @param {Function} [fn] - callback function * @return {Promise} Promise */ disableAutoupdate( query, fn ) { - return this.config( query, { autoupdate: false }, fn ); + return this.update( query, { autoupdate: false }, fn ); }; }
Merge pull request #<I> from Automattic/update/site.plugin SitePlugin: rename methods to be consistent.
Automattic_wp-calypso
train
d9b14cf6d53aef5ee6e45a4a6db1ff1e8513a3a6
diff --git a/src/actions/AddToCartAction.php b/src/actions/AddToCartAction.php index <HASH>..<HASH> 100644 --- a/src/actions/AddToCartAction.php +++ b/src/actions/AddToCartAction.php @@ -54,19 +54,25 @@ class AddToCartAction extends \yii\base\Action $collection->load(); } - if ($collection->validate()) { - foreach ($collection->models as $position) { - /** @var CartPositionInterface $position */ - if (!$cart->hasPosition($position->getId())) { - $cart->put($position); - Yii::$app->session->addFlash('success', Yii::t('cart', 'Item has been added to cart')); - } else { - Yii::$app->session->addFlash('warning', Yii::t('cart', 'Item is already in the cart')); + foreach ($collection->models as $position) { + /** @var CartPositionInterface $position */ + if (!$position->validate()) { + $error = $collection->getFirstError(); + if (empty($error)) { + $error = Yii::t('cart', 'Failed to add item to the cart'); } + Yii::$app->session->addFlash('warning', $error); + Yii::warning('Failed to add item to cart', 'cart'); + + continue; + } + + if (!$cart->hasPosition($position->getId())) { + $cart->put($position); + Yii::$app->session->addFlash('success', Yii::t('cart', 'Item has been added to cart')); + } else { + Yii::$app->session->addFlash('warning', Yii::t('cart', 'Item is already in the cart')); } - } else { - Yii::$app->session->addFlash('warning', Yii::t('cart', 'Failed to add item to the cart')); - Yii::warning('Failed to add item to the cart', 'cart'); } if ($request->isAjax) {
AddToCartAction updated to be able to handle both errored and ok positions
hiqdev_yii2-cart
train
d5baaf5109cd83af1f3d34676ae24c2181950782
diff --git a/js/binance.js b/js/binance.js index <HASH>..<HASH> 100644 --- a/js/binance.js +++ b/js/binance.js @@ -271,6 +271,7 @@ module.exports = class binance extends Exchange { '-1000': ExchangeNotAvailable, // {"code":-1000,"msg":"An unknown error occured while processing the request."} '-1013': InvalidOrder, // createOrder -> 'invalid quantity'/'invalid price'/MIN_NOTIONAL '-1021': InvalidNonce, // 'your time is ahead of server' + '-1022': AuthenticationError, // {"code":-1022,"msg":"Signature for this request is not valid."} '-1100': InvalidOrder, // createOrder(symbol, 1, asdf) -> 'Illegal characters found in parameter 'price' '-2010': InsufficientFunds, // createOrder -> 'Account has insufficient balance for requested action.' '-2011': OrderNotFound, // cancelOrder(1, 'BTC/USDT') -> 'UNKNOWN_ORDER'
binance added handling for AuthenticationError -<I> #<I>
ccxt_ccxt
train
67be361ab6d0767c7fba053fea54ab1addb1ac3d
diff --git a/src/rules/property-no-vendor-prefix/__tests__/index.js b/src/rules/property-no-vendor-prefix/__tests__/index.js index <HASH>..<HASH> 100644 --- a/src/rules/property-no-vendor-prefix/__tests__/index.js +++ b/src/rules/property-no-vendor-prefix/__tests__/index.js @@ -16,12 +16,41 @@ testRule(undefined, tr => { tr.ok("a { -webkit-font-smoothing: antialiased; }", "non-standard prefixed property") tr.ok("a { -webkit-touch-callout: none; }", "another non-standard prefixed property") - tr.notOk("a { -webkit-transform: scale(1); }", messages.rejected("-webkit-transform")) - tr.notOk("a { -webkit-transform: scale(1); transform: scale(1); }", messages.rejected("-webkit-transform")) - tr.notOk("a { transform: scale(1); -webkit-transform: scale(1); }", messages.rejected("-webkit-transform")) - tr.notOk("a { -moz-transition: all 3s; }", messages.rejected("-moz-transition")) - tr.notOk("a { -moz-columns: 2; }", messages.rejected("-moz-columns")) + tr.notOk("a { -webkit-transform: scale(1); }", { + message: messages.rejected("-webkit-transform"), + line: 1, + column: 5, + }) + tr.notOk("a { -webkit-transform: scale(1); transform: scale(1); }", { + message: messages.rejected("-webkit-transform"), + line: 1, + column: 5, + }) + tr.notOk("a { transform: scale(1); -webkit-transform: scale(1); }", { + message: messages.rejected("-webkit-transform"), + line: 1, + column: 26, + }) + tr.notOk("a { -moz-transition: all 3s; }", { + message: messages.rejected("-moz-transition"), + line: 1, + column: 5, + }) + tr.notOk("a { -moz-columns: 2; }", { + message: messages.rejected("-moz-columns"), + line: 1, + column: 5, + }) - tr.notOk("a { -o-columns: 2; }", messages.rejected("-o-columns"), "mistaken prefix") - tr.notOk("a { -ms-interpolation-mode: nearest-neighbor; }", messages.rejected("-ms-interpolation-mode"), "\"hack\" prefix") + tr.notOk("a { -o-columns: 2; }", { + message: messages.rejected("-o-columns"), + line: 1, + column: 5, + }, "mistaken prefix") + + tr.notOk("a { -ms-interpolation-mode: nearest-neighbor; }", { + message: messages.rejected("-ms-interpolation-mode"), + line: 1, + column: 5, + }, "\"hack\" prefix") })
Add accuracy for property-no-vendor-prefix
stylelint_stylelint
train
52a343e695d52add4a71637677b94db809806297
diff --git a/languagetool-language-modules/pl/src/test/java/org/languagetool/rules/pl/MorfologikPolishSpellerRuleTest.java b/languagetool-language-modules/pl/src/test/java/org/languagetool/rules/pl/MorfologikPolishSpellerRuleTest.java index <HASH>..<HASH> 100644 --- a/languagetool-language-modules/pl/src/test/java/org/languagetool/rules/pl/MorfologikPolishSpellerRuleTest.java +++ b/languagetool-language-modules/pl/src/test/java/org/languagetool/rules/pl/MorfologikPolishSpellerRuleTest.java @@ -52,7 +52,7 @@ public class MorfologikPolishSpellerRuleTest { assertEquals(1, matches.length); assertEquals(0, matches[0].getFromPos()); assertEquals(4, matches[0].getToPos()); - assertEquals("Zola", matches[0].getSuggestedReplacements().get(0)); + assertEquals("żółw", matches[0].getSuggestedReplacements().get(0)); assertEquals(1, rule.match(langTool.getAnalyzedSentence("aõh")).length); assertEquals(0, rule.match(langTool.getAnalyzedSentence("a")).length);
update the test - now the suggestion makes sense :)
languagetool-org_languagetool
train
e74245ae2eb774ae2f6afb405058f8e43009b7a7
diff --git a/Kwf/Benchmark/Rrd.php b/Kwf/Benchmark/Rrd.php index <HASH>..<HASH> 100644 --- a/Kwf/Benchmark/Rrd.php +++ b/Kwf/Benchmark/Rrd.php @@ -161,10 +161,17 @@ class Kwf_Benchmark_Rrd extends Kwf_Util_Rrd_File } $values = array_merge($values, array_values($cnt)); - $values[] = $memcacheStats['bytes']; - $values[] = $memcacheStats['curr_items']; - $values[] = $memcacheStats['curr_connections']; - $values[] = $memcacheStats['limit_maxbytes']; + if (Kwf_Registry::get('config')->server->memcache->host) { + $values[] = $memcacheStats['bytes']; + $values[] = $memcacheStats['curr_items']; + $values[] = $memcacheStats['curr_connections']; + $values[] = $memcacheStats['limit_maxbytes']; + } else { + $values[] = 'U'; + $values[] = 'U'; + $values[] = 'U'; + $values[] = 'U'; + } return $values; }
don't use memcache counter if host is not set
koala-framework_koala-framework
train
b98fb7db0057267d5b3487369ded5a54c15e3456
diff --git a/dev/router.js b/dev/router.js index <HASH>..<HASH> 100644 --- a/dev/router.js +++ b/dev/router.js @@ -23,6 +23,7 @@ let routes = [ component: load('test-layout/layout'), children: [ {path: 'about', component: load('test-layout/about')}, + {path: 'layout', redirect: '/test-layout/about'}, {path: 'toolbar', component: load('test-layout/toolbar')}, {path: 'tabs', component: load('test-layout/tabs')}, {path: 'drawer', component: load('test-layout/drawer')}
chore: dev server redirect Layout route to /test-layout/about
quasarframework_quasar
train