hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
4ba372d81321521d77b073e0ef787340d69b8f1c
|
diff --git a/test/unit/frontend/helpers/match.test.js b/test/unit/frontend/helpers/match.test.js
index <HASH>..<HASH> 100644
--- a/test/unit/frontend/helpers/match.test.js
+++ b/test/unit/frontend/helpers/match.test.js
@@ -148,41 +148,4 @@ describe('Match helper', function () {
shouldCompileToExpected(templateString, {title}, expected);
});
});
-
- // By using match as a block helper, instead of returning true or false, the matching template is executed
- // We've already tested all the logic of the matches, for the block helpers we only need to test that the correct template is executed
- describe('{{#match}} (block)', function () {
- it('Executes the first block when match is true', function () {
- const templateString = '{{#match title "=" "Hello World"}}case a{{else match title "=" "Hello World!"}}case b{{else}}case c{{/match}}';
- const hash = {
- title: 'Hello World'
- };
-
- const expected = 'case a';
-
- shouldCompileToExpected(templateString, hash, expected);
- });
-
- it('Executes secondary blocks correctly', function () {
- const templateString = '{{#match title "=" "Hello World"}}case a{{else match title "=" "Hello World!"}}case b{{else}}case c{{/match}}';
- const hash = {
- title: 'Hello World!'
- };
-
- const expected = 'case b';
-
- shouldCompileToExpected(templateString, hash, expected);
- });
-
- it('Executes the else block when match is false', function () {
- const templateString = '{{#match title "=" "Hello World"}}case a{{else match title "=" "Hello World!"}}case b{{else}}case c{{/match}}';
- const hash = {
- title: 'Hello'
- };
-
- const expected = 'case c';
-
- shouldCompileToExpected(templateString, hash, expected);
- });
- });
});
|
Removed accidentally duplicated tests
- this was a result of a bad rebase, these tests should only exist once in their new form
|
TryGhost_Ghost
|
train
|
aedec0fe9d06021251b8ef480126b4fb322b14e3
|
diff --git a/lib/pdk/cli/util.rb b/lib/pdk/cli/util.rb
index <HASH>..<HASH> 100644
--- a/lib/pdk/cli/util.rb
+++ b/lib/pdk/cli/util.rb
@@ -21,6 +21,23 @@ module PDK
{}
end
module_function :spinner_opts_for_platform
+
+ def prompt_for_yes(question_text, opts = {})
+ prompt = opts[:prompt] || TTY::Prompt.new(help_color: :cyan)
+ validator = proc { |value| [true, false].include?(value) || value =~ %r{\A(?:yes|y|no|n)\Z}i }
+ response = nil
+
+ begin
+ response = prompt.yes?(question_text) do |q|
+ q.validate(validator, _('Answer "Y" to continue or "n" to cancel.'))
+ end
+ rescue TTY::Prompt::Reader::InputInterrupt
+ PDK.logger.info opts[:cancel_message] if opts[:cancel_message]
+ end
+
+ response
+ end
+ module_function :prompt_for_yes
end
end
end
diff --git a/lib/pdk/generators/module.rb b/lib/pdk/generators/module.rb
index <HASH>..<HASH> 100644
--- a/lib/pdk/generators/module.rb
+++ b/lib/pdk/generators/module.rb
@@ -8,6 +8,7 @@ require 'pdk/logger'
require 'pdk/module/metadata'
require 'pdk/module/templatedir'
require 'pdk/cli/exec'
+require 'pdk/cli/util'
require 'pdk/cli/util/interview'
require 'pdk/cli/util/option_validator'
require 'pdk/util'
@@ -322,14 +323,11 @@ module PDK
puts '-' * 40
puts
- begin
- continue = prompt.yes?(_('About to generate this module; continue?')) do |q|
- q.validate(proc { |value| [true, false].include?(value) || value =~ %r{\A(?:yes|y|no|n)\Z}i }, _('Answer "Y" to continue or "n" to cancel.'))
- end
- rescue TTY::Prompt::Reader::InputInterrupt
- PDK.logger.info _('Interview cancelled; not generating the module.')
- exit 0
- end
+ continue = PDK::CLI::Util.prompt_for_yes(
+ _('About to generate this module, continue?'),
+ prompt: prompt,
+ cancel_message: _('Interview cancelled; not generating the module.'),
+ )
unless continue
PDK.logger.info _('Module not generated.')
|
(maint) Extract the prompt for yes logic into method
|
puppetlabs_pdk
|
train
|
f9f7fdb9745524a5ddd183d0002f2ea9cc3c32ea
|
diff --git a/library/src/com/handmark/pulltorefresh/library/PullToRefreshAdapterViewBase.java b/library/src/com/handmark/pulltorefresh/library/PullToRefreshAdapterViewBase.java
index <HASH>..<HASH> 100644
--- a/library/src/com/handmark/pulltorefresh/library/PullToRefreshAdapterViewBase.java
+++ b/library/src/com/handmark/pulltorefresh/library/PullToRefreshAdapterViewBase.java
@@ -16,7 +16,7 @@ import com.handmark.pulltorefresh.library.internal.EmptyViewMethodAccessor;
public abstract class PullToRefreshAdapterViewBase<T extends AbsListView> extends PullToRefreshBase<T> implements
OnScrollListener {
- private int mLastSavedFirstVisibleItem = -1;
+ private int mSavedLastVisibleIndex = -1;
private OnScrollListener mOnScrollListener;
private OnLastItemVisibleListener mOnLastItemVisibleListener;
private View mEmptyView;
@@ -44,10 +44,18 @@ public abstract class PullToRefreshAdapterViewBase<T extends AbsListView> extend
if (null != mOnLastItemVisibleListener) {
// detect if last item is visible
- if (visibleItemCount > 0 && (firstVisibleItem + visibleItemCount == totalItemCount)) {
+ int lastVisibleItemIndex = firstVisibleItem + visibleItemCount;
+
+ /**
+ * Check that we have any items, and that the last item is visible.
+ * lastVisibleItemIndex is a zero-based index, so we add one to it
+ * to check against totalItemCount.
+ */
+ if (visibleItemCount > 0 && (lastVisibleItemIndex + 1) == totalItemCount) {
+
// only process first event
- if (firstVisibleItem != mLastSavedFirstVisibleItem) {
- mLastSavedFirstVisibleItem = firstVisibleItem;
+ if (lastVisibleItemIndex != mSavedLastVisibleIndex) {
+ mSavedLastVisibleIndex = lastVisibleItemIndex;
mOnLastItemVisibleListener.onLastItemVisible();
}
}
@@ -146,7 +154,7 @@ public abstract class PullToRefreshAdapterViewBase<T extends AbsListView> extend
private boolean isLastItemVisible() {
final int count = mRefreshableView.getCount();
final int lastVisiblePosition = mRefreshableView.getLastVisiblePosition();
-
+
if (DEBUG) {
Log.d(LOG_TAG, "isLastItemVisible. Count: " + count + " Last Visible Pos: " + lastVisiblePosition);
}
|
Fix #<I>: OnLastItemVisible being call more than once.
|
chrisbanes_Android-PullToRefresh
|
train
|
ba12c9a3fddface7e17753993efd80c9d80e586d
|
diff --git a/src/Loaders/DatabaseLoader.php b/src/Loaders/DatabaseLoader.php
index <HASH>..<HASH> 100644
--- a/src/Loaders/DatabaseLoader.php
+++ b/src/Loaders/DatabaseLoader.php
@@ -39,12 +39,7 @@ class DatabaseLoader extends Loader implements LoaderInterface
*/
public function loadSource($locale, $group, $namespace = '*')
{
- $result = [];
- $translations = $this->translationRepository->getItems($locale, $namespace, $group);
- foreach ($translations as $translation) {
- array_set($result, $translation['item'], $translation['text']);
- }
- return $result;
+ return $this->translationRepository->loadSource($locale, $namespace, $group);
}
/**
diff --git a/src/Repositories/TranslationRepository.php b/src/Repositories/TranslationRepository.php
index <HASH>..<HASH> 100644
--- a/src/Repositories/TranslationRepository.php
+++ b/src/Repositories/TranslationRepository.php
@@ -202,7 +202,9 @@ class TranslationRepository extends Repository
/**
* Return all items for a given locale, namespace and group
*
- * @param string $code
+ * @param string $locale
+ * @param string $namespace
+ * @param string $group
* @return array
*/
public function getItems($locale, $namespace, $group)
@@ -216,6 +218,27 @@ class TranslationRepository extends Repository
}
/**
+ * Return all items formatted as if coming from a PHP language file.
+ *
+ * @param string $locale
+ * @param string $namespace
+ * @param string $group
+ * @return array
+ */
+ public function loadSource($locale, $namespace, $group)
+ {
+ return $this->model
+ ->whereLocale($locale)
+ ->whereNamespace($namespace)
+ ->whereGroup($group)
+ ->get()
+ ->reduce(function ($translationsArray, $translation) {
+ array_set($translationsArray, $translation['item'], $translation['text']);
+ return $translationsArray;
+ }, []);
+ }
+
+ /**
* Retrieve translations pending review for the given locale.
*
* @param string $locale
diff --git a/tests/Loaders/DatabaseLoaderTest.php b/tests/Loaders/DatabaseLoaderTest.php
index <HASH>..<HASH> 100644
--- a/tests/Loaders/DatabaseLoaderTest.php
+++ b/tests/Loaders/DatabaseLoaderTest.php
@@ -10,8 +10,8 @@ class DatabaseLoaderTest extends TestCase
public function setUp()
{
parent::setUp();
- $this->repo = Mockery::mock(TranslationRepository::class);
- $this->loader = new DatabaseLoader('en', $this->repo);
+ $this->translationRepository = \App::make(TranslationRepository::class);
+ $this->loader = new DatabaseLoader('es', $this->translationRepository);
}
public function tearDown()
@@ -25,16 +25,37 @@ class DatabaseLoaderTest extends TestCase
*/
public function it_returns_from_database()
{
- $data = [
- ['item' => 'one', 'text' => 'first'],
- ['item' => 'two', 'text' => 'second'],
- ];
$expected = [
- 'one' => 'first',
- 'two' => 'second',
+ 'simple' => 'text',
+ 'array' => [
+ 'item' => 'item',
+ 'nested' => [
+ 'item' => 'nested',
+ ],
+ ],
];
- $this->repo->shouldReceive('getItems')->with('en', 'name', 'group')->once()->andReturn($data);
- $results = $this->loader->loadSource('en', 'group', 'name');
- $this->assertEquals($expected, $results);
+ $translation = $this->translationRepository->create([
+ 'locale' => 'es',
+ 'namespace' => '*',
+ 'group' => 'group',
+ 'item' => 'simple',
+ 'text' => 'text',
+ ]);
+ $translation = $this->translationRepository->create([
+ 'locale' => 'es',
+ 'namespace' => '*',
+ 'group' => 'group',
+ 'item' => 'array.item',
+ 'text' => 'item',
+ ]);
+ $translation = $this->translationRepository->create([
+ 'locale' => 'es',
+ 'namespace' => '*',
+ 'group' => 'group',
+ 'item' => 'array.nested.item',
+ 'text' => 'nested',
+ ]);
+ $translations = $this->loader->loadSource('es', 'group');
+ $this->assertEquals($expected, $translations);
}
}
|
Added loadSource to translation repository.
Refactored DatabaseLoader to use loadSource in TranslationRepository.
Modified DatabaseLoader tests accordingly.
|
Waavi_translation
|
train
|
b8b2949b5d304dfa2885762addbe4f9caddc4a6b
|
diff --git a/src/Malenki/Bah/S.php b/src/Malenki/Bah/S.php
index <HASH>..<HASH> 100644
--- a/src/Malenki/Bah/S.php
+++ b/src/Malenki/Bah/S.php
@@ -171,6 +171,7 @@ class S extends O implements \Countable
return $this->chunk();
}
+
if ($name == 'ucw') {
return $this->_upperCaseWords();
}
@@ -179,7 +180,7 @@ class S extends O implements \Countable
return $this->_upperCaseFirst();
}
- if (in_array($name, array('string', 'title', 'upper', 'lower', 'n', 'r', 'first', 'last', 'a', 'trans', 'rtl', 'ltr'))) {
+ if (in_array($name, array('string', 'title', 'upper', 'lower', 'n', 'r', 'first', 'last', 'a', 'trans', 'rtl', 'ltr', 'md5'))) {
$str_method = '_' . $name;
return $this->$str_method();
@@ -1035,6 +1036,10 @@ class S extends O implements \Countable
return !$this->_rtl() && !$this->_ltr();
}
+ protected function _md5()
+ {
+ return new S(md5($this->value));
+ }
/**
*
diff --git a/tests/STest.php b/tests/STest.php
index <HASH>..<HASH> 100644
--- a/tests/STest.php
+++ b/tests/STest.php
@@ -594,4 +594,13 @@ class STest extends PHPUnit_Framework_TestCase
$this->assertEquals($should, $s->justify(15, 'right'));
}
+
+
+ public function testGettingMd5SumShouldSuccess()
+ {
+ $s = new S('I am not a number! I am free man!');
+ $this->assertInstanceOf('\Malenki\Bah\S', $s->md5);
+ $this->assertCount(32, $s->md5);
+ $this->assertRegExp('/^[a-f0-9]{32}$/', $s->md5->string);
+ }
}
|
Class S: md5 feature
|
malenkiki_bah
|
train
|
af8f20784691a3291a5284ae3a7a1e5b83c819a8
|
diff --git a/rehive/api/resources/admin_resources.py b/rehive/api/resources/admin_resources.py
index <HASH>..<HASH> 100644
--- a/rehive/api/resources/admin_resources.py
+++ b/rehive/api/resources/admin_resources.py
@@ -148,7 +148,7 @@ class APIAdminMobiles(ResourceList):
def create(self, user, number, **kwargs):
data = {
'user': user,
- 'email': email
+ 'number': number
}
return self.post(data, **kwargs)
|
Remove email from mobile number admin data. Added number field.
|
rehive_rehive-python
|
train
|
b829717210a069cd4f6124a871352e4e4dfd991f
|
diff --git a/lib/origen/generator/pattern.rb b/lib/origen/generator/pattern.rb
index <HASH>..<HASH> 100755
--- a/lib/origen/generator/pattern.rb
+++ b/lib/origen/generator/pattern.rb
@@ -235,7 +235,9 @@ module Origen
c2 " Workspace: #{Origen.root}"
if Origen.app.rc && Origen.app.rc.git?
begin
- status = "#{Origen.app.rc.current_branch}(#{Origen.app.rc.current_commit})"
+ @branch ||= Origen.app.rc.current_branch
+ @commit ||= Origen.app.rc.current_commit
+ status = "#{@branch}(#{@commit})"
@pattern_local_mods = !Origen.app.rc.local_modifications.empty? unless @pattern_local_mods_fetched
@pattern_local_mods_fetched = true
status += ' (+local edits)' if @pattern_local_mods
diff --git a/lib/origen/revision_control/git.rb b/lib/origen/revision_control/git.rb
index <HASH>..<HASH> 100755
--- a/lib/origen/revision_control/git.rb
+++ b/lib/origen/revision_control/git.rb
@@ -190,18 +190,18 @@ module Origen
end
def current_branch
- @current_branch ||= git('rev-parse --abbrev-ref HEAD', verbose: false).first
+ git('rev-parse --abbrev-ref HEAD', verbose: false).first
end
def current_commit(options = {})
options = {
short: true
}.merge(options)
- @current_commit ||= git('rev-parse HEAD', verbose: false).first
+ commit = git('rev-parse HEAD', verbose: false).first
if options[:short]
- @current_commit[0, 11]
+ commit[0, 11]
else
- @current_commit
+ commit
end
end
|
Actually, let's cache at the pattern header level rather than the
revision controller
|
Origen-SDK_origen
|
train
|
cd0be199a4fb3fed9486fc57607571bc8169e8c5
|
diff --git a/src/pymop/pymop/applauncher.py b/src/pymop/pymop/applauncher.py
index <HASH>..<HASH> 100644
--- a/src/pymop/pymop/applauncher.py
+++ b/src/pymop/pymop/applauncher.py
@@ -9,7 +9,7 @@ from pymop.io.mpc import MPCWriter
from pymop.io.naming import ProvisionalNameGenerator
from pymop.io.imgaccess import (AsynchronousImageDownloadManager,
ImageSliceDownloader, VOSpaceResolver)
-from pymop.gui.models import AstroDataModel
+from pymop.gui.models import ProcessRealsModel
from pymop.gui.controllers import ApplicationController
@@ -29,7 +29,7 @@ class AstromFileApplicationLauncher(object):
with open(output_filename, "wb") as output_filehandle:
self.astrom_data = self.parser.parse(astrom_file)
- self.model = AstroDataModel(self.astrom_data, self.download_manager)
+ self.model = ProcessRealsModel(self.astrom_data, self.download_manager)
self.output_writer = MPCWriter(output_filehandle)
self.controller = ApplicationController(self.model,
self.output_writer,
diff --git a/src/pymop/pymop/gui/models.py b/src/pymop/pymop/gui/models.py
index <HASH>..<HASH> 100644
--- a/src/pymop/pymop/gui/models.py
+++ b/src/pymop/pymop/gui/models.py
@@ -24,7 +24,7 @@ MSG_IMG_LOADED = MSG_ROOT + ("imgload", )
MSG_ALL_SRC_PROC = MSG_ROOT + ("allproc", )
-class AstroDataModel(object):
+class ProcessRealsModel(object):
"""
Main model for storing and accessing astronomical data in the
application.
diff --git a/src/pymop/test/test_pymop/test_gui/test_models.py b/src/pymop/test/test_pymop/test_gui/test_models.py
index <HASH>..<HASH> 100644
--- a/src/pymop/test/test_pymop/test_gui/test_models.py
+++ b/src/pymop/test/test_pymop/test_gui/test_models.py
@@ -22,7 +22,7 @@ class AstroDataModelTest(FileReadingTestCase):
self.astrom_data = AstromParser().parse(testfile)
self.download_manager = Mock()
- self.model = models.AstroDataModel(self.astrom_data, self.download_manager)
+ self.model = models.ProcessRealsModel(self.astrom_data, self.download_manager)
def create_real_first_image(self, path="data/testimg.fits"):
# Put a real fits image on the first source, first observation
|
Renamed AstroDataModel to ProcessRealsModel.
|
OSSOS_MOP
|
train
|
d8488bc74da79beea3ca9a01ffc28c6735217976
|
diff --git a/lib/promise.js b/lib/promise.js
index <HASH>..<HASH> 100644
--- a/lib/promise.js
+++ b/lib/promise.js
@@ -5,6 +5,7 @@ const { deprecationLog } = require('./helper');
/**
* @extends Promise
+ * @deprecated
*/
class ZkPromise extends Promise {
/**
|
fix: set deprecated for entire legacy Promise class
|
yfinkelstein_node-zookeeper
|
train
|
9c3b4594c0d703383c121ee9914d170a74eec33a
|
diff --git a/jupyterthemes/__init__.py b/jupyterthemes/__init__.py
index <HASH>..<HASH> 100644
--- a/jupyterthemes/__init__.py
+++ b/jupyterthemes/__init__.py
@@ -8,7 +8,7 @@ import os
import argparse
from glob import glob
import lesscpy
-__version__ = '0.7.5'
+__version__ = '0.7.6'
# juypter config and package dir
package_dir = os.path.dirname(os.path.realpath(__file__))
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,7 @@ os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='jupyterthemes',
- version='0.7.5',
+ version='0.7.6',
packages=['jupyterthemes'],
include_package_data=True,
package_data={'jupyterthemes': ['sandbox/*.js', 'layout/*.less', 'layout/*.css', 'styles/*.less']},
@@ -15,7 +15,7 @@ setup(
long_description=README,
license='MIT',
url='https://github.com/dunovank/jupyter-themes/',
- download_url='https://github.com/dunovank/jupyter-themes/tarball/v0.7.5',
+ download_url='https://github.com/dunovank/jupyter-themes/tarball/v0.7.6',
author='dunovank',
author_email='dunovank@gmail.com',
classifiers=[
|
removed spacelegos, version bump
|
dunovank_jupyter-themes
|
train
|
ac59200821207c14670040bb2ed191eabdd10ad7
|
diff --git a/MAVProxy/modules/mavproxy_wp.py b/MAVProxy/modules/mavproxy_wp.py
index <HASH>..<HASH> 100644
--- a/MAVProxy/modules/mavproxy_wp.py
+++ b/MAVProxy/modules/mavproxy_wp.py
@@ -16,8 +16,9 @@ class WPModule(mp_module.MPModule):
self.loading_waypoint_lasttime = time.time()
self.last_waypoint = 0
self.wp_period = mavutil.periodic_event(0.5)
+ self.use_terrain = False
self.add_command('wp', self.cmd_wp, 'waypoint management',
- ["<list|clear|move|remove|loop|set>",
+ ["<list|clear|move|remove|loop|set|terrain>",
"<load|update|save> (FILENAME)"])
if self.continue_mode and self.logdir != None:
@@ -203,7 +204,7 @@ class WPModule(mp_module.MPModule):
self.wploader.target_component = self.target_component
self.wploader.add(home)
for p in points:
- self.wploader.add_latlonalt(p[0], p[1], self.settings.wpalt)
+ self.wploader.add_latlonalt(p[0], p[1], self.settings.wpalt, terrain_alt=self.use_terrain)
self.send_all_waypoints()
def wp_loop(self):
@@ -300,7 +301,7 @@ class WPModule(mp_module.MPModule):
def cmd_wp(self, args):
'''waypoint commands'''
- usage = "usage: wp <list|load|update|save|set|clear|loop|remove|move>"
+ usage = "usage: wp <list|load|update|save|set|clear|loop|remove|move|terrain>"
if len(args) < 1:
print(usage)
return
@@ -348,6 +349,12 @@ class WPModule(mp_module.MPModule):
print("usage: wp set <wpindex>")
return
self.master.waypoint_set_current_send(int(args[1]))
+ elif args[0] == "terrain":
+ if len(args) > 1 and args[1] in ['1','true','yes']:
+ self.use_terrain = True
+ elif len(args) > 1 and args[1] in ['0','false','no']:
+ self.use_terrain = False
+ print("terrain: %s" % self.use_terrain)
elif args[0] == "clear":
self.master.waypoint_clear_all_send()
self.wploader.clear()
|
wp: support terrain alt missions
|
ArduPilot_MAVProxy
|
train
|
993dceea2f84c6f43ca0da7bcd7123ea873ed5ab
|
diff --git a/test/driver.js b/test/driver.js
index <HASH>..<HASH> 100644
--- a/test/driver.js
+++ b/test/driver.js
@@ -84,7 +84,7 @@ function runTests(callback) {
if (expFail) callback("expected", test.name);
else if (e instanceof Failure) callback("fail", test.name, e.message);
else {
- var pos = /\bat .*?([^\/:]+):(\d+):/.exec(e.stack);
+ var pos = /(?:\bat |@).*?([^\/:]+):(\d+)/.exec(e.stack);
callback("error", test.name, e.toString() + (pos ? " (" + pos[1] + ":" + pos[2] + ")" : ""));
}
}
|
[tests] Support the other format of error.stack
This makes error.stack parsing work in Firefox and Opera <I>-, and maybe in Safari too (didn't test).
|
codemirror_CodeMirror
|
train
|
33485d10b6e6508f6eabde969e96d4fb1201382f
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,10 @@
## WIP
+### Added
+
+- Toggable triggers 'shown'/'hidden' events, when animations complete
+
### Fixed
- Fix component initialization
diff --git a/src/js/core/scroll.js b/src/js/core/scroll.js
index <HASH>..<HASH> 100644
--- a/src/js/core/scroll.js
+++ b/src/js/core/scroll.js
@@ -36,7 +36,7 @@ export default function (UIkit) {
.stop()
.animate({scrollTop: parseInt(target, 10) || 1}, this.duration, this.transition)
.promise()
- .then(() => this.$el.triggerHandler($.Event('scrolled'), [this]));
+ .then(() => this.$el.trigger('scrolled', [this]));
}
diff --git a/src/js/mixin/toggable.js b/src/js/mixin/toggable.js
index <HASH>..<HASH> 100644
--- a/src/js/mixin/toggable.js
+++ b/src/js/mixin/toggable.js
@@ -127,7 +127,7 @@ export default {
)(el, show);
el.trigger(show ? 'show' : 'hide', [this]);
- return deferred;
+ return deferred.then(() => el.trigger(show ? 'shown' : 'hidden', [this]));
},
_toggle(el, toggled) {
|
Toggable triggers 'shown'/'hidden' events, when animations complete
|
uikit_uikit
|
train
|
e533637ae1c63cb0545e509360bae338bab82e14
|
diff --git a/.rubocop.yml b/.rubocop.yml
index <HASH>..<HASH> 100644
--- a/.rubocop.yml
+++ b/.rubocop.yml
@@ -10,3 +10,6 @@ Style/TrailingComma:
Style/BlockDelimiters:
Enabled: false
+
+Style/FormatString:
+ Enabled: false
diff --git a/lib/loga/rack/logger.rb b/lib/loga/rack/logger.rb
index <HASH>..<HASH> 100644
--- a/lib/loga/rack/logger.rb
+++ b/lib/loga/rack/logger.rb
@@ -59,7 +59,12 @@ module Loga
end
def compute_message
- "#{request.request_method} #{request.filtered_full_path}"
+ '%{method} %{filtered_full_path} %{status} in %{duration}ms' % {
+ method: request.request_method,
+ filtered_full_path: request.filtered_full_path,
+ status: data['status'],
+ duration: data['duration'],
+ }
end
def compute_level
diff --git a/spec/support/request_spec.rb b/spec/support/request_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/support/request_spec.rb
+++ b/spec/support/request_spec.rb
@@ -8,7 +8,7 @@ RSpec.shared_examples 'request logger' do
expect(json).to match(
'version' => '1.1',
'host' => 'bird.example.com',
- 'short_message' => 'GET /ok?username=yoshi',
+ 'short_message' => 'GET /ok?username=yoshi 200 in 0ms',
'timestamp' => 1_450_150_205.123,
'level' => 6,
'_type' => 'request',
@@ -38,7 +38,7 @@ RSpec.shared_examples 'request logger' do
expect(json).to match(
'version' => '1.1',
'host' => 'bird.example.com',
- 'short_message' => 'POST /users?username=yoshi',
+ 'short_message' => 'POST /users?username=yoshi 200 in 0ms',
'timestamp' => 1_450_150_205.123,
'level' => 6,
'_type' => 'request',
@@ -69,7 +69,7 @@ RSpec.shared_examples 'request logger' do
expect(json).to match(
'version' => '1.1',
'host' => 'bird.example.com',
- 'short_message' => 'GET /new',
+ 'short_message' => 'GET /new 302 in 0ms',
'timestamp' => 1_450_150_205.123,
'level' => 6,
'_type' => 'request',
@@ -97,7 +97,7 @@ RSpec.shared_examples 'request logger' do
expect(json).to match(
'version' => '1.1',
'host' => 'bird.example.com',
- 'short_message' => 'GET /error?username=yoshi',
+ 'short_message' => 'GET /error?username=yoshi 500 in 0ms',
'timestamp' => 1_450_150_205.123,
'level' => 3,
'_type' => 'request',
@@ -126,7 +126,7 @@ RSpec.shared_examples 'request logger' do
expect(json).to match(
'version' => '1.1',
'host' => 'bird.example.com',
- 'short_message' => 'GET /not_found',
+ 'short_message' => 'GET /not_found 404 in 0ms',
'timestamp' => 1_450_150_205.123,
'level' => 6,
'_type' => 'request',
@@ -156,7 +156,7 @@ RSpec.shared_examples 'request logger' do
it 'filters the parameter from the message' do
expect(json).to include(
- 'short_message' => 'GET /ok?password=[FILTERED]',
+ 'short_message' => 'GET /ok?password=[FILTERED] 200 in 0ms',
)
end
end
diff --git a/spec/unit/loga/rack/logger_spec.rb b/spec/unit/loga/rack/logger_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/loga/rack/logger_spec.rb
+++ b/spec/unit/loga/rack/logger_spec.rb
@@ -19,7 +19,7 @@ describe Loga::Rack::Logger do
before do
allow(subject).to receive(:started_at).and_return(:timestamp)
- allow(subject).to receive(:duration_in_ms).with(any_args).and_return(:duration)
+ allow(subject).to receive(:duration_in_ms).with(any_args).and_return(5)
end
it 'instantiates a Loga::Event' do
@@ -33,11 +33,11 @@ describe Loga::Rack::Logger do
'request_id' => nil,
'request_ip' => nil,
'user_agent' => nil,
- 'duration' => :duration,
+ 'duration' => 5,
},
},
exception: logged_exception,
- message: 'GET /about_us?limit=1',
+ message: %r{^GET \/about_us\?limit=1 #{response_status} in \d+ms$},
timestamp: :timestamp,
type: 'request',
)
|
Improve Rack request message
Provide additional information such as status and duration in the message.
```
// Before
GET /hello
// After
GET /hello <I> in 5ms
```
|
FundingCircle_loga
|
train
|
e69743f6fd95ff02a5e13facb05479572f584121
|
diff --git a/release.sh b/release.sh
index <HASH>..<HASH> 100755
--- a/release.sh
+++ b/release.sh
@@ -1,8 +1,11 @@
#!/bin/bash
+# pip release scripts that auto-updates version number and keeps trying until successful
#set -x
set -u
+i=0
while true
do
+ i=$[i+1]
output=$(grep version= setup.py | awk -F'=' '{print $2}' | sed "s/'\([0-9][0-9]*\)\.\([0-9][0-9]*\)\.\([0-9][0-9]*\)',/\1 \2 \3/")
major=$(echo $output | awk '{print $1}')
minor=$(echo $output | awk '{print $2}')
@@ -15,4 +18,7 @@ do
then
break
fi
+ # wait a minute
+ sleep 60
done
+echo Success after $i attempts
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -17,7 +17,7 @@ setup(
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
- version='0.9.104',
+ version='0.9.106',
description='An automation tool designed for complex Docker builds',
long_description=long_description,
diff --git a/shutit_global.py b/shutit_global.py
index <HASH>..<HASH> 100644
--- a/shutit_global.py
+++ b/shutit_global.py
@@ -740,8 +740,8 @@ $'"""
return send
cmd_arr = send.split()
if len(cmd_arr) and cmd_arr[0] in ('md5sum','sed','head'):
- cmd = self._get_command(cmd_arr[0])
- send = string.join(cmd + send[len(cmd_arr[0]):],'')
+ newcmd = self._get_command(cmd_arr[0])
+ send = send.replace(cmd_arr[0],newcmd)
return send
diff --git a/shutit_main.py b/shutit_main.py
index <HASH>..<HASH> 100755
--- a/shutit_main.py
+++ b/shutit_main.py
@@ -750,7 +750,7 @@ def setup_signals():
signal.signal(signal.SIGINT, shutit_util.ctrl_c_signal_handler)
signal.signal(signal.SIGQUIT, shutit_util.ctrl_quit_signal_handler)
-shutit_version='0.9.104'
+shutit_version='0.9.106'
if __name__ == '__main__':
setup_signals()
main()
diff --git a/test/10/test10.py b/test/10/test10.py
index <HASH>..<HASH> 100644
--- a/test/10/test10.py
+++ b/test/10/test10.py
@@ -1,37 +1,8 @@
-"""ShutIt module. See http://shutit.tk
-"""
-
from shutit_module import ShutItModule
-
class test10(ShutItModule):
-
def build(self, shutit):
- # Some useful API calls for reference see shutit's docs for more info and options:
- # shutit.send(send) - send a command
- # shutit.multisend(send,send_dict) - send a command, dict contains {expect1:response1,expect2:response2,...}
- # shutit.log(msg) - send a message to the log
- # shutit.run_script(script) - run the passed-in string as a script
- # shutit.send_file(path, contents) - send file to path on target with given contents as a string
- # shutit.send_host_file(path, hostfilepath) - send file from host machine to path on the target
- # shutit.send_host_dir(path, hostfilepath) - send directory and contents to path on the target
- # shutit.host_file_exists(filename, directory=False) - returns True if file exists on host
- # shutit.file_exists(filename, directory=False) - returns True if file exists on target
- # shutit.add_to_bashrc(line) - add a line to bashrc
- # shutit.get_url(filename, locations) - get a file via url from locations specified in a list
- # shutit.user_exists(user) - returns True if the user exists on the target
- # shutit.package_installed(package) - returns True if the package exists on the target
- # shutit.pause_point(msg='') - give control of the terminal to the user
- # shutit.step_through(msg='') - give control to the user and allow them to step through commands
- # shutit.send_and_get_output(send) - returns the output of the sent command
- # shutit.install(package) - install a package
- # shutit.remove(package) - remove a package
- # shutit.login(user='root', command='su -') - log user in with given command, and set up prompt and expects
- # shutit.logout() - clean up from a login
- # shutit.set_password(password, user='') - set password for a given user on target
- # shutit.get_config(module_id,option,default=None) - get configuration value
- # shutit.get_ip_address() - returns the ip address of the target
if not shutit.send_and_match_output('echo "A STRING"','A STR'):
shutit.fail('test10.1 failed')
if not shutit.send_and_match_output('echo "A STRING"','A STRING'):
diff --git a/test/11/test11.py b/test/11/test11.py
index <HASH>..<HASH> 100644
--- a/test/11/test11.py
+++ b/test/11/test11.py
@@ -1,12 +1,7 @@
-"""ShutIt module. See http://shutit.tk
-"""
-
from shutit_module import ShutItModule
-
class test11(ShutItModule):
-
def build(self, shutit):
################################################################################
|
bugfix for sends with leading spaces
|
ianmiell_shutit
|
train
|
579da2cc7133f67e6bbec67a26e80400c696b2b3
|
diff --git a/app/classes/lib.php b/app/classes/lib.php
index <HASH>..<HASH> 100644
--- a/app/classes/lib.php
+++ b/app/classes/lib.php
@@ -99,7 +99,7 @@ function cleanPostedData($var, $stripslashes = true)
$var = str_replace("\t", " ", $var);
// prune control characters
- $var = preg_replace('/[[:cntrl:][:space:]]/', ' ', $var);
+ // $var = preg_replace('/[[:cntrl:][:space:]]/', ' ', $var);
// Ah, the joys of \"magic quotes\"!
if ($stripslashes && get_magic_quotes_gpc()) {
|
Temporary workaround for editing files.
ref <I>eb<I>b<I>ea<I>dbe<I>ab<I>c
|
bolt_bolt
|
train
|
738cda347c8a6f7059a72cb683104066d6e3ba0b
|
diff --git a/flink-tests/src/test/java/org/apache/flink/test/recovery/AbstractTaskManagerProcessFailureRecoveryTest.java b/flink-tests/src/test/java/org/apache/flink/test/recovery/AbstractTaskManagerProcessFailureRecoveryTest.java
index <HASH>..<HASH> 100644
--- a/flink-tests/src/test/java/org/apache/flink/test/recovery/AbstractTaskManagerProcessFailureRecoveryTest.java
+++ b/flink-tests/src/test/java/org/apache/flink/test/recovery/AbstractTaskManagerProcessFailureRecoveryTest.java
@@ -104,6 +104,7 @@ public abstract class AbstractTaskManagerProcessFailureRecoveryTest extends Test
config.setInteger(TaskManagerOptions.NUM_TASK_SLOTS, 2);
config.setString(TaskManagerOptions.LEGACY_MANAGED_MEMORY_SIZE, "4m");
config.setInteger(NettyShuffleEnvironmentOptions.NETWORK_NUM_BUFFERS, 100);
+ config.setString(JobManagerOptions.EXECUTION_FAILOVER_STRATEGY, "full");
try (final StandaloneSessionClusterEntrypoint clusterEntrypoint = new StandaloneSessionClusterEntrypoint(config)) {
|
[FLINK-<I>][tests] Enable AbstractTaskManagerProcessFailureRecoveryTest to pass with new DefaultScheduler
This closes #<I>.
|
apache_flink
|
train
|
e0ed21a437d55e86f81e01f077cea92963d97669
|
diff --git a/eZ/Publish/API/Repository/Tests/BaseTest.php b/eZ/Publish/API/Repository/Tests/BaseTest.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/API/Repository/Tests/BaseTest.php
+++ b/eZ/Publish/API/Repository/Tests/BaseTest.php
@@ -93,9 +93,9 @@ abstract class BaseTest extends PHPUnit_Framework_TestCase
chdir( realpath( str_repeat( '../', $count ) ) );
$this->repository = include $file;
-
+/*
$userService = $this->repository->getUserService();
- $this->repository->setCurrentUser( $userService->loadUser( 14 ) );
+ $this->repository->setCurrentUser( $userService->loadUser( 14 ) );*/
}
return $this->repository;
}
|
Fixed: Expect that the init script returns a ready to use repository
|
ezsystems_ezpublish-kernel
|
train
|
73256843be7c95f5d01135b13f7d82cbfd3f1235
|
diff --git a/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/web/ssl/HTTPSWebConnectorTestCase.java b/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/web/ssl/HTTPSWebConnectorTestCase.java
index <HASH>..<HASH> 100644
--- a/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/web/ssl/HTTPSWebConnectorTestCase.java
+++ b/testsuite/integration/manualmode/src/test/java/org/jboss/as/test/manualmode/web/ssl/HTTPSWebConnectorTestCase.java
@@ -66,7 +66,7 @@ import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.operations.common.Util;
import org.jboss.as.test.categories.CommonCriteria;
import org.jboss.as.test.integration.security.common.AbstractSecurityDomainsServerSetupTask;
-import org.jboss.as.test.integration.security.common.AddRoleLoginModule;
+//import org.jboss.as.test.integration.security.common.AddRoleLoginModule;
import org.jboss.as.test.integration.security.common.SSLTruststoreUtil;
import org.jboss.as.test.integration.security.common.SecurityTestConstants;
import org.jboss.as.test.integration.security.common.SecurityTraceLoggingServerSetupTask;
@@ -159,7 +159,8 @@ public class HTTPSWebConnectorTestCase {
public static WebArchive deployment() {
LOGGER.trace("Start deployment " + APP_CONTEXT);
final WebArchive war = ShrinkWrap.create(WebArchive.class, APP_CONTEXT + ".war");
- war.addClasses(AddRoleLoginModule.class, SimpleServlet.class, SimpleSecuredServlet.class,
+ // AddRoleLoginModule.class
+ war.addClasses(SimpleServlet.class, SimpleSecuredServlet.class,
PrincipalPrintingServlet.class);
war.addAsWebInfResource(HTTPSWebConnectorTestCase.class.getPackage(), "web.xml", "web.xml");
war.addAsWebInfResource(HTTPSWebConnectorTestCase.class.getPackage(), "jboss-web.xml", "jboss-web.xml");
@@ -534,7 +535,7 @@ public class HTTPSWebConnectorTestCase {
new SecurityModule.Builder().name(BaseCertLoginModule.class.getName())
.putOption("securityDomain", SECURITY_DOMAIN_JSSE)
.putOption("password-stacking", "useFirstPass").build(),
- new SecurityModule.Builder().name(AddRoleLoginModule.class.getName()).flag("optional")
+ new SecurityModule.Builder().name("REMOVED").flag("optional") // AddRoleLoginModule.class.getName()
.putOption("password-stacking", "useFirstPass")
.putOption("roleName", SimpleSecuredServlet.ALLOWED_ROLE).build()) //
.build();
|
[WFLY-<I>] / [WFLY-<I>] Remove PicketBox use from already ignored test.
|
wildfly_wildfly
|
train
|
d0f92f573f61c11d9cc60d6df88730c8f6571af3
|
diff --git a/setup/test_integration.py b/setup/test_integration.py
index <HASH>..<HASH> 100644
--- a/setup/test_integration.py
+++ b/setup/test_integration.py
@@ -13,7 +13,7 @@ def rethink():
except KeyError:
tag="latest"
CLIENT.containers.run("".join(("ramrodpcp/database-brain:",tag)), name="rethinkdb", detach=True, ports={"28015/tcp":28015}, remove=True)
- sleep(8)
+ sleep(10)
yield r.connect("127.0.0.1", 28015)
try:
environ["LOGLEVEL"]=""
@@ -26,10 +26,10 @@ def rethink():
pass
def test_brain(rethink):
- r.db_list().contains('Brain').run(rethink)
+ r.db('Brain').run(rethink)
def test_plugins(rethink):
- r.db_list().contains('Plugins').run(rethink)
+ r.db('Plugins').run(rethink)
def test_brain_targets(rethink):
r.db("Brain").table('Targets').run(rethink)
@@ -41,7 +41,7 @@ def test_brain_jobs(rethink):
r.db("Brain").table('Jobs').run(rethink)
def test_audit(rethink):
- r.db_list().contains('Audit').run(rethink)
+ r.db('Audit').run(rethink)
def test_audit_jobs(rethink):
r.db("Audit").table('Jobs').run(rethink)
|
removed ,contains, extended sleep
|
ramrod-project_database-brain
|
train
|
272f2e86a334409e21c4647b177eb869ed18d133
|
diff --git a/db/db_sql_test.go b/db/db_sql_test.go
index <HASH>..<HASH> 100644
--- a/db/db_sql_test.go
+++ b/db/db_sql_test.go
@@ -996,16 +996,13 @@ var _ = Describe("SqlDB", func() {
Context("when db connection is successful", func() {
Context("when all routes have expired", func() {
- It("should prune the expired routes", func() {
+ It("should prune the expired routes and log the number of pruned routes", func() {
Eventually(func() []models.TcpRouteMapping {
var tcpRoutes []models.TcpRouteMapping
err := sqlDB.Client.Where("host_ip = ?", "127.0.0.1").Find(&tcpRoutes).Error
Expect(err).ToNot(HaveOccurred())
return tcpRoutes
}, 2).Should(HaveLen(0))
- })
-
- It("should log the number of pruned routes", func() {
Eventually(logger, 2).Should(gbytes.Say(`"prune.successfully-finished-pruning-tcp-routes","log_level":1,"data":{"rowsAffected":1}`))
})
@@ -1058,19 +1055,18 @@ var _ = Describe("SqlDB", func() {
routes, err := sqlDB.ReadRoutes()
Expect(routes).To(HaveLen(1))
})
+
Context("when db connection is successful", func() {
Context("when all routes have expired", func() {
- It("should prune the expired routes", func() {
+ It("should prune the expired routes and log the number of pruned routes", func() {
Eventually(func() []models.Route {
var httpRoutes []models.Route
err := sqlDB.Client.Where("ip = ?", "127.0.0.1").Find(&httpRoutes).Error
Expect(err).ToNot(HaveOccurred())
return httpRoutes
}, 2).Should(HaveLen(0))
- })
- It("should log the number of pruned routes", func() {
Eventually(logger, 2).Should(gbytes.Say(`prune.successfully-finished-pruning-http-routes","log_level":1,"data":{"rowsAffected":1}`))
})
|
Combined SQL db prune route tests
|
cloudfoundry_routing-api
|
train
|
6e21169b1a6304b63e00ff31976641254cdb00dc
|
diff --git a/src/main/java/de/btobastian/javacord/utils/handler/user/PresenceUpdateHandler.java b/src/main/java/de/btobastian/javacord/utils/handler/user/PresenceUpdateHandler.java
index <HASH>..<HASH> 100644
--- a/src/main/java/de/btobastian/javacord/utils/handler/user/PresenceUpdateHandler.java
+++ b/src/main/java/de/btobastian/javacord/utils/handler/user/PresenceUpdateHandler.java
@@ -100,8 +100,8 @@ public class PresenceUpdateHandler extends PacketHandler {
// check username
if (packet.getJSONObject("user").has("username")) {
String name = packet.getJSONObject("user").getString("username");
- if (!user.getName().equals(name)) {
- final String oldName = user.getName();
+ final String oldName = user.getName();
+ if ((oldName == null && name != null) || (oldName != null && !user.getName().equals(name))) {
((ImplUser) user).setName(name);
listenerExecutorService.submit(new Runnable() {
@Override
|
Fix warning of PRESENT_UPDATE
|
Javacord_Javacord
|
train
|
a7736880fcd5c7ee1c6a740520c6735f3cbc9f3e
|
diff --git a/src/SAML2/Attribute/Attribute.php b/src/SAML2/Attribute/Attribute.php
index <HASH>..<HASH> 100644
--- a/src/SAML2/Attribute/Attribute.php
+++ b/src/SAML2/Attribute/Attribute.php
@@ -18,8 +18,6 @@
namespace Surfnet\SamlBundle\SAML2\Attribute;
-use UnexpectedValueException;
-
class Attribute
{
/**
@@ -38,18 +36,8 @@ class Attribute
*/
public function __construct(AttributeDefinition $attributeDefinition, array $value)
{
- if ($attributeDefinition->getMultiplicity() === AttributeDefinition::MULTIPLICITY_SINGLE
- && count($value) > 1
- ) {
- throw new UnexpectedValueException(sprintf(
- 'AttributeDefinition "%s" has a single-value multiplicity, got "%d" values',
- $attributeDefinition->getName(),
- count($value)
- ));
- }
-
$this->attributeDefinition = $attributeDefinition;
- $this->value = $value;
+ $this->value = $value;
}
/**
@@ -61,18 +49,10 @@ class Attribute
}
/**
- * @return null|string[]|string
+ * @return string[]
*/
public function getValue()
{
- if ($this->attributeDefinition->getMultiplicity() === AttributeDefinition::MULTIPLICITY_SINGLE) {
- if (empty($this->value)) {
- return null;
- }
-
- return reset($this->value);
- }
-
return $this->value;
}
diff --git a/src/SAML2/Attribute/AttributeDefinition.php b/src/SAML2/Attribute/AttributeDefinition.php
index <HASH>..<HASH> 100644
--- a/src/SAML2/Attribute/AttributeDefinition.php
+++ b/src/SAML2/Attribute/AttributeDefinition.php
@@ -23,20 +23,12 @@ use Surfnet\SamlBundle\Exception\LogicException;
class AttributeDefinition
{
- const MULTIPLICITY_SINGLE = 1;
- const MULTIPLICITY_MULTIPLE = 2;
-
/**
* @var string the name of the saml attribute
*/
private $name;
/**
- * @var int the multiplicity of this attribute
- */
- private $multiplicity;
-
- /**
* @var string the urn:mace identifier of this attribute
*/
private $urnMace;
@@ -50,9 +42,8 @@ class AttributeDefinition
* @param string $name
* @param string $urnMace
* @param string $urnOid
- * @param int $multiplicity
*/
- public function __construct($name, $urnMace = null, $urnOid = null, $multiplicity = self::MULTIPLICITY_SINGLE)
+ public function __construct($name, $urnMace = null, $urnOid = null)
{
if (!is_string($name)) {
throw InvalidArgumentException::invalidType('string', 'name', $name);
@@ -70,16 +61,7 @@ class AttributeDefinition
throw new LogicException('An AttributeDefinition should have at least either a mace or an oid urn');
}
- if (!in_array($multiplicity, [self::MULTIPLICITY_SINGLE, self::MULTIPLICITY_MULTIPLE])) {
- throw new InvalidArgumentException(sprintf(
- 'Multiplicity should be once of "%s", "%s" given',
- implode('", "', [self::MULTIPLICITY_SINGLE, self::MULTIPLICITY_MULTIPLE]),
- $multiplicity
- ));
- }
-
$this->name = $name;
- $this->multiplicity = $multiplicity;
$this->urnMace = $urnMace;
$this->urnOid = $urnOid;
}
@@ -125,14 +107,6 @@ class AttributeDefinition
}
/**
- * @return int
- */
- public function getMultiplicity()
- {
- return $this->multiplicity;
- }
-
- /**
* @param AttributeDefinition $other
* @return bool
*/
@@ -140,7 +114,6 @@ class AttributeDefinition
{
return $this->name === $other->name
&& $this->urnOid === $other->urnOid
- && $this->urnMace === $other->urnMace
- && $this->multiplicity === $other->multiplicity;
+ && $this->urnMace === $other->urnMace;
}
}
|
Remove Multiplicity from AttributeDefinition
The SAML2 specification does not make any mention
of multiplicity. Furthermore the functionality
was used sparsely if at all and should not have
been relied on as it was configuration based,
which could have changed causing a BC break in
and of itself as an Attribute could suddenly
cause exceptions to be thrown when configuration
changed or was overridden.
|
OpenConext_Stepup-saml-bundle
|
train
|
249b43a4121153e11fca31995142132a13dad4ae
|
diff --git a/src/main/java/io/openliberty/tools/ant/ServerTask.java b/src/main/java/io/openliberty/tools/ant/ServerTask.java
index <HASH>..<HASH> 100644
--- a/src/main/java/io/openliberty/tools/ant/ServerTask.java
+++ b/src/main/java/io/openliberty/tools/ant/ServerTask.java
@@ -458,7 +458,14 @@ public class ServerTask extends AbstractTask {
throw new BuildException("The archive attribute must specify a file");
}
if (isWindows) {
- command.add("--archive=" + "\"" + archive.toString() + "\"");
+ String archivePath = archive.toString();
+ if (archivePath.contains(" ")) {
+ // Command arguments that contain spaces will get surrounded by quotes by ProcessBuilder on Windows,
+ // which will cause problems with embedded quotes. So quote the entire command argument instead.
+ command.add("\"--archive=" + archivePath + "\"");
+ } else {
+ command.add("--archive=" + "\"" + archivePath + "\"");
+ }
} else {
command.add("--archive=" + archive.toString().replaceAll(" ", "\\\\ "));
}
|
handle embedded spaces in archive path (#<I>)
* escape embedded quotes
* try quoting entire archive option
* recreate initial error
* quote archive option and no embedded quotes
|
WASdev_ci.ant
|
train
|
56e806420556de546c15d4a66a182ee398fe09c7
|
diff --git a/test_flake8_future_import.py b/test_flake8_future_import.py
index <HASH>..<HASH> 100644
--- a/test_flake8_future_import.py
+++ b/test_flake8_future_import.py
@@ -4,7 +4,9 @@ import ast
import codecs
import itertools
import os
+import pip
import re
+import subprocess
import tempfile
import unittest
@@ -20,7 +22,9 @@ def generate_code(*imported):
"from os import path\n"
"print('Hello World')\n"
"if 42 % 2 == 0:\n"
- " print('42 is even')")
+ " print('42 is even')\n"
+ "print(sys.version_info)\n"
+ "print(path.abspath(__file__))\n")
for chain in imported:
code = "from __future__ import {0}\n{1}".format(
', '.join(chain), code)
@@ -168,5 +172,66 @@ class BadSyntaxTestCase(TestCaseBase):
"""Test using various bad syntax examples from Python's library."""
+class Flake8TestCase(unittest.TestCase):
+
+ """
+ Test this plugin using flake8.
+
+ This must install it in order for flake8 to be detected and might change the
+ current environment. So run it only if "TEST_FLAKE8_INSTALL" is set.
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ for dist in pip.utils.get_installed_distributions():
+ if dist.key == 'flake8-future-import':
+ if dist.location != os.path.dirname(os.path.abspath(__file__)):
+ raise unittest.SkipTest('The plugin is already installed '
+ 'but somewhere else.')
+ cls._installed = False
+ break
+ else:
+ if os.environ.get('TEST_FLAKE8_INSTALL') == '1':
+ output = subprocess.check_output(['python', 'setup.py',
+ 'develop'])
+ output = output.decode('utf8')
+ print('Installed package:\n\n' + output)
+ raise unittest.SkipTest('Installation not yet implemented')
+ cls._installed = True
+ else:
+ raise unittest.SkipTest('The plugin is not installed and '
+ 'TEST_FLAKE8_INSTALL not set')
+ super(Flake8TestCase, cls).setUpClass()
+
+ @classmethod
+ def tearDownClass(cls):
+ if cls._installed:
+ output = subprocess.check_output(['pip', 'uninstall',
+ 'flake8-future-import'])
+ output = output.decode('utf8')
+ print('Uninstalled package:\n\n' + output)
+ super(Flake8TestCase, cls).tearDownClass()
+
+ def test_flake8(self):
+ imported = [['unicode_literals']]
+ code = generate_code(*imported)
+ code = '#!/usr/bin/python\n# -*- coding: utf-8 -*-\n' + code
+ handle, tmp_file = tempfile.mkstemp()
+ print(tmp_file)
+ try:
+ with codecs.open(tmp_file, 'w', 'utf-8') as f:
+ f.write(code)
+ env = os.environ.copy()
+ env['PYTHONIOENCODING'] = 'utf8'
+ command = ['flake8', tmp_file]
+ p = subprocess.Popen(command, env=env, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE)
+ data_out = p.communicate()
+ finally:
+ os.close(handle)
+ os.remove(tmp_file)
+ print(data_out)
+
+
if __name__ == '__main__':
unittest.main()
|
[FEAT] Do tests directly with flake8
Instead of just calling the class or `main` it should be also run with `flake8`
in case it doesn't use the class as expected. To do that it either checks if
it's installed using `pip` in the right location. Otherwise it installs it if
`TEST_FLAKE8_INSTALL` is set to `1`. Afterwards it uninstalls it, if it wasn't
already installed.
|
xZise_flake8-future-import
|
train
|
765988dd67f3bc76bd694cec433d5b7a27b4b6b5
|
diff --git a/code/view/abstract.php b/code/view/abstract.php
index <HASH>..<HASH> 100644
--- a/code/view/abstract.php
+++ b/code/view/abstract.php
@@ -316,10 +316,6 @@ abstract class KViewAbstract extends KObject implements KViewInterface, KCommand
{
if(!$this->_model instanceof KModelInterface)
{
- if(!($this->_model instanceof KObjectIdentifier)) {
- $this->setModel($this->_model);
- }
-
$this->_model = $this->getObject($this->_model);
if(!$this->_model instanceof KModelInterface)
|
re #<I> : View idenitifier is already set through constructor.
|
timble_kodekit
|
train
|
7642cfa823782bdd10d50fa37f80c32170e4432b
|
diff --git a/core-bundle/src/Resources/contao/widgets/PageSelector.php b/core-bundle/src/Resources/contao/widgets/PageSelector.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/widgets/PageSelector.php
+++ b/core-bundle/src/Resources/contao/widgets/PageSelector.php
@@ -170,7 +170,7 @@ class PageSelector extends \Widget
);
if (count($root) === 0) {
- $root = $this->rootNodes;
+ $root = $this->User->hasAccess($this->rootNodes, 'pagemounts') ? $this->rootNodes : [];
// Hide the breadcrumb
$GLOBALS['TL_DCA']['tl_page']['list']['sorting']['breadcrumb'] = '';
|
[Core] Make sure the user has access to the root nodes set
|
contao_contao
|
train
|
51aecd2c6283667bed73c911477b09a421eb3998
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -37,6 +37,7 @@ Decidim::User.find_each(&:add_to_index_as_search_resource)
- **decidim-core**: Fix followable type for Decidim::Accountability::Result. [\#3798](https://github.com/decidim/decidim/pull/3798)
- **decidim-accountability**: Fix accountability diff renderer when a locale is missing. [\#3797](https://github.com/decidim/decidim/pull/3797)
- **decidim-core**: Don't crash when a nickname has a dot. [\#3793](https://github.com/decidim/decidim/pull/3793)
+- **decidim-core**: Don't crash when a page doesn't exist. [\#3799](https://github.com/decidim/decidim/pull/3799)
**Removed**:
diff --git a/decidim-core/app/controllers/decidim/newsletters_controller.rb b/decidim-core/app/controllers/decidim/newsletters_controller.rb
index <HASH>..<HASH> 100644
--- a/decidim-core/app/controllers/decidim/newsletters_controller.rb
+++ b/decidim-core/app/controllers/decidim/newsletters_controller.rb
@@ -13,12 +13,10 @@ module Decidim
@user = current_user
@organization = current_organization
- if newsletter.sent?
- @encrypted_token = Decidim::NewsletterEncryptor.sent_at_encrypted(@user.id, newsletter.sent_at) if @user.present?
- @body = parse_interpolations(newsletter.body[I18n.locale.to_s], @user, newsletter.id)
- else
- redirect_to "/404"
- end
+ raise ActionController::RoutingError, "Not Found" unless newsletter.sent?
+
+ @encrypted_token = Decidim::NewsletterEncryptor.sent_at_encrypted(@user.id, newsletter.sent_at) if @user.present?
+ @body = parse_interpolations(newsletter.body[I18n.locale.to_s], @user, newsletter.id)
end
def unsubscribe
diff --git a/decidim-core/app/controllers/decidim/pages_controller.rb b/decidim-core/app/controllers/decidim/pages_controller.rb
index <HASH>..<HASH> 100644
--- a/decidim-core/app/controllers/decidim/pages_controller.rb
+++ b/decidim-core/app/controllers/decidim/pages_controller.rb
@@ -19,8 +19,10 @@ module Decidim
enforce_permission_to :read, :public_page, page: page
if params[:id] == "home"
render :home
- else
+ elsif page
render :decidim_page
+ else
+ raise ActionController::RoutingError, "Not Found"
end
end
diff --git a/decidim-core/spec/controllers/newsletters_controller_spec.rb b/decidim-core/spec/controllers/newsletters_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/decidim-core/spec/controllers/newsletters_controller_spec.rb
+++ b/decidim-core/spec/controllers/newsletters_controller_spec.rb
@@ -17,9 +17,8 @@ module Decidim
let(:newsletter) { create(:newsletter, organization: organization) }
it "expect a 404 page" do
- get :show, params: { id: newsletter.id }
- expect(response.status).to eq(302)
- expect(response).to redirect_to("/404")
+ expect { get :show, params: { id: newsletter.id } }
+ .to raise_error(ActionController::RoutingError)
end
end
diff --git a/decidim-core/spec/controllers/pages_controller_spec.rb b/decidim-core/spec/controllers/pages_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/decidim-core/spec/controllers/pages_controller_spec.rb
+++ b/decidim-core/spec/controllers/pages_controller_spec.rb
@@ -36,6 +36,13 @@ module Decidim
expect(response.body).to include(page.content[I18n.locale.to_s])
end
end
+
+ context "when a page doesn't exist" do
+ it "redirects to the 404" do
+ expect { get :show, params: { id: "some-page" } }
+ .to raise_error(ActionController::RoutingError)
+ end
+ end
end
end
end
|
Don't crash when a page doesn't exist (#<I>)
* Don't crash when a page doesn't exist. Closes #<I>
* Raise error instead of redirecting to <I>
* Add CHANGELOG
|
decidim_decidim
|
train
|
f63d13ed9285d0f6aa0b7857f5749e5c35307791
|
diff --git a/profile/profile_default/static/genepattern/navigation.js b/profile/profile_default/static/genepattern/navigation.js
index <HASH>..<HASH> 100644
--- a/profile/profile_default/static/genepattern/navigation.js
+++ b/profile/profile_default/static/genepattern/navigation.js
@@ -742,14 +742,23 @@ GenePattern.notebook.buildMenu = function(widget, element, name, href, kind, ind
// Attach methods in a way that will not break when popover is hidden
element.on('shown.bs.popover', function () {
+ var viewCodeButton = element.parent().find(".gp-widget-job-view-code");
+ var newTaskDropdown = element.parent().find(".gp-widget-job-new-task");
+ var sendToExistingTask = element.parent().find('.gp-widget-job-existing-task');
+
+ // Unbind old click events so they aren't double-bound
+ viewCodeButton.unbind("click");
+ newTaskDropdown.unbind("change");
+ sendToExistingTask.unbind("change");
+
// Attach the click method to "view code"
- element.parent().find(".gp-widget-job-view-code").click(function() {
+ viewCodeButton.click(function() {
widget.codeDialog(widget.options.job, indexString);
$(".popover").popover("hide");
});
// Attach "Send to New Task" clicks
- element.parent().find(".gp-widget-job-new-task").change(function(event) {
+ newTaskDropdown.change(function(event) {
var option = $(event.target).find(":selected");
var lsid = option.attr("data-lsid");
if (lsid === undefined || lsid === null) return;
@@ -782,7 +791,6 @@ GenePattern.notebook.buildMenu = function(widget, element, name, href, kind, ind
});
// Dynamically add options to "Send to Downstream Task" dropdown
- var sendToExistingTask = element.parent().find('.gp-widget-job-existing-task');
var matchingTasks = GenePattern.notebook.taskWidgetsForKind(fixedKind);
sendToExistingTask
.empty()
|
Bug fix preventing "double pop-ups" when selecting "View Code Use"
|
genepattern_genepattern-notebook
|
train
|
1ef1eacf1759d11e54b441cfdc5a30ef5d5c0fea
|
diff --git a/src/collectors/postgres/postgres.py b/src/collectors/postgres/postgres.py
index <HASH>..<HASH> 100644
--- a/src/collectors/postgres/postgres.py
+++ b/src/collectors/postgres/postgres.py
@@ -71,11 +71,17 @@ class PostgresqlCollector(diamond.collector.Collector):
for klass in metrics.itervalues():
stat = klass(self.connections, underscore=self.config['underscore'])
stat.fetch()
- [self.publish(metric, value) for metric, value in stat if value]
+ [self.publish(metric, value) for metric, value in stat]
# Cleanup
[conn.close() for conn in self.connections.itervalues()]
+ def publish(self, metric, value, **kwargs):
+ # Don't publish empty values
+ if not value or value == '0':
+ return
+ super(PostgresqlCollector, self).publish(metric, value, **kwargs)
+
def _get_db_names(self):
query = """
SELECT datname FROM pg_database
|
Override publish method to skip falsey or 0 values
|
python-diamond_Diamond
|
train
|
c8344e49bd5d2fd7ce2e23517696e84a759160e0
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -110,13 +110,12 @@ Peer.prototype._setupData = function (event) {
var self = this
this._channel.onmessage = function (event) {
console.log('[datachannel] ' + event.data)
- self.emit('message', event.data)
try {
var message = JSON.parse(event.data)
+ self.emit('message', message)
} catch (err) {
- return
+ self.emit('message', event.data)
}
- self.emit('message:' + message.type, message.data)
}
}
|
do not emit 'message:type' events
This assumes too much about the user’s app
|
feross_simple-peer
|
train
|
a443ddc31d4cd9be380149f24ea0c9277b312499
|
diff --git a/openquake/common/record.py b/openquake/common/record.py
index <HASH>..<HASH> 100644
--- a/openquake/common/record.py
+++ b/openquake/common/record.py
@@ -432,10 +432,16 @@ class Table(collections.MutableSequence):
"""Return the i-th record"""
return self._records[i]
- def __setitem__(self, i, record):
+ def __setitem__(self, i, new_record):
"""Set the i-th record"""
- # XXX: the unique and fk dictionaries must be updated!
- self._records[i] = record
+ # TODO: the fk dictionaries must be updated!
+ # TODO: there is no unique check here!
+ for name, unique in self._unique_data.iteritems():
+ old_key = getattr(self._records[i], name)
+ new_key = getattr(new_record, name)
+ del unique.dict[old_key]
+ unique.dict[new_key] = new_record
+ self._records[i] = new_record
def __delitem__(self, i):
"""Delete the i-th record"""
diff --git a/openquake/common/records.py b/openquake/common/records.py
index <HASH>..<HASH> 100644
--- a/openquake/common/records.py
+++ b/openquake/common/records.py
@@ -252,7 +252,8 @@ class CostType(Record):
name = Field(str)
type = Field(valid.Choice('aggregated', 'per_asset', 'per_area'))
unit = Field(str)
- retrofittedType = Field(str)
+ retrofittedType = Field(valid.NoneOr(
+ valid.Choice('aggregated', 'per_asset', 'per_area')))
retrofittedUnit = Field(str)
def to_node(self):
diff --git a/openquake/common/tests/table_test.py b/openquake/common/tests/table_test.py
index <HASH>..<HASH> 100644
--- a/openquake/common/tests/table_test.py
+++ b/openquake/common/tests/table_test.py
@@ -31,5 +31,5 @@ class TableTest(unittest.TestCase):
self.assertEqual(self.t[1], ['severe'])
def test_insert_update(self):
- self.t[0][0] = 'moderate'
+ self.t[0] = records.FFLimitStateContinuous('moderate')
self.t.insert(0, records.FFLimitStateContinuous('severe'))
\ No newline at end of file
|
Added validation; improved situation about unique constraint
|
gem_oq-engine
|
train
|
9d1a832109b2c6fbe0bcc7d8e5306d0140d26a4c
|
diff --git a/src/scs_core/aws/monitor/device_monitor.py b/src/scs_core/aws/monitor/device_monitor.py
index <HASH>..<HASH> 100644
--- a/src/scs_core/aws/monitor/device_monitor.py
+++ b/src/scs_core/aws/monitor/device_monitor.py
@@ -12,6 +12,7 @@ from collections import OrderedDict
from botocore.exceptions import ClientError
from scs_core.aws.data.byline import TopicBylineGroup
+from scs_core.aws.data.email_list import EmailList
from scs_core.aws.monitor.device_tester import DeviceTester
from scs_core.aws.monitor.scs_device import SCSDevice
@@ -39,6 +40,7 @@ class DeviceMonitor(object):
self.__persistence_manager = persistence_manager
self.__email_client = email_client
self.__runtime_record = None
+ self.__email_list = EmailList.load(persistence_manager).as_json()
logging.getLogger().setLevel(logging.INFO)
@@ -116,14 +118,24 @@ class DeviceMonitor(object):
self.save_runtime_record()
def send_email_alert(self, this_dev, message):
- # TODO allow for extra recipients
+ jdict = self.__email_list.get("email_list")
+ v_list = []
+ for key, value in jdict.items():
+ if key == this_dev.device_tag:
+ if value is not None:
+ if type(value).__name__ == "list":
+ for item in value:
+ v_list.append(item)
+ else:
+ v_list.append(value)
+ break
+
+ v_list.append(self.__config.email_name)
try:
self.__email_client.send_email(
Source=self.__config.email_name,
Destination={
- 'ToAddresses': [
- self.__config.email_name,
- ]
+ 'ToAddresses': v_list
},
Message={
'Subject': {
diff --git a/src/scs_core/aws/monitor/device_monitor_conf.py b/src/scs_core/aws/monitor/device_monitor_conf.py
index <HASH>..<HASH> 100644
--- a/src/scs_core/aws/monitor/device_monitor_conf.py
+++ b/src/scs_core/aws/monitor/device_monitor_conf.py
@@ -93,6 +93,6 @@ class DeviceMonitorConf(PersistentJSONable):
# ----------------------------------------------------------------------------------------------------------------
def __str__(self, *args, **kwargs):
- return "DeviceManagerConf:{email_name:%s, unresponsive_minutes_allowed:%s, email_password:%s}" % \
+ return "DeviceMonitorConf:{email_name:%s, unresponsive_minutes_allowed:%s, email_password:%s}" % \
(DeviceMonitorConf.email_name, DeviceMonitorConf.unresponsive_minutes_allowed,
DeviceMonitorConf.email_password)
|
Device monitor now accepts any number of recipients
|
south-coast-science_scs_core
|
train
|
dcc5eaa95eb37c496787ce4ecbd760b7c66841c5
|
diff --git a/lib/6to5/transformers/destructuring.js b/lib/6to5/transformers/destructuring.js
index <HASH>..<HASH> 100644
--- a/lib/6to5/transformers/destructuring.js
+++ b/lib/6to5/transformers/destructuring.js
@@ -42,6 +42,8 @@ var pushArrayPattern = function (kind, nodes, pattern, parentId) {
if (elem.type === "Identifier") {
nodes.push(buildVariableAssign(kind, elem, newPatternId));
+ } else if (elem.type === "MemberExpression") {
+ nodes.push(buildVariableAssign(false, elem, newPatternId));
} else {
push(kind, nodes, elem, newPatternId);
}
|
support MemberExpressions in destructuring - fixes #<I>
|
babel_babel
|
train
|
9856ac7fafc358e2e558a7f9efdd90bc7a9f09c0
|
diff --git a/docs/log-files.adoc b/docs/log-files.adoc
index <HASH>..<HASH> 100644
--- a/docs/log-files.adoc
+++ b/docs/log-files.adoc
@@ -42,6 +42,7 @@ The following statuses are available:
| INVALID_VNC_REQUEST_URL | VNC request URL do not contain enough information to determine upstream host
| INVALID_VIDEO_REQUEST_URL | Video request URL do not contain enough information to determine upstream host
| INVALID_URL | Session ID does not contain information about host where it was created
+| PROXYING | Proxying Selenium request (shown in verbose mode only)
| PROXYING_TO_VNC | Starting to proxy VNC traffic
| PROXYING_VIDEO | Starting to proxy video from upstream host
| QUOTA_INFO_REQUESTED | Quota information request arrived
diff --git a/proxy.go b/proxy.go
index <HASH>..<HASH> 100644
--- a/proxy.go
+++ b/proxy.go
@@ -333,8 +333,11 @@ func proxy(r *http.Request) {
r.URL.Host = h.net()
r.URL.Path = proxyPath
fragments := strings.Split(proxyPath, "/")
- if r.Method == "DELETE" && len(fragments) == sessPart+1 {
- sess := fragments[sessPart]
+ sess := fragments[sessPart]
+ if verbose {
+ log.Printf("[%d] [-] [PROXYING] [-] [%s] [-] [%s] [%s] [-] [%s]\n", id, remote, h.net(), sess, proxyPath)
+ }
+ if r.Method == http.MethodDelete && len(fragments) == sessPart+1 {
log.Printf("[%d] [-] [SESSION_DELETED] [-] [%s] [-] [%s] [%s] [-] [-]\n", id, remote, h.net(), sess)
}
return
diff --git a/proxy_test.go b/proxy_test.go
index <HASH>..<HASH> 100644
--- a/proxy_test.go
+++ b/proxy_test.go
@@ -75,6 +75,7 @@ func init() {
srv = httptest.NewServer(mux())
listen = hostport(srv.URL)
gitRevision = "test-revision"
+ verbose = true
}
func gridrouter(p string) string {
|
Logging proxy requests in verbose mode (fixes #<I>)
|
aerokube_ggr
|
train
|
5921719e3bfc7861251c8161cfa02ab189b59015
|
diff --git a/src/Storage/Entity/ContentValuesTrait.php b/src/Storage/Entity/ContentValuesTrait.php
index <HASH>..<HASH> 100644
--- a/src/Storage/Entity/ContentValuesTrait.php
+++ b/src/Storage/Entity/ContentValuesTrait.php
@@ -487,8 +487,21 @@ trait ContentValuesTrait
}
}
- $this->taxonomy[$taxonomytype] = $value;
+ $taxonomyOptions = $this->app['config']->get('taxonomy/' . $taxonomytype . '/options');
+
+ if ($taxonomyOptions && is_array($value)) {
+ foreach ($value as $k => $v) {
+ if (isset($taxonomyOptions[$v])) {
+ $this->setTaxonomy($taxonomytype, $v, $taxonomyOptions[$v], $k);
+ }
+ }
+ } else if ($taxonomyOptions && isset($taxonomyOptions[$value])) {
+ $this->setTaxonomy($taxonomytype, $value, $taxonomyOptions[$value], 0);
+ } else {
+ $this->setTaxonomy($taxonomytype, $value, $value, 0);
+ }
}
+
unset($values['taxonomy']);
unset($values['taxonomy-order']);
}
|
Fixes #<I> by passing all the posted taxonomy values through the standard `setTaxonomy` method
|
bolt_bolt
|
train
|
2b60dd935433526172a18cc36c33f7dc21c5bde8
|
diff --git a/lib/auth/auth_with_roles.go b/lib/auth/auth_with_roles.go
index <HASH>..<HASH> 100644
--- a/lib/auth/auth_with_roles.go
+++ b/lib/auth/auth_with_roles.go
@@ -893,18 +893,6 @@ func (a *AuthWithRoles) UpsertTrustedCluster(tc services.TrustedCluster) error {
if err := a.action(defaults.Namespace, services.KindTrustedCluster, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
- if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbCreate); err != nil {
- return trace.Wrap(err)
- }
- if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbUpdate); err != nil {
- return trace.Wrap(err)
- }
- if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbCreate); err != nil {
- return trace.Wrap(err)
- }
- if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbUpdate); err != nil {
- return trace.Wrap(err)
- }
return a.authServer.UpsertTrustedCluster(tc)
}
@@ -918,12 +906,6 @@ func (a *AuthWithRoles) DeleteTrustedCluster(name string) error {
if err := a.action(defaults.Namespace, services.KindTrustedCluster, services.VerbDelete); err != nil {
return trace.Wrap(err)
}
- if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbDelete); err != nil {
- return trace.Wrap(err)
- }
- if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbDelete); err != nil {
- return trace.Wrap(err)
- }
return a.authServer.DeleteTrustedCluster(name)
}
@@ -933,12 +915,6 @@ func (a *AuthWithRoles) EnableTrustedCluster(t services.TrustedCluster) error {
if err := a.action(defaults.Namespace, services.KindTrustedCluster, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
- if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbUpdate); err != nil {
- return trace.Wrap(err)
- }
- if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbUpdate); err != nil {
- return trace.Wrap(err)
- }
return a.authServer.EnableTrustedCluster(t)
}
@@ -948,12 +924,6 @@ func (a *AuthWithRoles) DisableTrustedCluster(t services.TrustedCluster) error {
if err := a.action(defaults.Namespace, services.KindTrustedCluster, services.VerbUpdate); err != nil {
return trace.Wrap(err)
}
- if err := a.action(defaults.Namespace, services.KindCertAuthority, services.VerbUpdate); err != nil {
- return trace.Wrap(err)
- }
- if err := a.action(defaults.Namespace, services.KindReverseTunnel, services.VerbUpdate); err != nil {
- return trace.Wrap(err)
- }
return a.authServer.DisableTrustedCluster(t)
}
diff --git a/lib/web/sessions.go b/lib/web/sessions.go
index <HASH>..<HASH> 100644
--- a/lib/web/sessions.go
+++ b/lib/web/sessions.go
@@ -171,7 +171,9 @@ func (c *SessionContext) GetUserClient(site reversetunnel.RemoteSite) (auth.Clie
}
// add a closer for the underlying connection
- c.AddClosers(rConn)
+ if rConn != nil {
+ c.AddClosers(rConn)
+ }
// we'll save the remote client in our session context so we don't have to
// build a new connection next time. all remote clients will be closed when
|
Removed cert authority and reverse tunnel permission check for
trusted clusters.
|
gravitational_teleport
|
train
|
ef6b9279a4cda0bf76bf78d04e7d524e7a2b0a75
|
diff --git a/watch.go b/watch.go
index <HASH>..<HASH> 100644
--- a/watch.go
+++ b/watch.go
@@ -55,10 +55,10 @@ func (client *Client) Watch(options *WatchOptions) *Watcher {
watcher := &Watcher{
client: client,
options: options,
- Error: make(chan error),
+ Error: make(chan error, 1),
Done: make(chan *AssemblyInfo),
Change: make(chan string),
- end: make(chan bool),
+ end: make(chan bool, 1),
recentWrites: make(map[string]time.Time),
blacklist: make(map[string]bool),
}
@@ -194,12 +194,14 @@ func (watcher *Watcher) startWatcher() {
fsWatcher, err := fsnotify.NewWatcher()
if err != nil {
watcher.error(err)
+ return
}
defer fsWatcher.Close()
if err = fsWatcher.Add(watcher.options.Input); err != nil {
watcher.error(err)
+ return
}
go func() {
|
Define buffers to see errors in transloadify
|
transloadit_go-sdk
|
train
|
c3523ebe046baa6669e7f50a807d1f2f63891a51
|
diff --git a/aiounifi/controller.py b/aiounifi/controller.py
index <HASH>..<HASH> 100644
--- a/aiounifi/controller.py
+++ b/aiounifi/controller.py
@@ -158,6 +158,7 @@ class Controller:
) as res:
print(res)
if res.content_type != "application/json":
+ LOGGER.debug("Unexpected content type: %s", res)
raise ResponseError(f"Invalid content type: {res.content_type}")
response = await res.json()
|
Add debug print when receiving unexpected content type
|
Kane610_aiounifi
|
train
|
25af299e2d5c8b7cc8b6e6e5be411a0171db1cae
|
diff --git a/tests/NotificationBagTest.php b/tests/NotificationBagTest.php
index <HASH>..<HASH> 100644
--- a/tests/NotificationBagTest.php
+++ b/tests/NotificationBagTest.php
@@ -552,4 +552,19 @@ class NotificationBagTest extends PHPUnit_Framework_TestCase
$this->assertCount(0, $this->bag->all());
}
+
+ public function testsClearMethodsWhenBagIsEmpty()
+ {
+ $this->bag->clear();
+
+ $this->assertCount(0, $this->bag->all());
+
+ $this->bag->clear();
+
+ $this->assertCount(0, $this->bag->all());
+
+ $this->bag->clear('success');
+
+ $this->assertCount(0, $this->bag->get('success'));
+ }
}
\ No newline at end of file
|
Adde one more test for notification bag
|
edvinaskrucas_notification
|
train
|
c1f005f0fffd6ee2f9be63ec9b6535e9bec2ad5c
|
diff --git a/app/models/esrf_info.rb b/app/models/esrf_info.rb
index <HASH>..<HASH> 100644
--- a/app/models/esrf_info.rb
+++ b/app/models/esrf_info.rb
@@ -1,3 +1,4 @@
class EsrfInfo < ActiveRecord::Base
belongs_to :patient
+ belongs_to :prd_code
end
diff --git a/app/models/prd_code.rb b/app/models/prd_code.rb
index <HASH>..<HASH> 100644
--- a/app/models/prd_code.rb
+++ b/app/models/prd_code.rb
@@ -1,2 +1,5 @@
class PrdCode < ActiveRecord::Base
+
+ has_many :esrf_info
+
end
|
set up associations for prd codes/esrf info
|
airslie_renalware-core
|
train
|
278f9a54c60c7d35971142fbe55ecd50368fcba0
|
diff --git a/generators/email_spec/templates/email_steps.rb b/generators/email_spec/templates/email_steps.rb
index <HASH>..<HASH> 100644
--- a/generators/email_spec/templates/email_steps.rb
+++ b/generators/email_spec/templates/email_steps.rb
@@ -68,4 +68,7 @@ When %r{^"([^']*?)" opens? the email with text "([^']*?)"$} do |address, text|
open_email(address, :with_text => text)
end
+When /^I click the first link in the email$/ do
+ click_first_link_in_email
+end
|
added 'I click the first link in the email' step definition
|
email-spec_email-spec
|
train
|
af3a42082cdd0aa6b13285c6a56beb940b431e81
|
diff --git a/packages/build-tools/create-webpack-config.js b/packages/build-tools/create-webpack-config.js
index <HASH>..<HASH> 100644
--- a/packages/build-tools/create-webpack-config.js
+++ b/packages/build-tools/create-webpack-config.js
@@ -306,7 +306,7 @@ async function createWebpackConfig(buildConfig) {
],
},
{
- test: /\.(js|tsx|mjs)$/,
+ test: /\.(js|tsx|mjs|jsx)$/,
exclude: thePath => {
if (
thePath.includes('custom-elements-es5-adapter.js') ||
@@ -324,7 +324,6 @@ async function createWebpackConfig(buildConfig) {
return false;
},
use: [
- 'cache-loader',
{
loader: 'babel-loader',
options: {
@@ -337,7 +336,6 @@ async function createWebpackConfig(buildConfig) {
{
test: /\.(woff|woff2)$/,
use: [
- 'cache-loader',
{
loader: 'url-loader',
options: {
@@ -439,6 +437,8 @@ async function createWebpackConfig(buildConfig) {
new TerserPlugin({
test: /\.m?js(\?.*)?$/i,
sourceMap: config.sourceMaps,
+ cache: true,
+ parallel: true,
terserOptions: {
safari10: true,
},
|
chore: minor Webpack config updates (ex. remove cache-loader due to issues encountered when building out and testing Icon work)
|
bolt-design-system_bolt
|
train
|
f0d40b4e1fc57c82f142fb483c8b0618369b7aa7
|
diff --git a/example/shapes/main.go b/example/shapes/main.go
index <HASH>..<HASH> 100644
--- a/example/shapes/main.go
+++ b/example/shapes/main.go
@@ -27,7 +27,7 @@ const (
func update(screen *ebiten.Image) error {
for i := 0; i < 6; i++ {
- screen.DrawRect(float64(2*i), float64(2*i), 100, 100, color.NRGBA{0x80, 0x80, 0xff, 0x80})
+ screen.DrawRect(2*i, 2*i, 100, 100, color.NRGBA{0x80, 0x80, 0xff, 0x80})
}
screen.FillRect(10, 10, 100, 100, color.NRGBA{0x80, 0x80, 0xff, 0x80})
screen.FillRect(20, 20, 100, 100, color.NRGBA{0x80, 0x80, 0xff, 0x80})
diff --git a/image.go b/image.go
index <HASH>..<HASH> 100644
--- a/image.go
+++ b/image.go
@@ -108,16 +108,18 @@ func (i *Image) DrawLines(lines Lines) (err error) {
return
}
-func (i *Image) DrawRect(x, y, width, height float64, clr color.Color) error {
+// DrawRect draws a rectangle.
+func (i *Image) DrawRect(x, y, width, height int, clr color.Color) error {
return i.DrawLines(&rectsAsLines{&rect{x, y, width, height, clr}})
}
+// DrawRect draws rectangles.
func (i *Image) DrawRects(rects Rects) error {
return i.DrawLines(&rectsAsLines{rects})
}
// FillRect draws a filled rectangle.
-func (i *Image) FillRect(x, y, width, height float64, clr color.Color) error {
+func (i *Image) FillRect(x, y, width, height int, clr color.Color) error {
return i.FillRects(&rect{x, y, width, height, clr})
}
diff --git a/internal/graphics/framebuffer.go b/internal/graphics/framebuffer.go
index <HASH>..<HASH> 100644
--- a/internal/graphics/framebuffer.go
+++ b/internal/graphics/framebuffer.go
@@ -130,7 +130,7 @@ func (f *Framebuffer) DrawLines(c *opengl.Context, lines Lines) error {
type Rects interface {
Len() int
- Rect(i int) (x, y, width, height float64)
+ Rect(i int) (x, y, width, height int)
Color(i int) color.Color
}
diff --git a/internal/graphics/internal/shader/draw.go b/internal/graphics/internal/shader/draw.go
index <HASH>..<HASH> 100644
--- a/internal/graphics/internal/shader/draw.go
+++ b/internal/graphics/internal/shader/draw.go
@@ -135,7 +135,7 @@ func DrawLines(c *opengl.Context, projectionMatrix *[4][4]float64, lines Lines)
type Rects interface {
Len() int
- Rect(i int) (x, y, width, height float64)
+ Rect(i int) (x, y, width, height int)
Color(i int) color.Color
}
diff --git a/shapes.go b/shapes.go
index <HASH>..<HASH> 100644
--- a/shapes.go
+++ b/shapes.go
@@ -52,7 +52,8 @@ func (r *rectsAsLines) Len() int {
}
func (r *rectsAsLines) Points(i int) (x0, y0, x1, y1 float64) {
- x, y, w, h := r.Rects.Rect(i / 4)
+ ix, iy, iw, ih := r.Rects.Rect(i / 4)
+ x, y, w, h := float64(ix), float64(iy), float64(iw), float64(ih)
switch i % 4 {
case 0:
return x, y, x + w, y
@@ -73,13 +74,13 @@ func (r *rectsAsLines) Color(i int) color.Color {
// A Rects represents the set of rectangles.
type Rects interface {
Len() int
- Rect(i int) (x, y, width, height float64)
+ Rect(i int) (x, y, width, height int)
Color(i int) color.Color
}
type rect struct {
- x, y float64
- width, height float64
+ x, y int
+ width, height int
color color.Color
}
@@ -87,7 +88,7 @@ func (r *rect) Len() int {
return 1
}
-func (r *rect) Rect(i int) (x, y, width, height float64) {
+func (r *rect) Rect(i int) (x, y, width, height int) {
return r.x, r.y, r.width, r.height
}
|
Revert rectangles' vetices (float<I> -> int)
|
hajimehoshi_ebiten
|
train
|
b2e1c0c0458674ab5abf39d6d8d04d8e0d77d5cc
|
diff --git a/fireplace/cards/karazhan/collectible.py b/fireplace/cards/karazhan/collectible.py
index <HASH>..<HASH> 100644
--- a/fireplace/cards/karazhan/collectible.py
+++ b/fireplace/cards/karazhan/collectible.py
@@ -177,8 +177,9 @@ class KAR_075:
"Moonglade Portal"
play = Heal(TARGET, 6), Summon(CONTROLLER, RandomMinion(cost=6))
-# class KAR_076:
-# "Firelands Portal"
+class KAR_076:
+ "Firelands Portal"
+ play = Hit(TARGET, 5), Summon(CONTROLLER, RandomMinion(cost=5))
# class KAR_077:
# "Silvermoon Portal"
diff --git a/tests/test_karazhan.py b/tests/test_karazhan.py
index <HASH>..<HASH> 100644
--- a/tests/test_karazhan.py
+++ b/tests/test_karazhan.py
@@ -301,4 +301,11 @@ def test_moonglade_portal():
g.player1.hero.set_current_health(20)
g.player1.give("KAR_075").play(target=g.player1.hero)
assert len(g.player1.field) == 1
- assert g.player1.hero.health == 26
\ No newline at end of file
+ assert g.player1.hero.health == 26
+
+def test_firelands_portal():
+ g=prepare_game()
+ g.player1.give("KAR_076").play(target=g.player2.hero)
+ assert len(g.player1.field) == 1
+ assert g.player1.field[0].cost == 5
+ assert g.player2.hero.health == 25
\ No newline at end of file
|
Implement "Firelands Portal" with test
KAR_<I>
|
jleclanche_fireplace
|
train
|
d72806ca258b667f44f01e6cee70fc8a17262da1
|
diff --git a/src/Monolog/Processor/IntrospectionProcessor.php b/src/Monolog/Processor/IntrospectionProcessor.php
index <HASH>..<HASH> 100644
--- a/src/Monolog/Processor/IntrospectionProcessor.php
+++ b/src/Monolog/Processor/IntrospectionProcessor.php
@@ -93,7 +93,7 @@ class IntrospectionProcessor
private function isTraceClassOrSkippedFunction (array $trace, $index)
{
- if (isset($trace[$index]) === false) {
+ if (!isset($trace[$index])) {
return false;
}
|
Would have, could have. Why not.
|
Seldaek_monolog
|
train
|
737a62482d9892e0cce94ec698d0c25f0ea1d143
|
diff --git a/lib/core.js b/lib/core.js
index <HASH>..<HASH> 100644
--- a/lib/core.js
+++ b/lib/core.js
@@ -83,6 +83,16 @@ module.exports = function(type, properties, store) {
})
}
+ /** Find an object or make a new unsaved one if it doesn't exist
+ */
+ Model.find_or_new = function(id, cb) {
+ Model.find(id, function(m) {
+ m = m || new Model({id: id})
+ cb && cb(m)
+ })
+ }
+
+
/** @private
* Synchonize an object
* This copies the local properties onto a _private_ _.properties object
@@ -122,17 +132,9 @@ module.exports = function(type, properties, store) {
/** Update the model with the params and save it
*/
fn.update = function(params, cb) {
- params || (params == {})
-
- Model.find(params.id, function(m) {
- if(!m) {
- cb && cb()
- } else {
- m.merge(params)
- m.save(function(ok) {
- cb && cb.call(m, ok)
- })
- }
+ this.merge(params)
+ this.save(function(ok) {
+ cb && cb.call(this, ok)
})
}
@@ -196,10 +198,15 @@ module.exports = function(type, properties, store) {
/** Returns a object ready for JSON.stringify
* NB Does not return a string
* NB Date types are converted to numbers
+ * @only {Array} if passed, only these properties will be serialized
*/
- fn.toJSON = function() {
- var o = {}
+ fn.toJSON = function(opts) {
+ var o = {}, opts = opts || {}
+
for(var name in properties) {
+ if(opts.only && opts.only.indexOf(name) < 0) continue
+ if(opts.skip && opts.skip.indexOf(name) > 0) continue
+
if(name in this) {
o[name] = this[name]
if(properties[name].type == "date") o[name] = o[name]/1
diff --git a/lib/stores/redis.js b/lib/stores/redis.js
index <HASH>..<HASH> 100644
--- a/lib/stores/redis.js
+++ b/lib/stores/redis.js
@@ -99,10 +99,15 @@ exports.mixin = function(Model) {
Model.find = function(id, cb) {
- (new Model({id: id})).db("HGETALL", "", function(data) {
- if(!data || data.id == null) return cb(null)
+ if(id == null) return cb && cb(null)
+// console.log("XX", id, (new Model({id: id})).db)
+
+ var m = new Model({id: id})
+
+ m.db("HGETALL", "", function(data) {
+ if(!data || data.id == null) return cb && cb(null)
var o = Model.new_from_strings(data)
- cb(Model.load(o))
+ cb && cb(Model.load(o))
})
}
|
added skip, only option to toJSON
|
weepy_mmmodel
|
train
|
3886d68de3de7a42cf48aa8142ee613db4a623b6
|
diff --git a/physical/zookeeper.go b/physical/zookeeper.go
index <HASH>..<HASH> 100644
--- a/physical/zookeeper.go
+++ b/physical/zookeeper.go
@@ -26,7 +26,7 @@ const (
type ZookeeperBackend struct {
path string
client *zk.Conn
- acl []zk.ACL
+ acl []zk.ACL
}
// newZookeeperBackend constructs a Zookeeper backend using the given API client
@@ -53,43 +53,41 @@ func newZookeeperBackend(conf map[string]string) (Backend, error) {
machines = "localhost:2181"
}
- // zNode owner and schema.
- var owner string
- var schema string
- var schemaAndOwner string
- schemaAndOwner, ok = conf["znode_owner"]
- if !ok {
- owner = "anyone"
- schema = "world"
- } else {
- parsedSchemaAndOwner := strings.SplitN(schemaAndOwner, ":", 2)
- if !(len(parsedSchemaAndOwner)==2) {
- return nil, fmt.Errorf("znode_owner expected format is 'schema:owner'")
- } else {
- schema = parsedSchemaAndOwner[0]
- owner = parsedSchemaAndOwner[1]
- }
- }
-
- acl := []zk.ACL{{zk.PermAll, schema, owner}}
-
-
- // Authnetication info
- var schemaAndUser string
- schemaAndUser, ok = conf["auth_info"]
- if !ok {
- owner = ""
- schema = ""
- } else {
- parsedSchemaAndUser := strings.SplitN(schemaAndUser, ":", 2)
- if !(len(parsedSchemaAndUser)==2) {
- return nil, fmt.Errorf("auth_info expected format is 'schema:auth'")
- } else {
- schema = parsedSchemaAndUser[0]
- owner = parsedSchemaAndUser[1]
- }
- }
+ // zNode owner and schema.
+ var owner string
+ var schema string
+ var schemaAndOwner string
+ schemaAndOwner, ok = conf["znode_owner"]
+ if !ok {
+ owner = "anyone"
+ schema = "world"
+ } else {
+ parsedSchemaAndOwner := strings.SplitN(schemaAndOwner, ":", 2)
+ if len(parsedSchemaAndOwner) != 2 {
+ return nil, fmt.Errorf("znode_owner expected format is 'schema:owner'")
+ } else {
+ schema = parsedSchemaAndOwner[0]
+ owner = parsedSchemaAndOwner[1]
+ }
+ }
+ acl := []zk.ACL{{zk.PermAll, schema, owner}}
+
+ // Authnetication info
+ var schemaAndUser string
+ schemaAndUser, ok = conf["auth_info"]
+ if !ok {
+ owner = ""
+ schema = ""
+ } else {
+ parsedSchemaAndUser := strings.SplitN(schemaAndUser, ":", 2)
+ if len(parsedSchemaAndUser) != 2 {
+ return nil, fmt.Errorf("auth_info expected format is 'schema:auth'")
+ } else {
+ schema = parsedSchemaAndUser[0]
+ owner = parsedSchemaAndUser[1]
+ }
+ }
// Attempt to create the ZK client
client, _, err := zk.Connect(strings.Split(machines, ","), time.Second)
@@ -97,19 +95,19 @@ func newZookeeperBackend(conf map[string]string) (Backend, error) {
return nil, fmt.Errorf("client setup failed: %v", err)
}
- // If auth_info provided - attempt to authenticate
- if owner != "" {
- err = client.AddAuth(schema, []byte(owner))
- if err != nil {
- return nil, fmt.Errorf("Zookeeper rejected authentication information provided at auth_info")
- }
- }
+ // If auth_info provided - attempt to authenticate
+ if owner != "" {
+ err = client.AddAuth(schema, []byte(owner))
+ if err != nil {
+ return nil, fmt.Errorf("Zookeeper rejected authentication information provided at auth_info: %v", err)
+ }
+ }
// Setup the backend
c := &ZookeeperBackend{
path: path,
client: client,
- acl: acl,
+ acl: acl,
}
return c, nil
}
|
1. gofmt
2. Change if expr syntax to be consist with the rest of Vault code
3. More details on error message
|
hashicorp_vault
|
train
|
e4cb93f23264b1c80d45c8d6cddf0a980aa17a8d
|
diff --git a/src/javascript/file/FileInput.js b/src/javascript/file/FileInput.js
index <HASH>..<HASH> 100644
--- a/src/javascript/file/FileInput.js
+++ b/src/javascript/file/FileInput.js
@@ -198,6 +198,15 @@ define('moxie/file/FileInput', [
@type {String}
*/
ruid: null,
+
+ /**
+ Unique id of the runtime container. Useful to get hold of it for various manipulations.
+
+ @property shimid
+ @protected
+ @type {String}
+ */
+ shimid: null,
/**
Array of selected mOxie.File objects
@@ -218,6 +227,7 @@ define('moxie/file/FileInput', [
self.bind('RuntimeInit', function(e, runtime) {
self.ruid = runtime.uid;
+ self.shimid = runtime.shimid;
self.bind("Ready", function() {
self.trigger("Refresh");
|
FileInput: Expose uid of the runtime container.
Useful to get hold of it for various manipulations.
|
moxiecode_moxie
|
train
|
f2c9cc17df4c3cd84d43db0f15d9dab030b84667
|
diff --git a/src/app/components/kbn.js b/src/app/components/kbn.js
index <HASH>..<HASH> 100644
--- a/src/app/components/kbn.js
+++ b/src/app/components/kbn.js
@@ -430,28 +430,28 @@ function($, _, moment) {
ext = " B";
break;
case 1:
- ext = " KB";
+ ext = " KiB";
break;
case 2:
- ext = " MB";
+ ext = " MiB";
break;
case 3:
- ext = " GB";
+ ext = " GiB";
break;
case 4:
- ext = " TB";
+ ext = " TiB";
break;
case 5:
- ext = " PB";
+ ext = " PiB";
break;
case 6:
- ext = " EB";
+ ext = " EiB";
break;
case 7:
- ext = " ZB";
+ ext = " ZiB";
break;
case 8:
- ext = " YB";
+ ext = " YiB";
break;
}
@@ -477,28 +477,28 @@ function($, _, moment) {
ext = " b";
break;
case 1:
- ext = " Kb";
+ ext = " Kib";
break;
case 2:
- ext = " Mb";
+ ext = " Mib";
break;
case 3:
- ext = " Gb";
+ ext = " Gib";
break;
case 4:
- ext = " Tb";
+ ext = " Tib";
break;
case 5:
- ext = " Pb";
+ ext = " Pib";
break;
case 6:
- ext = " Eb";
+ ext = " Eib";
break;
case 7:
- ext = " Zb";
+ ext = " Zib";
break;
case 8:
- ext = " Yb";
+ ext = " Yib";
break;
}
diff --git a/src/app/directives/grafanaGraph.js b/src/app/directives/grafanaGraph.js
index <HASH>..<HASH> 100644
--- a/src/app/directives/grafanaGraph.js
+++ b/src/app/directives/grafanaGraph.js
@@ -248,10 +248,7 @@ function (angular, $, kbn, moment, _) {
}
function configureAxisMode(axis, format) {
- if (format === 'bytes') {
- axis.mode = 'byte';
- }
- else if (format !== 'none') {
+ if (format !== 'none') {
axis.tickFormatter = kbn.getFormatFunction(format, 1);
}
}
|
#Closes #<I>, changed byte and bit formats to conform with IEC standard symbols, like Kib, Mib for bits, and KiB, MiB, GiB for bytes
|
grafana_grafana
|
train
|
99bf386d1301b2c051e0144a00faae4ee9a5ab19
|
diff --git a/quilt_server/views.py b/quilt_server/views.py
index <HASH>..<HASH> 100644
--- a/quilt_server/views.py
+++ b/quilt_server/views.py
@@ -1131,8 +1131,20 @@ def payments_update_plan(auth_user):
except ValueError:
raise ApiException(requests.codes.bad_request, "Invalid plan: %r" % plan)
+ stripe_token = request.values.get('token')
+
customer = _get_or_create_customer()
+ if stripe_token is not None:
+ customer.source = stripe_token
+
+ try:
+ customer.save()
+ except stripe.InvalidRequestError as ex:
+ raise ApiException(requests.codes.bad_request, str(ex))
+
+ assert customer.sources.total_count
+
if plan != PaymentPlan.FREE and not customer.sources.total_count:
# No payment info.
raise ApiException(
diff --git a/tests/payments_test.py b/tests/payments_test.py
index <HASH>..<HASH> 100644
--- a/tests/payments_test.py
+++ b/tests/payments_test.py
@@ -122,6 +122,39 @@ class PaymentsTestCase(QuiltTestCase):
assert resp.status_code == requests.codes.payment_required
assert not subscription.save.called
+ @mock_customer(plan=PaymentPlan.FREE, have_credit_card=False)
+ def testUpgradeWithToken(self, customer):
+ user = 'test_user'
+ token = '12345'
+
+ def _update_source():
+ assert customer.source == token
+ # Emulate the Stripe API weirdness.
+ del customer.source
+ customer.sources.total_count = 1
+
+ customer.save.return_value = None
+ customer.save.side_effect = _update_source
+ subscription = customer.subscriptions.data[0]
+ subscription.save.return_value = None
+
+ resp = self.app.post(
+ '/api/payments/update_plan',
+ data=dict(
+ plan=PaymentPlan.INDIVIDUAL.value,
+ token=token,
+ ),
+ headers={
+ 'Authorization': user,
+ }
+ )
+ assert resp.status_code == requests.codes.ok
+
+ customer.save.assert_called_with()
+
+ assert subscription.plan == PaymentPlan.INDIVIDUAL.value
+ subscription.save.assert_called_with()
+
@mock_customer(plan=PaymentPlan.INDIVIDUAL, have_credit_card=False)
def testDowngradeNoPayment(self, customer):
user = 'test_user'
|
Make it possible to update payment and plan in a single call
|
quiltdata_quilt
|
train
|
edaad1561f854dc17cdfcd34ec4e031228d4d24f
|
diff --git a/shared/actions/notifications.js b/shared/actions/notifications.js
index <HASH>..<HASH> 100644
--- a/shared/actions/notifications.js
+++ b/shared/actions/notifications.js
@@ -75,7 +75,6 @@ function _onRecievedBadgeState(action: NotificationsGen.ReceivedBadgeStatePayloa
teamsWithResetUsers: teamsWithResetUsers || [],
})
),
- Saga.put(FsGen.createFavoritesLoad()),
])
}
|
fs: Remove favorites listing trigger from badge state notification (#<I>)
|
keybase_client
|
train
|
a3bd5fa7fef471246fe3f22983d6931bbb334dbf
|
diff --git a/docs/collectors/LoadAverageCollector.md b/docs/collectors/LoadAverageCollector.md
index <HASH>..<HASH> 100644
--- a/docs/collectors/LoadAverageCollector.md
+++ b/docs/collectors/LoadAverageCollector.md
@@ -26,8 +26,11 @@ simple | False | Only collect the 1 minute load average | str
```
servers.hostname.loadavg.01 (0.12, 2)
+servers.hostname.loadavg.01_normalized (0.06, 2)
servers.hostname.loadavg.05 (0.23, 2)
+servers.hostname.loadavg.05_normalized (0.115, 2)
servers.hostname.loadavg.15 (0.34, 2)
+servers.hostname.loadavg.15_normalized (0.17, 2)
servers.hostname.loadavg.processes_running 1
servers.hostname.loadavg.processes_total 235
```
diff --git a/src/collectors/loadavg/loadavg.py b/src/collectors/loadavg/loadavg.py
index <HASH>..<HASH> 100644
--- a/src/collectors/loadavg/loadavg.py
+++ b/src/collectors/loadavg/loadavg.py
@@ -12,6 +12,7 @@ Uses /proc/loadavg to collect data on load average
import diamond.collector
import re
import os
+import multiprocessing
from diamond.collector import str_to_bool
@@ -41,13 +42,18 @@ class LoadAverageCollector(diamond.collector.Collector):
def collect(self):
load01, load05, load15 = os.getloadavg()
+ cpu_count = multiprocessing.cpu_count()
if not str_to_bool(self.config['simple']):
self.publish_gauge('01', load01, 2)
self.publish_gauge('05', load05, 2)
self.publish_gauge('15', load15, 2)
+ self.publish_gauge('01_normalized', load01 / cpu_count, 2)
+ self.publish_gauge('05_normalized', load05 / cpu_count, 2)
+ self.publish_gauge('15_normalized', load15 / cpu_count, 2)
else:
self.publish_gauge('load', load01, 2)
+ self.publish_gauge('load_normalized', load01 / cpu_count, 2)
# Legacy: add process/thread counters provided by
# /proc/loadavg (if available).
diff --git a/src/collectors/loadavg/test/testloadavg.py b/src/collectors/loadavg/test/testloadavg.py
index <HASH>..<HASH> 100644
--- a/src/collectors/loadavg/test/testloadavg.py
+++ b/src/collectors/loadavg/test/testloadavg.py
@@ -44,17 +44,23 @@ class TestLoadAverageCollector(CollectorTestCase):
self.collector.collect()
open_mock.assert_called_once_with('/proc/loadavg')
+ @patch('multiprocessing.cpu_count')
@patch('os.getloadavg')
@patch.object(Collector, 'publish')
- def test_should_work_with_real_data(self, publish_mock, getloadavg_mock):
+ def test_should_work_with_real_data(self, publish_mock, getloadavg_mock,
+ cpu_count_mock):
LoadAverageCollector.PROC_LOADAVG = self.getFixturePath('proc_loadavg')
getloadavg_mock.return_value = (0.12, 0.23, 0.34)
+ cpu_count_mock.return_value = 2
self.collector.collect()
metrics = {
'01': (0.12, 2),
'05': (0.23, 2),
'15': (0.34, 2),
+ '01_normalized': (0.06, 2),
+ '05_normalized': (0.115, 2),
+ '15_normalized': (0.17, 2),
'processes_running': 1,
'processes_total': 235
}
|
Add `_normalized` metrics for loadaverage
Normalized is the load average divided by the number of CPU's
A normalized load average of 1 = all CPU's at <I>% usage
|
python-diamond_Diamond
|
train
|
9fd4d3c008eaa8bf9de767ca4afef57295474e96
|
diff --git a/Password/Simple.php b/Password/Simple.php
index <HASH>..<HASH> 100644
--- a/Password/Simple.php
+++ b/Password/Simple.php
@@ -142,7 +142,7 @@ class Simple implements PasswordInterface
}
// Check if the hash is a Joomla hash.
- if (preg_match('#[a-z0-9]{32}:[A-Za-z0-9]{32}#', $hash) === 1)
+ if (preg_match('#[a-z0-9]{32}:[./A-Za-z0-9]{32}#', $hash) === 1)
{
return md5($password . substr($hash, 33)) == substr($hash, 0, 32);
}
|
Fix verify hash to properly recognize Joomla password hashes
|
joomla-framework_crypt
|
train
|
eb36c1aadc704e02d84c0fe5b6ea0269deef7870
|
diff --git a/go/libkb/features.go b/go/libkb/features.go
index <HASH>..<HASH> 100644
--- a/go/libkb/features.go
+++ b/go/libkb/features.go
@@ -156,6 +156,14 @@ func (s *FeatureFlagSet) EnabledWithError(m MetaContext, f Feature) (on bool, er
"features": S{Val: string(f)},
}
err = m.G().API.GetDecode(m, arg, &raw)
+ switch err.(type) {
+ case nil:
+ case LoginRequiredError:
+ // No features for logged-out users
+ return false, nil
+ default:
+ return false, err
+ }
if err != nil {
return false, err
}
|
no features for logged-out users (#<I>)
|
keybase_client
|
train
|
4e551d1d155cecb523c7026f8d98712cffc707c4
|
diff --git a/packages/scroll-pane/ScrollPane.js b/packages/scroll-pane/ScrollPane.js
index <HASH>..<HASH> 100644
--- a/packages/scroll-pane/ScrollPane.js
+++ b/packages/scroll-pane/ScrollPane.js
@@ -190,6 +190,7 @@ class ScrollPane extends Component {
let mouseBounds = getRelativeMouseBounds(e, contentContainerEl)
let contextMenu = this.refs.contextMenu
contextMenu.show(mouseBounds)
+ this.refs.scrollbar.updatePositions()
}
/**
|
Update scrollbar whenever a context menu has been opened.
|
substance_substance
|
train
|
11b919ab4933936a28fb6aeda5c6523091266f37
|
diff --git a/export.go b/export.go
index <HASH>..<HASH> 100644
--- a/export.go
+++ b/export.go
@@ -8,7 +8,7 @@ import (
"net/mail"
"time"
- "gopkg.in/alexcesaro/quotedprintable.v1"
+ "gopkg.in/alexcesaro/quotedprintable.v2"
)
// Export converts the message into a net/mail.Message.
|
remove dependency to quotedprintable.v1
since the v2 is already used in gomail.go
Closes #<I>.
|
go-gomail_gomail
|
train
|
f918de6a4636f0b91b4ff35493a4b7291463da57
|
diff --git a/lib/koala/uploadable_io.rb b/lib/koala/uploadable_io.rb
index <HASH>..<HASH> 100644
--- a/lib/koala/uploadable_io.rb
+++ b/lib/koala/uploadable_io.rb
@@ -95,7 +95,7 @@ module Koala
def use_simple_detection(filename)
# very rudimentary extension analysis for images
# first, get the downcased extension, or an empty string if it doesn't exist
- extension = ((filename.match(/\.([a-zA-Z0-9]+)/) || [])[1] || "").downcase
+ extension = ((filename.match(/\.([a-zA-Z0-9]+)$/) || [])[1] || "").downcase
if extension == ""
nil
elsif extension == "jpg" || extension == "jpeg"
diff --git a/spec/koala/uploadable_io/uploadable_io_tests.rb b/spec/koala/uploadable_io/uploadable_io_tests.rb
index <HASH>..<HASH> 100644
--- a/spec/koala/uploadable_io/uploadable_io_tests.rb
+++ b/spec/koala/uploadable_io/uploadable_io_tests.rb
@@ -141,6 +141,10 @@ class UploadableIOTests < Test::Unit::TestCase
it "should properly get content types for #{extension} using basic analysis" do
UploadableIO.new("filename.#{extension}").content_type.should == mime_type
end
+
+ it "should get content types for #{extension} using basic analysis with file names with more than one dot" do
+ UploadableIO.new("path/to/file.name.#{extension}").content_type.should == mime_type
+ end
end
it "should throw an exception if the MIME type can't be determined" do
|
Adding support for mime parsing of filename with more than one dot
|
arsduo_koala
|
train
|
2a0253ba936c7d9afdb538d9f43540473244cdfa
|
diff --git a/src/Exportable.php b/src/Exportable.php
index <HASH>..<HASH> 100644
--- a/src/Exportable.php
+++ b/src/Exportable.php
@@ -103,6 +103,8 @@ trait Exportable
$this->writeRowsFromCollection($writer, $collection, $callback);
} elseif ($collection instanceof Generator) {
$this->writeRowsFromGenerator($writer, $collection);
+ } elseif (is_array($collection)) {
+ $this->writeRowsFromArray($writer, $collection, $callback);
}
if (is_string($key)) {
$writer->getCurrentSheet()->setName($key);
@@ -146,6 +148,16 @@ trait Exportable
}
}
+ private function writeRowsFromArray($writer, array $array, $callback)
+ {
+ $collection = collect($array);
+
+ if (is_object($collection->first()) || is_array($collection->first())) {
+ // provided $array was valid and could be converted to a collection
+ $this->writeRowsFromCollection($writer, $collection, $callback);
+ }
+ }
+
private function writeHeader($writer, $first_row)
{
if ($first_row === null) {
|
add support for array as input (#<I>)
|
rap2hpoutre_fast-excel
|
train
|
a8a406290b813afc37d3f9fcddc5e562632a6396
|
diff --git a/dashboard-mongo/src/main/java/com/xqbase/metric/dashboard/DashboardApi.java b/dashboard-mongo/src/main/java/com/xqbase/metric/dashboard/DashboardApi.java
index <HASH>..<HASH> 100644
--- a/dashboard-mongo/src/main/java/com/xqbase/metric/dashboard/DashboardApi.java
+++ b/dashboard-mongo/src/main/java/com/xqbase/metric/dashboard/DashboardApi.java
@@ -137,8 +137,7 @@ public class DashboardApi extends HttpServlet {
private static double getDouble(Document row, String key) {
Object value = row.get(key);
- double d = value instanceof Number ? ((Number) value).doubleValue() : 0;
- return Double.isFinite(d) ? d : 0;
+ return value instanceof Number ? ((Number) value).doubleValue() : 0;
}
private static String getString(Document row, String key) {
|
Infinity aggregation bugfix
|
xqbase_metric
|
train
|
e4d6c35a77e9a4af4472e25c2547e096a86a6324
|
diff --git a/lib/jenkins_api_client/build_queue.rb b/lib/jenkins_api_client/build_queue.rb
index <HASH>..<HASH> 100644
--- a/lib/jenkins_api_client/build_queue.rb
+++ b/lib/jenkins_api_client/build_queue.rb
@@ -48,18 +48,31 @@ module JenkinsApi
#
def list_tasks
response_json = @client.api_get_request("/queue")
- puts response_json
tasks = []
- unless response_json["items"].empty?
- response_json["items"].each do |item|
- tasks << item["task"]["name"]
- end
+ response_json["items"].each do |item|
+ tasks << item["task"]["name"]
end
tasks
end
+ def get_age(task_name)
+ age = nil
+ details = get_details(task_name)
+ unless details.empty?
+ age = Time.now - Time.at(details["inQueueSince"].to_i/1000)
+ end
+ age
+ end
+
+ def get_details(task_name)
+ response_json = @client.api_get_request("/queue")
+ details = {}
+ response_json["items"].each do |item|
+ details = item if item["task"]["name"]
+ end
+ details
+ end
+
end
end
end
-
-
|
[BuildQueue] added get_age and get_details
|
arangamani_jenkins_api_client
|
train
|
ec2eaf720bd15f61206d6c7abe09b641253b7923
|
diff --git a/sitetree/sitetreeapp.py b/sitetree/sitetreeapp.py
index <HASH>..<HASH> 100644
--- a/sitetree/sitetreeapp.py
+++ b/sitetree/sitetreeapp.py
@@ -200,7 +200,7 @@ def register_dynamic_trees(trees, *args, **kwargs):
trees = [trees]
trees.extend(args)
- for tree in trees:
+ for tree in trees or []:
if tree is not None and tree['sitetrees'] is not None:
if tree['tree'] is None:
# Register trees as they are defined in app.
|
register_dynamic_trees() now handles non-iterables in 'trees' arg.
|
idlesign_django-sitetree
|
train
|
d66da1078acc072c19188b54dcfc68eab0adcdbf
|
diff --git a/tests/test_equations.py b/tests/test_equations.py
index <HASH>..<HASH> 100644
--- a/tests/test_equations.py
+++ b/tests/test_equations.py
@@ -43,10 +43,10 @@ class Test_starLuminosity(unittest.TestCase):
R_s = 1 * aq.R_s
T_eff_s = 5780 * pq.degK
- answer = 3.891440112409585e+26 * pq.W
+ answer = 3.89144e+26 * pq.W
result = starLuminosity(R_s, T_eff_s)
- self.assertEqual(answer, result)
+ self.assertAlmostEqual(answer, result, delta=0.0001e27)
class Test_ratioTerminatorToStar(unittest.TestCase):
|
changed aserrtequal to almost equal for float test on sun
|
ryanvarley_ExoData
|
train
|
7e2520c02aeefec6681dcc23094f9dba39086e23
|
diff --git a/dvc/parsing/__init__.py b/dvc/parsing/__init__.py
index <HASH>..<HASH> 100644
--- a/dvc/parsing/__init__.py
+++ b/dvc/parsing/__init__.py
@@ -246,11 +246,6 @@ class EntryDefinition:
definition = deepcopy(self.definition)
wdir = self._resolve_wdir(context, name, definition.get(WDIR_KWD))
- if self.wdir != wdir:
- logger.debug(
- "Stage %s has different wdir than dvc.yaml file", name
- )
-
vars_ = definition.pop(VARS_KWD, [])
# FIXME: Should `vars` be templatized?
check_interpolations(vars_, f"{self.where}.{name}.vars", self.relpath)
diff --git a/dvc/stage/__init__.py b/dvc/stage/__init__.py
index <HASH>..<HASH> 100644
--- a/dvc/stage/__init__.py
+++ b/dvc/stage/__init__.py
@@ -257,10 +257,7 @@ class Stage(params.StageParams):
if self.is_callback:
logger.debug(
- '%s is a "callback" stage '
- "(has a command and no dependencies) and thus always "
- "considered as changed.",
- self,
+ "%s has a command but no dependencies", self.addressing
)
return True
diff --git a/dvc/stage/loader.py b/dvc/stage/loader.py
index <HASH>..<HASH> 100644
--- a/dvc/stage/loader.py
+++ b/dvc/stage/loader.py
@@ -3,7 +3,7 @@ from collections.abc import Mapping
from copy import deepcopy
from itertools import chain
-from funcy import cached_property, get_in, lcat, project
+from funcy import cached_property, get_in, lcat, once, project
from dvc import dependency, output
from dvc.hash_info import HashInfo
@@ -24,13 +24,19 @@ class StageLoader(Mapping):
self.data = data or {}
self.stages_data = self.data.get("stages", {})
self.repo = self.dvcfile.repo
- self.lockfile_data = lockfile_data or {}
+ self._lockfile_data = lockfile_data or {}
@cached_property
def resolver(self):
wdir = PathInfo(self.dvcfile.path).parent
return DataResolver(self.repo, wdir, self.data)
+ @cached_property
+ def lockfile_data(self):
+ if not self._lockfile_data:
+ logger.debug("Lockfile for '%s' not found", self.dvcfile.relpath)
+ return self._lockfile_data
+
@staticmethod
def fill_from_lock(stage, lock_data=None):
"""Fill values for params, checksums for outs and deps from lock."""
@@ -88,6 +94,14 @@ class StageLoader(Mapping):
cls.fill_from_lock(stage, lock_data)
return stage
+ @once
+ def lockfile_needs_update(self):
+ # if lockfile does not have all of the entries that dvc.yaml says it
+ # should have, provide a debug message once
+ # pylint: disable=protected-access
+ lockfile = self.dvcfile._lockfile.relpath
+ logger.debug("Lockfile '%s' needs to be updated.", lockfile)
+
def __getitem__(self, name):
if not name:
raise StageNameUnspecified(self.dvcfile)
@@ -97,8 +111,9 @@ class StageLoader(Mapping):
except EntryNotFound:
raise StageNotFound(self.dvcfile, name)
- if not self.lockfile_data.get(name):
- logger.debug(
+ if self.lockfile_data and name not in self.lockfile_data:
+ self.lockfile_needs_update()
+ logger.trace( # type: ignore[attr-defined]
"No lock entry found for '%s:%s'", self.dvcfile.relpath, name,
)
|
Cleanup debug log messages when loading stages (#<I>)
* Cleanup log messages when loading stages
1. Simplified callback stage debug message
2. Reduced no lock entry message to trace
If lockfile does not have some entry, it will simply complain
that lockfile is not uptodate once.
If there is no lockfile or empty lockfile, it will complain that
lockfile not found.
3. Annoying parametrization related wdir-interpolated debug message
removed.
* Update dvc/stage/__init__.py
* black
|
iterative_dvc
|
train
|
114ca57746d334228c6674bbf59fd89915a185c0
|
diff --git a/lib/fakefs/file.rb b/lib/fakefs/file.rb
index <HASH>..<HASH> 100644
--- a/lib/fakefs/file.rb
+++ b/lib/fakefs/file.rb
@@ -35,6 +35,10 @@ module FakeFS
RealFile.join(parts)
end
+ def self.path(file)
+ RealFile.path(file)
+ end
+
def self.exist?(path)
if File.symlink?(path)
referent = File.expand_path(File.readlink(path), File.dirname(path))
diff --git a/test/file/stat_test.rb b/test/file/stat_test.rb
index <HASH>..<HASH> 100644
--- a/test/file/stat_test.rb
+++ b/test/file/stat_test.rb
@@ -155,4 +155,13 @@ class FileStatTest < Minitest::Test
refute File.respond_to?(:realdirpath)
end
end
+
+ def test_file_path_exists
+ assert File.respond_to?(:path)
+ end
+
+ def test_file_path_returns_correct_path
+ assert File::path('/temp/test_file') == '/temp/test_file'
+ end
+
end
|
Added fake File.path() method with a test for method existance and a test for returning correct value
|
fakefs_fakefs
|
train
|
49508a39858c93ff0fc1ef7161fb58062c0d8f55
|
diff --git a/autofit/optimize/non_linear/paths.py b/autofit/optimize/non_linear/paths.py
index <HASH>..<HASH> 100644
--- a/autofit/optimize/non_linear/paths.py
+++ b/autofit/optimize/non_linear/paths.py
@@ -181,11 +181,11 @@ class Paths:
"""
return "{}pdf/".format(self.image_path)
- def make_optimizer_pickle_path(self) -> str:
+ def make_non_linear_pickle_path(self) -> str:
"""
Create the path at which the optimizer pickle should be saved
"""
- return "{}/optimizer.pickle".format(self.make_path())
+ return "{}/non_linear.pickle".format(self.make_path())
def make_model_pickle_path(self):
"""
diff --git a/autofit/tools/phase.py b/autofit/tools/phase.py
index <HASH>..<HASH> 100644
--- a/autofit/tools/phase.py
+++ b/autofit/tools/phase.py
@@ -161,7 +161,7 @@ class AbstractPhase:
"""
Save the optimizer associated with the phase as a pickle
"""
- with open(self.paths.make_optimizer_pickle_path(), "w+b") as f:
+ with open(self.paths.make_non_linear_pickle_path(), "w+b") as f:
f.write(pickle.dumps(self.optimizer))
with open(self.paths.make_model_pickle_path(), "w+b") as f:
f.write(pickle.dumps(self.model))
@@ -175,7 +175,7 @@ class AbstractPhase:
-------
exc.PipelineException
"""
- path = self.paths.make_optimizer_pickle_path()
+ path = self.paths.make_non_linear_pickle_path()
if os.path.exists(path):
with open(path, "r+b") as f:
loaded_optimizer = pickle.loads(f.read())
|
optimizer pickle renamed to non linear pickle
|
rhayes777_PyAutoFit
|
train
|
9a74fa53c0e737e4f6d0b5348e62a5f225d97327
|
diff --git a/rdopkg/guess.py b/rdopkg/guess.py
index <HASH>..<HASH> 100644
--- a/rdopkg/guess.py
+++ b/rdopkg/guess.py
@@ -2,11 +2,10 @@ import os
import re
import exception
-from utils.cmd import run, git, GerritQuery
+from utils.cmd import git, GerritQuery
from utils import specfile
from utils import log
from rdopkg.actionmods import rdoinfo
-from rdopkg.conf import cfg
def package(default=exception.CantGuess):
|
lint - F<I> imported but unused in guess.py
Change-Id: I<I>bbe<I>f<I>ede<I>a<I>faf<I>eb3e0f4
|
softwarefactory-project_rdopkg
|
train
|
2f2b66e21f2c2e8c41377aee1335134f7b81c938
|
diff --git a/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/MetricsServiceImpl.java b/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/MetricsServiceImpl.java
index <HASH>..<HASH> 100644
--- a/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/MetricsServiceImpl.java
+++ b/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/MetricsServiceImpl.java
@@ -1097,8 +1097,12 @@ public class MetricsServiceImpl implements MetricsService {
Observable<Void> result = dataAccess.getMetricTags(id)
.map(row -> row.getMap(0, String.class, String.class))
.defaultIfEmpty(new HashMap<>())
- .flatMap(map -> dataAccess.deleteFromMetricsTagsIndex(id, map))
- .map(r -> null);
+ .flatMap(map -> {
+ if (map.isEmpty()) {
+ return Observable.empty();
+ }
+ return dataAccess.deleteFromMetricsTagsIndex(id, map).map(r -> null);
+ });
result = result.mergeWith(dataAccess.deleteMetricFromMetricsIndex(id).map(r -> null))
.mergeWith(dataAccess.deleteMetricData(id).map(r -> null))
.mergeWith(dataAccess.deleteMetricFromRetentionIndex(id).map(r -> null))
diff --git a/core/metrics-core-service/src/test/java/org/hawkular/metrics/core/service/metrics/MixedMetricsITest.java b/core/metrics-core-service/src/test/java/org/hawkular/metrics/core/service/metrics/MixedMetricsITest.java
index <HASH>..<HASH> 100644
--- a/core/metrics-core-service/src/test/java/org/hawkular/metrics/core/service/metrics/MixedMetricsITest.java
+++ b/core/metrics-core-service/src/test/java/org/hawkular/metrics/core/service/metrics/MixedMetricsITest.java
@@ -322,7 +322,7 @@ public class MixedMetricsITest extends BaseMetricsITest {
Map<String, String> actualTags = metricsService.getMetricTags(mId).toBlocking().lastOrDefault(null);
assertEquals(actualTags, m.getTags());
- doAction(() -> metricsService.deleteMetric(mId));
+ metricsService.deleteMetric(mId).toBlocking().lastOrDefault(null);
deletedMetrics.add(m);
for (Metric<T> checkMetric : mList) {
|
[HWKMETRICS-<I>] Attempt to fix MixedMetricsITest failures due to changes to delete metric implementation.
|
hawkular_hawkular-metrics
|
train
|
3975885dad0d4f5720f6c6cf28c3ca1d446c310c
|
diff --git a/src/Decorator/DecoratorManager.php b/src/Decorator/DecoratorManager.php
index <HASH>..<HASH> 100644
--- a/src/Decorator/DecoratorManager.php
+++ b/src/Decorator/DecoratorManager.php
@@ -27,10 +27,11 @@ class DecoratorManager
{
$decorators = $this->decorators[$type] ?? [];
- /** @var IDecorator $decorator */
foreach ($decorators as $decorator) {
/** @var ServerRequestInterface|null $request */
$request = $decorator->decorate($request, $response, $context);
+
+ if ($request === null) return null; // Cannot pass null to next decorator
}
return $request;
@@ -46,10 +47,11 @@ class DecoratorManager
// If there is no exception handler defined so return null (and exception will be thrown in DecoratedDispatcher)
if ($type === IDecorator::ON_DISPATCHER_EXCEPTION && $decorators === []) return null;
- /** @var IDecorator $decorator */
foreach ($decorators as $decorator) {
/** @var ResponseInterface|null $response */
$response = $decorator->decorate($request, $response, $context);
+
+ if ($response === null) return null; // Cannot pass null to next decorator
}
return $response;
|
Cannot pass null to next decorator - IDecorator do not accept it
|
apitte_core
|
train
|
8713f859a44b5d91b49b81f8ad4a87cd867a21cf
|
diff --git a/selene/core/match.py b/selene/core/match.py
index <HASH>..<HASH> 100644
--- a/selene/core/match.py
+++ b/selene/core/match.py
@@ -22,15 +22,15 @@
import warnings
from typing import List, Any
-from selene.core import query
from selene.common import predicate
+from selene.core import query
from selene.core.condition import Condition
-from selene.core.entity import Collection, Element, Browser
from selene.core.conditions import (
ElementCondition,
CollectionCondition,
BrowserCondition,
)
+from selene.core.entity import Collection, Element, Browser
# todo: consider moving to selene.match.element.is_visible, etc...
element_is_visible: Condition[Element] = ElementCondition.raise_if_not(
@@ -464,7 +464,8 @@ def browser_has_tabs_number_less_than_or_equal(
def browser_has_js_returned(
- expected: Any, script: str, *args) -> Condition[Browser]:
+ expected: Any, script: str, *args
+) -> Condition[Browser]:
def script_result(browser: Browser):
return browser.driver.execute_script(script, *args)
|
fix selene/core/match.py:<I>:5: E<I> continuation line with same indent as next logical line
|
yashaka_selene
|
train
|
5a66d2c51582dae83a3287dc141b8cc74b6c534a
|
diff --git a/lib/assets/Asset.js b/lib/assets/Asset.js
index <HASH>..<HASH> 100644
--- a/lib/assets/Asset.js
+++ b/lib/assets/Asset.js
@@ -439,10 +439,11 @@ extendWithGettersAndSetters(Asset.prototype, {
delete this._rawSrc; // Hmm, this doesn't make sense for assets.Asset, now does it?
if (this.isInline && this.assetGraph) {
// Cascade dirtiness to containing asset and re-inline
- if (this.incomingRelations.length !== 1) {
- throw new Error("Asset.markDirty assertion error: Expected exactly one incoming relation to inline asset, but found " + this.incomingRelations.length);
+ if (this.incomingRelations.length > 1) {
+ throw new Error("Asset.markDirty assertion error: Expected a maximum of one incoming relation to inline asset, but found " + this.incomingRelations.length);
+ } else if (this.incomingRelations.length === 1) {
+ this.incomingRelations[0].inline();
}
- this.incomingRelations[0].inline();
}
return this;
},
|
Asset.markDirty: Also allow inline assets to have zero incoming relations, as long as they don't have more than one we'll be fine.
|
assetgraph_assetgraph
|
train
|
18b5c4a29e7c07d52e0551e5866f9285e7eadd81
|
diff --git a/tests/e2e/conftest.py b/tests/e2e/conftest.py
index <HASH>..<HASH> 100644
--- a/tests/e2e/conftest.py
+++ b/tests/e2e/conftest.py
@@ -99,11 +99,15 @@ def pytest_generate_tests(metafunc):
test is called once for each value found in the `E2E_WEBDRIVER_BROWSERS`
environment variable.
"""
+ browsers = os.environ.get('E2E_WEBDRIVER_BROWSERS', '').split()
+
+ if not browsers:
+ pytest.skip('E2E_WEBDRIVER_BROWSERS not set, '
+ 'end-to-end tests skipped.')
+
if 'env_browser' in metafunc.fixturenames:
# In Python 2.7 the fallback kwarg of os.environ.get is `failobj`,
# in 3.x it's `default`.
- browsers = os.environ.get('E2E_WEBDRIVER_BROWSERS',
- 'Firefox').split()
metafunc.parametrize('env_browser', browsers, indirect=True)
@@ -115,9 +119,6 @@ def env_browser(request):
number of seconds specified by the ``E2E_WEBDRIVER_TIMEOUT`` variable or
defaults to 300 (five minutes).
"""
- if not request.param:
- pytest.skip('Empty value in E2E_WEBDRIVER_BROWSERS.')
-
timeout = int(os.environ.get('E2E_WEBDRIVER_TIMEOUT', 300))
def wait_kill():
|
tests: E2E tests disabled locally by default
* Disables E2E tests locally by default. They can still be run by
setting E2E_WEBDRIVER_BROWSERS.
|
inveniosoftware_invenio-accounts
|
train
|
2e0e135ab868d52304477f12f408c17fdb3c5483
|
diff --git a/cnxpublishing/db.py b/cnxpublishing/db.py
index <HASH>..<HASH> 100644
--- a/cnxpublishing/db.py
+++ b/cnxpublishing/db.py
@@ -645,7 +645,7 @@ RETURNING id
def _check_pending_document_license_state(cursor, document_id):
"""Check the aggregate state on the pending document."""
cursor.execute("""\
-SELECT bool_and(accepted)
+SELECT BOOL_AND(accepted IS TRUE)
FROM
pending_documents AS pd,
license_acceptances AS la
@@ -656,7 +656,7 @@ WHERE
(document_id,))
try:
is_accepted = cursor.fetchone()[0]
- except IndexError:
+ except TypeError:
# There are no licenses associated with this document.
is_accepted = True
return is_accepted
@@ -665,7 +665,7 @@ WHERE
def _check_pending_document_role_state(cursor, document_id):
"""Check the aggregate state on the pending document."""
cursor.execute("""\
-SELECT bool_and(accepted)
+SELECT BOOL_AND(accepted IS TRUE)
FROM
role_acceptances AS ra,
pending_documents as pd
@@ -676,8 +676,8 @@ WHERE
(document_id,))
try:
is_accepted = cursor.fetchone()[0]
- except IndexError:
- # There are no licenses associated with this document.
+ except TypeError:
+ # There are no roles to accept
is_accepted = True
return is_accepted
diff --git a/cnxpublishing/tests/test_views.py b/cnxpublishing/tests/test_views.py
index <HASH>..<HASH> 100644
--- a/cnxpublishing/tests/test_views.py
+++ b/cnxpublishing/tests/test_views.py
@@ -1489,3 +1489,78 @@ WHERE portal_type = 'Collection'""")
self.assertEqual(len(epub_content), len(epub_in_db))
self.assertEqual(epub_content, epub_in_db)
+
+ def test_new_to_publication_license_not_accepted(self):
+ """Publish documents only after all users have accepted the license"""
+ publisher = u'ream'
+ # We use the REVISED_BOOK here, because it contains fixed identifiers.
+ epub_filepath = self.make_epub(use_cases.REVISED_BOOK, publisher,
+ u'públishing this book')
+ api_key = self.api_keys_by_uid['some-trust']
+ api_key_headers = [('x-api-key', api_key,)]
+
+ # Give publisher permission to publish
+ from cnxarchive.utils import split_ident_hash
+ ids = [
+ split_ident_hash(use_cases.REVISED_BOOK.id)[0],
+ split_ident_hash(use_cases.REVISED_BOOK[0][0].id)[0],
+ ]
+ for id in ids:
+ resp = self.app_post_acl(
+ id, [{'uid': publisher, 'permission': 'publish'}],
+ headers=api_key_headers)
+
+ attr_role_key_to_db_role = {
+ 'publishers': 'Publisher', 'copyright_holders': 'Copyright Holder',
+ 'editors': 'Editor', 'illustrators': 'Illustrator',
+ 'translators': 'Translator', 'authors': 'Author',
+ }
+ for model in (use_cases.REVISED_BOOK, use_cases.REVISED_BOOK[0][0],):
+ id = split_ident_hash(model.id)[0]
+ attributed_roles = []
+ roles = []
+ for role_key in cnxepub.ATTRIBUTED_ROLE_KEYS:
+ for role in model.metadata.get(role_key, []):
+ role_name = attr_role_key_to_db_role[role_key]
+ attributed_roles.append({'uid': role['id'],
+ 'role': role_name,
+ 'has_accepted': True})
+ if role['id'] not in [r['uid'] for r in roles]:
+ roles.append({'uid': role['id'], 'has_accepted': True})
+ # Post the accepted attributed roles.
+ path = "/contents/{}/roles".format(id)
+ self.app.post_json(path, attributed_roles,
+ headers=api_key_headers)
+ # Post the accepted licensors. (everyone except one)
+ path = "/contents/{}/licensors".format(id)
+ data = {'license_url': 'http://creativecommons.org/licenses/by/4.0/',
+ 'licensors': roles[:-1],
+ }
+ self.app.post_json(path, data, headers=api_key_headers)
+
+ # Check publication state
+ resp = self.app_post_publication(epub_filepath,
+ headers=api_key_headers)
+ self.assertEqual(resp.json['state'], 'Waiting for acceptance')
+ publication_id = resp.json['publication']
+
+ # Post the last accepted licensor.
+ for model in (use_cases.REVISED_BOOK, use_cases.REVISED_BOOK[0][0],):
+ id = split_ident_hash(model.id)[0]
+ path = "/contents/{}/licensors".format(id)
+ data = {'license_url': 'http://creativecommons.org/licenses/by/4.0/',
+ 'licensors': [roles[-1]],
+ }
+ self.app.post_json(path, data, headers=api_key_headers)
+
+ # Check publication state
+ resp = self.app_post_publication(epub_filepath,
+ headers=api_key_headers)
+ self.assertEqual(resp.json['state'], 'Done/Success')
+ publication_id = resp.json['publication']
+
+ # *. --
+ # This is publication completion,
+ # because all licenses and roles have been accepted.
+ self.app_check_state(publication_id, 'Done/Success',
+ headers=api_key_headers)
|
Publish documents only if all users have accepted the license
The original code for checking the state of license acceptance was
```
SELECT bool_and(accepted)
FROM
pending_documents AS pd,
license_acceptances AS la
WHERE
pd.id = %s
AND
pd.uuid = la.uuid
```
which returns true if accepted is true and null. This means cnx-publishing was
publishing content even if some users have not accepted the license.
Close #<I>
|
openstax_cnx-publishing
|
train
|
4f3aa431392e3c01ba67d4b33149a2c8f8bedd62
|
diff --git a/tests/providers/google/cloud/operators/test_datastore_system.py b/tests/providers/google/cloud/operators/test_datastore_system.py
index <HASH>..<HASH> 100644
--- a/tests/providers/google/cloud/operators/test_datastore_system.py
+++ b/tests/providers/google/cloud/operators/test_datastore_system.py
@@ -31,7 +31,7 @@ class GcpDatastoreSystemTest(GoogleSystemTest):
@provide_gcp_context(GCP_DATASTORE_KEY)
def setUp(self):
super().setUp()
- self.create_gcs_bucket(BUCKET, location="europe-north1")
+ self.create_gcs_bucket(BUCKET, location="europe-central2")
@provide_gcp_context(GCP_DATASTORE_KEY)
def tearDown(self):
|
Change location of bucket creation for Datastore (#<I>)
|
apache_airflow
|
train
|
99fa0c26aa30370c1c2f28ad370adbccb7ed70da
|
diff --git a/client.go b/client.go
index <HASH>..<HASH> 100644
--- a/client.go
+++ b/client.go
@@ -1277,7 +1277,7 @@ func (cl *Client) peerHasAll(t *torrent, cn *connection) {
cn.PeerPieces = nil
if t.haveInfo() {
for i := 0; i < t.numPieces(); i++ {
- cl.peerGotPiece(t, cn, i)
+ cn.peerGotPiece(i)
}
}
}
@@ -1385,7 +1385,7 @@ func (me *Client) connectionLoop(t *torrent, c *connection) error {
c.PeerInterested = false
c.Choke()
case pp.Have:
- me.peerGotPiece(t, c, int(msg.Index))
+ c.peerGotPiece(int(msg.Index))
case pp.Request:
if c.Choked {
break
@@ -1427,7 +1427,7 @@ func (me *Client) connectionLoop(t *torrent, c *connection) error {
c.PeerPieces = msg.Bitfield
for index, has := range c.PeerPieces {
if has {
- me.peerGotPiece(t, c, index)
+ c.peerGotPiece(index)
}
}
case pp.HaveAll:
diff --git a/connection.go b/connection.go
index <HASH>..<HASH> 100644
--- a/connection.go
+++ b/connection.go
@@ -626,11 +626,11 @@ func (c *connection) discardPieceInclination() {
c.pieceInclination = nil
}
-func (me *Client) peerGotPiece(t *torrent, c *connection, piece int) error {
+func (c *connection) peerGotPiece(piece int) error {
if !c.peerHasAll {
- if t.haveInfo() {
+ if c.t.haveInfo() {
if c.PeerPieces == nil {
- c.PeerPieces = make([]bool, t.numPieces())
+ c.PeerPieces = make([]bool, c.t.numPieces())
}
} else {
for piece >= len(c.PeerPieces) {
|
Make peerGotPiece a method on connection
|
anacrolix_torrent
|
train
|
f37ab1eebc00cc09f28bafcb0245e4352a271a89
|
diff --git a/troposphere/rds.py b/troposphere/rds.py
index <HASH>..<HASH> 100644
--- a/troposphere/rds.py
+++ b/troposphere/rds.py
@@ -173,6 +173,7 @@ class DBInstance(AWSObject):
'DBSecurityGroups': (list, False),
'DBSnapshotIdentifier': (basestring, False),
'DBSubnetGroupName': (basestring, False),
+ 'DeleteAutomatedBackups': (boolean, False),
'DeletionProtection': (boolean, False),
'Domain': (basestring, False),
'DomainIAMRoleName': (basestring, False),
|
Add DeleteAutomatedBackups to RDS DBInstance (#<I>)
This was part of the Nov. <I> update:
> Use the DeleteAutomatedBackups property to indicate whether automated backups
> should be deleted (true) or retained (false) when you delete a DB instance.
> The default is true.
|
cloudtools_troposphere
|
train
|
bcd39900b385c68dba706f514aa9f9ab3558bef6
|
diff --git a/pkg/cloudprovider/providers/gce/gce.go b/pkg/cloudprovider/providers/gce/gce.go
index <HASH>..<HASH> 100644
--- a/pkg/cloudprovider/providers/gce/gce.go
+++ b/pkg/cloudprovider/providers/gce/gce.go
@@ -1323,11 +1323,13 @@ func (gce *GCECloud) ListSslCertificates() (*compute.SslCertificateList, error)
// GlobalForwardingRule management
-// CreateGlobalForwardingRule creates and returns a GlobalForwardingRule that points to the given TargetHttpProxy.
-func (gce *GCECloud) CreateGlobalForwardingRule(proxy *compute.TargetHttpProxy, name string, portRange string) (*compute.ForwardingRule, error) {
+// CreateGlobalForwardingRule creates and returns a GlobalForwardingRule that points to the given TargetHttp(s)Proxy.
+// targetProxyLink is the SelfLink of a TargetHttp(s)Proxy.
+func (gce *GCECloud) CreateGlobalForwardingRule(targetProxyLink, ip, name, portRange string) (*compute.ForwardingRule, error) {
rule := &compute.ForwardingRule{
Name: name,
- Target: proxy.SelfLink,
+ IPAddress: ip,
+ Target: targetProxyLink,
PortRange: portRange,
IPProtocol: "TCP",
}
@@ -1341,9 +1343,10 @@ func (gce *GCECloud) CreateGlobalForwardingRule(proxy *compute.TargetHttpProxy,
return gce.GetGlobalForwardingRule(name)
}
-// SetProxyForGlobalForwardingRule links the given TargetHttpProxy with the given GlobalForwardingRule.
-func (gce *GCECloud) SetProxyForGlobalForwardingRule(fw *compute.ForwardingRule, proxy *compute.TargetHttpProxy) error {
- op, err := gce.service.GlobalForwardingRules.SetTarget(gce.projectID, fw.Name, &compute.TargetReference{Target: proxy.SelfLink}).Do()
+// SetProxyForGlobalForwardingRule links the given TargetHttp(s)Proxy with the given GlobalForwardingRule.
+// targetProxyLink is the SelfLink of a TargetHttp(s)Proxy.
+func (gce *GCECloud) SetProxyForGlobalForwardingRule(fw *compute.ForwardingRule, targetProxyLink string) error {
+ op, err := gce.service.GlobalForwardingRules.SetTarget(gce.projectID, fw.Name, &compute.TargetReference{Target: targetProxyLink}).Do()
if err != nil {
return err
}
|
Modify Create/SetGlobalForwardingRule to just take a link.
|
kubernetes_kubernetes
|
train
|
1150aeb896bd62ab7d2c62936d5b911da53ea67f
|
diff --git a/lib/testing/classes/util.php b/lib/testing/classes/util.php
index <HASH>..<HASH> 100644
--- a/lib/testing/classes/util.php
+++ b/lib/testing/classes/util.php
@@ -121,7 +121,7 @@ abstract class testing_util {
/**
* Returns whether test database and dataroot were created using the current version codebase
*
- * @return boolean
+ * @return bool
*/
protected static function is_test_data_updated() {
global $CFG;
@@ -490,9 +490,9 @@ abstract class testing_util {
}
/**
- * Resets the database
+ * Reset all database tables to default values.
* @static
- * @return boolean Returns whether database has been modified or not
+ * @return bool true if reset done, false if skipped
*/
public static function reset_database() {
global $DB;
@@ -610,7 +610,7 @@ abstract class testing_util {
/**
* Drop the whole test database
* @static
- * @param boolean $displayprogress
+ * @param bool $displayprogress
*/
protected static function drop_database($displayprogress = false) {
global $DB;
@@ -671,11 +671,6 @@ abstract class testing_util {
}
/**
- * Reset all database tables to default values.
- * @static
- * @return bool true if reset done, false if skipped
- */
- /**
* Calculate unique version hash for all plugins and core.
* @static
* @return string sha1 hash
|
MDL-<I> testing: Removing wrong comments
|
moodle_moodle
|
train
|
9f2b69ad6444ddd31ab5b135a7f95c27a18fd2cd
|
diff --git a/synapse/models/inet.py b/synapse/models/inet.py
index <HASH>..<HASH> 100644
--- a/synapse/models/inet.py
+++ b/synapse/models/inet.py
@@ -952,13 +952,20 @@ class InetMod(CoreModule):
'req': 1}),
('acct:site', {'ptype': 'inet:fqdn', 'doc': 'Site the user account is at', 'ro': 1, }),
('acct:user', {'ptype': 'inet:user', 'doc': 'User account name', 'ro': 1, }),
- ('ipv4', {'ptype': 'inet:ipv4', 'doc': 'Source IPv4 Address the action was done from', }),
- ('ipv6', {'ptype': 'inet:ipv6', 'doc': 'Source IPv6 Address the action was done from', }),
- ('time', {'ptype': 'time', 'doc': 'Time the action was observed', }),
- ('pv', {'ptype': 'propvalu', 'doc': 'The value changed in the account', 'ro': 1, 'req': 1}),
+ ('ipv4', {'ptype': 'inet:ipv4', 'doc': 'Source IPv4 address used to make the account change.', }),
+ ('ipv6', {'ptype': 'inet:ipv6', 'doc': 'Source IPv6 address used to make the account change.', }),
+ ('time', {'ptype': 'time', 'doc': 'When the account change was done', }),
+ ('pv', {'ptype': 'propvalu', 'ro': 1, 'req': 1,
+ 'doc': 'The prop=valu of the account property that was changed. Valu should be the '
+ 'old / original value, while the new value should be updated on the '
+ 'inet:web:acct form.'}),
('pv:prop', {'ptype': 'str', 'doc': 'Property which changed', 'ro': 1}),
- ('pv:strval', {'ptype': 'str', 'doc': 'System normed string value', 'ro': 1}),
- ('pv:intval', {'ptype': 'int', 'doc': 'System normed integer value.', 'ro': 1}),
+ ('pv:strval', {'ptype': 'str', 'ro': 1,
+ 'doc': 'The normed value of the property (specified by pv), if the property is '
+ 'a string', }),
+ ('pv:intval', {'ptype': 'int', 'ro': 1,
+ 'doc': 'The normed value of the property (specified by pv), if the property is '
+ 'a integer.', }),
]),
('inet:web:logon', {'ptype': 'inet:web:logon'}, [
|
Update docstrings based on feedback.
|
vertexproject_synapse
|
train
|
6fceccfdf954bc0a838effdb6418fd076eaa2919
|
diff --git a/src/Renderer/PlainTextRenderer.php b/src/Renderer/PlainTextRenderer.php
index <HASH>..<HASH> 100644
--- a/src/Renderer/PlainTextRenderer.php
+++ b/src/Renderer/PlainTextRenderer.php
@@ -24,9 +24,9 @@ final class PlainTextRenderer implements RendererInterface
private const LOWER_HALF_BLOCK = "\xe2\x96\x84";
/**
- * Empty block.
+ * UTF-8 no-break space (U+00A0)
*/
- private const EMPTY_BLOCK = ' ';
+ private const EMPTY_BLOCK = "\xc2\xa0";
/**
* @var int
|
Use no-break space for empty blocks in plain text QR code
|
Bacon_BaconQrCode
|
train
|
d05bb2d37c8f6de9c551f3bbdc6765c6bd052869
|
diff --git a/indra/tests/test_db_rest.py b/indra/tests/test_db_rest.py
index <HASH>..<HASH> 100644
--- a/indra/tests/test_db_rest.py
+++ b/indra/tests/test_db_rest.py
@@ -138,10 +138,12 @@ def test_famplex_namespace():
stmts = dbr.get_statements('PDGF@FPLX', 'FOS', stmt_type='IncreaseAmount',
simple_response=True)
print(len(stmts))
+ print(stmts)
assert all([s.agent_list()[0].db_refs.get('FPLX') == 'PDGF' for s in stmts]),\
'Not all subjects match.'
assert all([s.agent_list()[1].name == 'FOS' for s in stmts]),\
- 'Not all objects match.'
+ 'Not all objects match: ' \
+ + ', '.join({s.agent_list()[1].name for s in stmts})
@attr('nonpublic')
|
Add more clarity to famplex ns test.
|
sorgerlab_indra
|
train
|
2f7232f1ce6ea87ddbf6a9f1bff3f969ce435440
|
diff --git a/tests/integration/nupic/opf/expgenerator_test.py b/tests/integration/nupic/opf/expgenerator_test.py
index <HASH>..<HASH> 100755
--- a/tests/integration/nupic/opf/expgenerator_test.py
+++ b/tests/integration/nupic/opf/expgenerator_test.py
@@ -49,8 +49,7 @@ from nupic.frameworks.opf.opfutils import (InferenceType,
InferenceElement)
LOGGER = logging.getLogger(__name__)
-HOTGYM_INPUT = resource_filename("nupic.datafiles",
- os.path.join("extra", "hotgym", "hotgym.csv"))
+HOTGYM_INPUT = "extra/hotgym/hotgym.csv"
g_debug = False
|
Use resource handler deeper into expGen tests
|
numenta_nupic
|
train
|
8de6f50523d74ff08d81a0764d19259393c705ae
|
diff --git a/bonobo/examples/datasets/fablabs.py b/bonobo/examples/datasets/fablabs.py
index <HASH>..<HASH> 100644
--- a/bonobo/examples/datasets/fablabs.py
+++ b/bonobo/examples/datasets/fablabs.py
@@ -73,15 +73,15 @@ def display(row):
print(
' - {}address{}: {address}'.
- format(Fore.BLUE, Style.RESET_ALL, address=', '.join(address))
+ format(Fore.BLUE, Style.RESET_ALL, address=', '.join(address))
)
print(
' - {}links{}: {links}'.
- format(Fore.BLUE, Style.RESET_ALL, links=', '.join(row['links']))
+ format(Fore.BLUE, Style.RESET_ALL, links=', '.join(row['links']))
)
print(
' - {}geometry{}: {geometry}'.
- format(Fore.BLUE, Style.RESET_ALL, **row)
+ format(Fore.BLUE, Style.RESET_ALL, **row)
)
print(
' - {}source{}: {source}'.format(
@@ -96,8 +96,8 @@ graph = bonobo.Graph(
),
normalize,
filter_france,
+ bonobo.JsonWriter(path='fablabs.txt', ioformat='arg0'),
bonobo.Tee(display),
- bonobo.JsonWriter(path='fablabs.txt'),
)
if __name__ == '__main__':
diff --git a/bonobo/examples/nodes/filter.py b/bonobo/examples/nodes/filter.py
index <HASH>..<HASH> 100644
--- a/bonobo/examples/nodes/filter.py
+++ b/bonobo/examples/nodes/filter.py
@@ -9,13 +9,16 @@ class OddOnlyFilter(Filter):
@Filter
-def MultiplesOfThreeOnlyFilter(self, i):
+def multiples_of_three(i):
return not (i % 3)
graph = bonobo.Graph(
lambda: tuple(range(50)),
OddOnlyFilter(),
- MultiplesOfThreeOnlyFilter(),
+ multiples_of_three,
print,
)
+
+if __name__ == '__main__':
+ bonobo.run(graph)
diff --git a/bonobo/examples/nodes/slow.py b/bonobo/examples/nodes/slow.py
index <HASH>..<HASH> 100644
--- a/bonobo/examples/nodes/slow.py
+++ b/bonobo/examples/nodes/slow.py
@@ -14,3 +14,6 @@ graph = bonobo.Graph(
pause,
print,
)
+
+if __name__ == '__main__':
+ bonobo.run(graph)
diff --git a/bonobo/examples/tutorials/tut02e02_write.py b/bonobo/examples/tutorials/tut02e02_write.py
index <HASH>..<HASH> 100644
--- a/bonobo/examples/tutorials/tut02e02_write.py
+++ b/bonobo/examples/tutorials/tut02e02_write.py
@@ -8,7 +8,7 @@ def split_one(line):
graph = bonobo.Graph(
bonobo.FileReader('coffeeshops.txt'),
split_one,
- bonobo.JsonWriter('coffeeshops.json'),
+ bonobo.JsonWriter('coffeeshops.json', ioformat='arg0'),
)
if __name__ == '__main__':
diff --git a/bonobo/execution/node.py b/bonobo/execution/node.py
index <HASH>..<HASH> 100644
--- a/bonobo/execution/node.py
+++ b/bonobo/execution/node.py
@@ -95,6 +95,7 @@ class NodeExecutionContext(WithStatistics, LoopingExecutionContext):
continue
except UnrecoverableError as exc:
self.handle_error(exc, traceback.format_exc())
+ self.input.shutdown()
break
except Exception as exc: # pylint: disable=broad-except
self.handle_error(exc, traceback.format_exc())
diff --git a/bonobo/structs/inputs.py b/bonobo/structs/inputs.py
index <HASH>..<HASH> 100644
--- a/bonobo/structs/inputs.py
+++ b/bonobo/structs/inputs.py
@@ -77,6 +77,12 @@ class Input(Queue, Readable, Writable):
return Queue.put(self, data, block, timeout)
+ def _decrement_runlevel(self):
+ if self._runlevel == 1:
+ self.on_finalize()
+ self._runlevel -= 1
+ self.on_end()
+
def get(self, block=True, timeout=None):
if not self.alive:
raise InactiveReadableError('Cannot get() on an inactive {}.'.format(Readable.__name__))
@@ -84,13 +90,7 @@ class Input(Queue, Readable, Writable):
data = Queue.get(self, block, timeout)
if data == END:
- if self._runlevel == 1:
- self.on_finalize()
-
- self._runlevel -= 1
-
- # callback
- self.on_end()
+ self._decrement_runlevel()
if not self.alive:
raise InactiveReadableError(
@@ -100,6 +100,10 @@ class Input(Queue, Readable, Writable):
return data
+ def shutdown(self):
+ while self._runlevel >= 1:
+ self._decrement_runlevel()
+
def empty(self):
self.mutex.acquire()
while self._qsize() and self.queue[0] == END:
|
[examples] Fix examples, fix termination bug with unrecoverable errors.
|
python-bonobo_bonobo
|
train
|
99a5c2ef9ee09474c4447e008982f2de1b49ff0f
|
diff --git a/airflow/api/common/experimental/delete_dag.py b/airflow/api/common/experimental/delete_dag.py
index <HASH>..<HASH> 100644
--- a/airflow/api/common/experimental/delete_dag.py
+++ b/airflow/api/common/experimental/delete_dag.py
@@ -17,14 +17,13 @@
# specific language governing permissions and limitations
# under the License.
"""Delete DAGs APIs."""
-import os
from sqlalchemy import or_
from airflow import models
from airflow.models import TaskFail, DagModel
from airflow.utils.db import provide_session
-from airflow.exceptions import DagFileExists, DagNotFound
+from airflow.exceptions import DagNotFound
@provide_session
@@ -41,10 +40,6 @@ def delete_dag(dag_id: str, keep_records_in_log: bool = True, session=None) -> i
if dag is None:
raise DagNotFound("Dag id {} not found".format(dag_id))
- if dag.fileloc and os.path.exists(dag.fileloc):
- raise DagFileExists("Dag id {} is still in DagBag. "
- "Remove the DAG file first: {}".format(dag_id, dag.fileloc))
-
count = 0
# noinspection PyUnresolvedReferences,PyProtectedMember
diff --git a/tests/api/common/experimental/test_delete_dag.py b/tests/api/common/experimental/test_delete_dag.py
index <HASH>..<HASH> 100644
--- a/tests/api/common/experimental/test_delete_dag.py
+++ b/tests/api/common/experimental/test_delete_dag.py
@@ -21,7 +21,7 @@ import unittest
from airflow import models
from airflow.api.common.experimental.delete_dag import delete_dag
-from airflow.exceptions import DagNotFound, DagFileExists
+from airflow.exceptions import DagNotFound
from airflow.operators.dummy_operator import DummyOperator
from airflow.utils.dates import days_ago
from airflow.utils.db import create_session
@@ -49,28 +49,6 @@ class TestDeleteDAGCatchError(unittest.TestCase):
with self.assertRaises(DagNotFound):
delete_dag("non-existent DAG")
- def test_delete_dag_dag_still_in_dagbag(self):
- with create_session() as session:
- models_to_check = ['DagModel', 'DagRun', 'TaskInstance']
- record_counts = {}
-
- for model_name in models_to_check:
- m = getattr(models, model_name)
- record_counts[model_name] = session.query(m).filter(m.dag_id == self.dag_id).count()
-
- with self.assertRaises(DagFileExists):
- delete_dag(self.dag_id)
-
- # No change should happen in DB
- for model_name in models_to_check:
- m = getattr(models, model_name)
- self.assertEqual(
- session.query(m).filter(
- m.dag_id == self.dag_id
- ).count(),
- record_counts[model_name]
- )
-
class TestDeleteDAGSuccessfulDelete(unittest.TestCase):
diff --git a/tests/core.py b/tests/core.py
index <HASH>..<HASH> 100644
--- a/tests/core.py
+++ b/tests/core.py
@@ -1695,6 +1695,19 @@ class TestCli(unittest.TestCase):
'--yes'])
)
+ def test_delete_dag_existing_file(self):
+ # Test to check that the DAG should be deleted even if
+ # the file containing it is not deleted
+ DM = DagModel
+ key = "my_dag_id"
+ session = settings.Session()
+ with tempfile.NamedTemporaryFile() as f:
+ session.add(DM(dag_id=key, fileloc=f.name))
+ session.commit()
+ cli.delete_dag(self.parser.parse_args([
+ 'dags', 'delete', key, '--yes']))
+ self.assertEqual(session.query(DM).filter_by(dag_id=key).count(), 0)
+
def test_pool_create(self):
cli.pool_set(self.parser.parse_args(['pools', 'set', 'foo', '1', 'test']))
self.assertEqual(self.session.query(Pool).count(), 1)
|
[AIRFLOW-<I>] Allow Deleting Renamed DAGs (#<I>)
|
apache_airflow
|
train
|
49188caa3f2d2c88b0324e3e8eefb02102e7b853
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -26,6 +26,8 @@ import setuptools
import sys
from setuptools import setup, find_packages, Extension
+from setuptools.command.test import test as BaseTestCommand
+
REPO_DIR = os.path.dirname(os.path.realpath(__file__))
@@ -52,6 +54,33 @@ def parse_file(requirementFile):
+class TestCommand(BaseTestCommand):
+ user_options = [("pytest-args=", "a", "Arguments to pass to py.test")]
+
+
+ def initialize_options(self):
+ BaseTestCommand.initialize_options(self)
+ self.pytest_args = ["unit"] # pylint: disable=W0201
+
+
+ def finalize_options(self):
+ BaseTestCommand.finalize_options(self)
+ self.test_args = []
+ self.test_suite = True
+
+
+ def run_tests(self):
+ import pytest
+ cwd = os.getcwd()
+ try:
+ os.chdir("tests")
+ errno = pytest.main(self.pytest_args)
+ finally:
+ os.chdir(cwd)
+ sys.exit(errno)
+
+
+
def findRequirements():
"""
Read the requirements.txt file and parse into requirements for setup's
@@ -86,6 +115,7 @@ if __name__ == "__main__":
"nupic.swarming.jsonschema": ["*.json"],
"nupic.datafiles": ["*.csv", "*.txt"],
},
+ cmdclass = {"test": TestCommand},
include_package_data=True,
zip_safe=False,
extras_require = {"capnp": ["pycapnp==0.5.5"]},
|
Added python setup.py test functionality
|
numenta_nupic
|
train
|
1df336628afbbc9fef0eed94e01ebeeaf782ce65
|
diff --git a/django_extensions/db/fields/json.py b/django_extensions/db/fields/json.py
index <HASH>..<HASH> 100644
--- a/django_extensions/db/fields/json.py
+++ b/django_extensions/db/fields/json.py
@@ -69,7 +69,7 @@ class JSONField(models.TextField):
if not default:
kwargs['default'] = '{}'
elif isinstance(default, (list, dict)):
- kwargs['default'] = dump(value)
+ kwargs['default'] = dumps(default)
models.TextField.__init__(self, *args, **kwargs)
def to_python(self, value):
|
Fixed typo in JSONField
Fixes #<I>. Previous fix introduced a typo that caused a NameError when using a dict or list in the 'default' kwarg for JSONField.
|
django-extensions_django-extensions
|
train
|
d5e30999c782b12134eed98abfcc5f35967bc680
|
diff --git a/salt/modules/state.py b/salt/modules/state.py
index <HASH>..<HASH> 100644
--- a/salt/modules/state.py
+++ b/salt/modules/state.py
@@ -1089,7 +1089,6 @@ def sls(mods, test=None, exclude=None, queue=False, **kwargs):
mods = mods.split(',')
st_.push_active()
- ret = {}
try:
high_, errors = st_.render_highstate({opts['environment']: mods})
|
Remove unused variable (no exception, within the try/finally block)
|
saltstack_salt
|
train
|
9b79509ca06c2d7305341a880749dac2b34e3717
|
diff --git a/core/src/test/java/io/tracee/contextlogger/outputgenerator/writer/json/styles/JsonOutputStyleTest.java b/core/src/test/java/io/tracee/contextlogger/outputgenerator/writer/json/styles/JsonOutputStyleTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/io/tracee/contextlogger/outputgenerator/writer/json/styles/JsonOutputStyleTest.java
+++ b/core/src/test/java/io/tracee/contextlogger/outputgenerator/writer/json/styles/JsonOutputStyleTest.java
@@ -37,7 +37,7 @@ public class JsonOutputStyleTest {
@Test
public void should_escape_string_correctly() {
- final String givenString = "\\ \" / \b \t \n \f \r ü ABCD" + (char)27;
+ final String givenString = "\\ \" / \b \t \n \f \r ü ABCD " + (char)27;
String result = jsonOutputStyle.escapeString(givenString);
MatcherAssert.assertThat(result, Matchers.is("\\\\ \\\" \\/ \\b \\t \\n \\f \\r ü ABCD \\u001b"));
|
[#<I>] increased test coverage
|
tracee_contextlogger
|
train
|
12fd3a625a044a454cca3dbb2187e78efe1b4596
|
diff --git a/references/classification/train.py b/references/classification/train.py
index <HASH>..<HASH> 100644
--- a/references/classification/train.py
+++ b/references/classification/train.py
@@ -17,7 +17,8 @@ except ImportError:
amp = None
-def train_one_epoch(model, criterion, optimizer, data_loader, device, epoch, print_freq, apex=False):
+def train_one_epoch(model, criterion, optimizer, data_loader, device, epoch,
+ print_freq, apex=False, model_ema=None):
model.train()
metric_logger = utils.MetricLogger(delimiter=" ")
metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value}'))
@@ -45,11 +46,14 @@ def train_one_epoch(model, criterion, optimizer, data_loader, device, epoch, pri
metric_logger.meters['acc5'].update(acc5.item(), n=batch_size)
metric_logger.meters['img/s'].update(batch_size / (time.time() - start_time))
+ if model_ema:
+ model_ema.update_parameters(model)
-def evaluate(model, criterion, data_loader, device, print_freq=100):
+
+def evaluate(model, criterion, data_loader, device, print_freq=100, log_suffix=''):
model.eval()
metric_logger = utils.MetricLogger(delimiter=" ")
- header = 'Test:'
+ header = f'Test: {log_suffix}'
with torch.no_grad():
for image, target in metric_logger.log_every(data_loader, print_freq, header):
image = image.to(device, non_blocking=True)
@@ -199,12 +203,18 @@ def main(args):
model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu])
model_without_ddp = model.module
+ model_ema = None
+ if args.model_ema:
+ model_ema = utils.ExponentialMovingAverage(model_without_ddp, device=device, decay=args.model_ema_decay)
+
if args.resume:
checkpoint = torch.load(args.resume, map_location='cpu')
model_without_ddp.load_state_dict(checkpoint['model'])
optimizer.load_state_dict(checkpoint['optimizer'])
lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])
args.start_epoch = checkpoint['epoch'] + 1
+ if model_ema:
+ model_ema.load_state_dict(checkpoint['model_ema'])
if args.test_only:
evaluate(model, criterion, data_loader_test, device=device)
@@ -215,9 +225,11 @@ def main(args):
for epoch in range(args.start_epoch, args.epochs):
if args.distributed:
train_sampler.set_epoch(epoch)
- train_one_epoch(model, criterion, optimizer, data_loader, device, epoch, args.print_freq, args.apex)
+ train_one_epoch(model, criterion, optimizer, data_loader, device, epoch, args.print_freq, args.apex, model_ema)
lr_scheduler.step()
evaluate(model, criterion, data_loader_test, device=device)
+ if model_ema:
+ evaluate(model_ema, criterion, data_loader_test, device=device, log_suffix='EMA')
if args.output_dir:
checkpoint = {
'model': model_without_ddp.state_dict(),
@@ -225,6 +237,8 @@ def main(args):
'lr_scheduler': lr_scheduler.state_dict(),
'epoch': epoch,
'args': args}
+ if model_ema:
+ checkpoint['model_ema'] = model_ema.state_dict()
utils.save_on_master(
checkpoint,
os.path.join(args.output_dir, 'model_{}.pth'.format(epoch)))
@@ -306,6 +320,12 @@ def get_args_parser(add_help=True):
parser.add_argument('--world-size', default=1, type=int,
help='number of distributed processes')
parser.add_argument('--dist-url', default='env://', help='url used to set up distributed training')
+ parser.add_argument(
+ '--model-ema', action='store_true',
+ help='enable tracking Exponential Moving Average of model parameters')
+ parser.add_argument(
+ '--model-ema-decay', type=float, default=0.99,
+ help='decay factor for Exponential Moving Average of model parameters(default: 0.99)')
return parser
diff --git a/references/classification/utils.py b/references/classification/utils.py
index <HASH>..<HASH> 100644
--- a/references/classification/utils.py
+++ b/references/classification/utils.py
@@ -161,6 +161,18 @@ class MetricLogger(object):
print('{} Total time: {}'.format(header, total_time_str))
+class ExponentialMovingAverage(torch.optim.swa_utils.AveragedModel):
+ """Maintains moving averages of model parameters using an exponential decay.
+ ``ema_avg = decay * avg_model_param + (1 - decay) * model_param``
+ `torch.optim.swa_utils.AveragedModel <https://pytorch.org/docs/stable/optim.html#custom-averaging-strategies>`_
+ is used to compute the EMA.
+ """
+ def __init__(self, model, decay, device='cpu'):
+ ema_avg = (lambda avg_model_param, model_param, num_averaged:
+ decay * avg_model_param + (1 - decay) * model_param)
+ super().__init__(model, device, ema_avg)
+
+
def accuracy(output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
|
Added Exponential Moving Average support to classification reference script (#<I>)
* Added Exponential Moving Average support to classification reference script
* Addressed review comments
* Updated model argument
|
pytorch_vision
|
train
|
73059566ab91570c966e6e86338c666bc7f528ed
|
diff --git a/pyrax/cloudblockstorage.py b/pyrax/cloudblockstorage.py
index <HASH>..<HASH> 100644
--- a/pyrax/cloudblockstorage.py
+++ b/pyrax/cloudblockstorage.py
@@ -29,8 +29,6 @@ from pyrax.resource import BaseResource
import pyrax.utils as utils
-MIN_SIZE = 100
-MAX_SIZE = 1024
RETRY_INTERVAL = 5
@@ -283,10 +281,11 @@ class CloudBlockStorageManager(BaseManager):
"""
Used to create the dict required to create a new volume
"""
- if not isinstance(size, (int, long)) or not (
- MIN_SIZE <= size <= MAX_SIZE):
- raise exc.InvalidSize("Volume sizes must be integers between "
- "%s and %s." % (MIN_SIZE, MAX_SIZE))
+ try:
+ int(size)
+ except:
+ raise exc.InvalidSize("Volume sizes must be integers")
+
if volume_type is None:
volume_type = "SATA"
if description is None:
diff --git a/tests/unit/test_cloud_blockstorage.py b/tests/unit/test_cloud_blockstorage.py
index <HASH>..<HASH> 100644
--- a/tests/unit/test_cloud_blockstorage.py
+++ b/tests/unit/test_cloud_blockstorage.py
@@ -17,8 +17,6 @@ from pyrax.cloudblockstorage import _resolve_id
from pyrax.cloudblockstorage import _resolve_name
from pyrax.cloudblockstorage import assure_volume
from pyrax.cloudblockstorage import assure_snapshot
-from pyrax.cloudblockstorage import MIN_SIZE
-from pyrax.cloudblockstorage import MAX_SIZE
import pyrax.exceptions as exc
from pyrax.manager import BaseManager
import pyrax.utils as utils
@@ -255,26 +253,24 @@ class CloudBlockStorageTest(unittest.TestCase):
def test_create_body_volume_bad_size(self):
mgr = self.client._manager
self.assertRaises(exc.InvalidSize, mgr._create_body, "name",
- size=MIN_SIZE - 1)
- self.assertRaises(exc.InvalidSize, mgr._create_body, "name",
- size=MAX_SIZE + 1)
+ size='foo')
def test_create_volume_bad_clone_size(self):
mgr = self.client._manager
mgr._create = Mock(side_effect=exc.BadRequest(400,
"Clones currently must be >= original volume size"))
self.assertRaises(exc.VolumeCloneTooSmall, mgr.create, "name",
- size=MIN_SIZE, clone_id=utils.random_unicode())
+ size=100, clone_id=utils.random_unicode())
def test_create_volume_fail_other(self):
mgr = self.client._manager
mgr._create = Mock(side_effect=exc.BadRequest(400, "FAKE"))
self.assertRaises(exc.BadRequest, mgr.create, "name",
- size=MIN_SIZE, clone_id=utils.random_unicode())
+ size=100, clone_id=utils.random_unicode())
def test_create_body_volume(self):
mgr = self.client._manager
- size = random.randint(MIN_SIZE, MAX_SIZE)
+ size = random.randint(100, 1024)
name = utils.random_unicode()
snapshot_id = utils.random_unicode()
clone_id = utils.random_unicode()
@@ -301,7 +297,7 @@ class CloudBlockStorageTest(unittest.TestCase):
def test_create_body_volume_defaults(self):
mgr = self.client._manager
- size = random.randint(MIN_SIZE, MAX_SIZE)
+ size = random.randint(100, 1024)
name = utils.random_unicode()
snapshot_id = utils.random_unicode()
clone_id = utils.random_unicode()
|
Don't hardcode min and max CBS size, just rely on the API to validate. Fixes #<I>
|
pycontribs_pyrax
|
train
|
c62fae2de085d448f97af26d680cf8b539eb5c27
|
diff --git a/lib/adapter.js b/lib/adapter.js
index <HASH>..<HASH> 100644
--- a/lib/adapter.js
+++ b/lib/adapter.js
@@ -6,9 +6,17 @@ var formatFailedAssertion = function(assertion) {
};
var createStartFn = function(tc, passedInRunner) {
+ var nodeunit = window.nodeunit,
+ deferredModules;
+
+ // Intercept nodeunit.run in case its called before Karma has started
+ nodeunit.run = function(modules) {
+ deferredModules = modules;
+ };
+
return function () {
var totalNumberOfTest = 0;
- var runner = passedInRunner || window.nodeunit;
+ var runner = passedInRunner || nodeunit;
runner.run = function(modules) {
runner.runModules(modules, {
@@ -43,6 +51,11 @@ var createStartFn = function(tc, passedInRunner) {
}
});
};
+
+ // Run any suites that were waiting for Karma to start
+ if(deferredModules) {
+ runner.run(deferredModules);
+ }
};
};
diff --git a/src/adapter.js b/src/adapter.js
index <HASH>..<HASH> 100644
--- a/src/adapter.js
+++ b/src/adapter.js
@@ -4,9 +4,17 @@ var formatFailedAssertion = function(assertion) {
};
var createStartFn = function(tc, passedInRunner) {
+ var nodeunit = window.nodeunit,
+ deferredModules;
+
+ // Intercept nodeunit.run in case its called before Karma has started
+ nodeunit.run = function(modules) {
+ deferredModules = modules;
+ };
+
return function () {
var totalNumberOfTest = 0;
- var runner = passedInRunner || window.nodeunit;
+ var runner = passedInRunner || nodeunit;
runner.run = function(modules) {
runner.runModules(modules, {
@@ -41,6 +49,11 @@ var createStartFn = function(tc, passedInRunner) {
}
});
};
+
+ // Run any suites that were waiting for Karma to start
+ if(deferredModules) {
+ runner.run(deferredModules);
+ }
};
};
|
Capture calls to nodeunit.run before karma starts
|
karma-runner_karma-nodeunit
|
train
|
e362823b136feb192828bfff9c82a094052c5dbf
|
diff --git a/holoviews/plotting/mpl/__init__.py b/holoviews/plotting/mpl/__init__.py
index <HASH>..<HASH> 100644
--- a/holoviews/plotting/mpl/__init__.py
+++ b/holoviews/plotting/mpl/__init__.py
@@ -179,6 +179,8 @@ options.Scatter3D = Options('style', facecolors=Cycle(), marker='o')
options.Scatter3D = Options('plot', fig_size=150)
options.Surface = Options('plot', fig_size=150)
options.Spikes = Options('style', color='black')
+options.BoxWhisker = Options('style', boxprops=dict(color='k'),
+ whiskerprops=dict(color='k'))
# Rasters
options.Image = Options('style', cmap='hot', interpolation='nearest')
options.Raster = Options('style', cmap='hot', interpolation='nearest')
diff --git a/holoviews/plotting/mpl/chart.py b/holoviews/plotting/mpl/chart.py
index <HASH>..<HASH> 100644
--- a/holoviews/plotting/mpl/chart.py
+++ b/holoviews/plotting/mpl/chart.py
@@ -9,7 +9,7 @@ from matplotlib.collections import LineCollection
import param
from ...core import OrderedDict, NdMapping, CompositeOverlay, HoloMap
-from ...core.util import match_spec, unique_iterator
+from ...core.util import match_spec, unique_iterator, safe_unicode, basestring
from ...element import Points, Raster, Polygons
from ..util import compute_sizes, get_sideplot_ranges
from .element import ElementPlot, ColorbarPlot, LegendPlot
@@ -1090,12 +1090,14 @@ class BoxPlot(ChartPlot):
plot option.
"""
- style_opts = ['notch', 'sym', 'vert', 'whis', 'bootstrap',
+ style_opts = ['notch', 'sym', 'whis', 'bootstrap',
'conf_intervals', 'widths', 'showmeans',
'show_caps', 'showfliers', 'boxprops',
'whiskerprops', 'capprops', 'flierprops',
'medianprops', 'meanprops', 'meanline']
+ def get_extents(self, element, ranges):
+ return (np.NaN,)*4
def initialize_plot(self, ranges=None):
element = self.hmap.last
@@ -1106,10 +1108,12 @@ class BoxPlot(ChartPlot):
ranges = match_spec(element, ranges)
xlabel = ','.join([str(d) for d in element.kdims])
+ ylabel = str(element.vdims[0])
self.handles['artist'] = self.get_artist(element, axis)
- return self._finalize_axis(self.keys[-1], ranges=ranges, xlabel=xlabel)
+ return self._finalize_axis(self.keys[-1], ranges=ranges, xlabel=xlabel,
+ ylabel=ylabel)
def get_artist(self, element, axis):
dims = element.dimensions()
@@ -1117,11 +1121,13 @@ class BoxPlot(ChartPlot):
data, labels = [], []
for key, group in groups.data.items():
- label = ','.join([d.pprint_value(v) for d, v in zip(groups.kdims, key)])
+ key = [k if isinstance(k, basestring) else str(k) for k in key]
+ label = ','.join([safe_unicode(d.pprint_value(v))
+ for d, v in zip(groups.kdims, key)])
data.append(group[group.vdims[0]])
labels.append(label)
- boxplot = axis.boxplot(data, labels=labels, **self.style[self.cyclic_index])
- return boxplot
+ return axis.boxplot(data, labels=labels, vert=not self.invert_axes,
+ **self.style[self.cyclic_index])
def update_handles(self, axis, element, key, ranges=None):
|
Fixes for styling of BoxPlots
|
pyviz_holoviews
|
train
|
1132117846e783c329ff282f48d858b6c63d76f8
|
diff --git a/js/validator.js b/js/validator.js
index <HASH>..<HASH> 100644
--- a/js/validator.js
+++ b/js/validator.js
@@ -79,6 +79,8 @@
var prevErrors = $el.data('bs.validator.errors')
var errors
+ if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')
+
this.$element.trigger(e = $.Event('validate.bs.validator', {relatedTarget: $el[0]}))
if (e.isDefaultPrevented()) return
|
Fixes #<I>: radio buttons were keeping the form disabled because they weren't being handled as a group
|
1000hz_bootstrap-validator
|
train
|
c0ea7891cd0ad5d011f7ae073335cec8e8579b4a
|
diff --git a/entry.go b/entry.go
index <HASH>..<HASH> 100644
--- a/entry.go
+++ b/entry.go
@@ -188,6 +188,7 @@ func (entry *Entry) Fatalf(format string, args ...interface{}) {
if entry.Logger.Level >= FatalLevel {
entry.Fatal(fmt.Sprintf(format, args...))
}
+ os.Exit(1)
}
func (entry *Entry) Panicf(format string, args ...interface{}) {
@@ -234,6 +235,7 @@ func (entry *Entry) Fatalln(args ...interface{}) {
if entry.Logger.Level >= FatalLevel {
entry.Fatal(entry.sprintlnn(args...))
}
+ os.Exit(1)
}
func (entry *Entry) Panicln(args ...interface{}) {
|
Fix Fatalf() and Fatalln() to exit irrespective of log level
|
sirupsen_logrus
|
train
|
c943ceb6c0c0c70ede78382563bac8cb69a53444
|
diff --git a/lib/fog/aws/requests/elasticache/authorize_cache_security_group_ingress.rb b/lib/fog/aws/requests/elasticache/authorize_cache_security_group_ingress.rb
index <HASH>..<HASH> 100644
--- a/lib/fog/aws/requests/elasticache/authorize_cache_security_group_ingress.rb
+++ b/lib/fog/aws/requests/elasticache/authorize_cache_security_group_ingress.rb
@@ -34,8 +34,6 @@ module Fog
'EC2SecurityGroupOwnerId' => ec2_owner_id
}
- response = Excon::Response.new
-
if sec_group = self.data[:security_groups][name]
if sec_group['EC2SecurityGroups'].detect{|h| h['EC2SecurityGroupName'] == opts['EC2SecurityGroupName']}
@@ -43,13 +41,15 @@ module Fog
end
sec_group['EC2SecurityGroups'] << opts.merge({'Status' => 'authorizing'})
- response.status = 200
- response.body = {
- 'ResponseMetadata'=>{ 'RequestId'=> Fog::AWS::Mock.request_id },
- 'CacheSecurityGroup' => sec_group
- }
-
- response
+ Excon::Response.new(
+ {
+ :status => 200,
+ :body => {
+ 'ResponseMetadata'=>{ 'RequestId'=> Fog::AWS::Mock.request_id },
+ 'CacheSecurityGroup' => sec_group
+ }
+ }
+ )
else
raise Fog::AWS::Elasticache::NotFound.new("CacheSecurityGroupNotFound => #{name} not found")
end
|
Another fix from @jbence comments to simplify Excon response in authorize_cache_security_group_ingress
|
fog_fog
|
train
|
b365152fb931d50b754a4927d39f7ae9cb5c6dc4
|
diff --git a/openquake/calculators/hazard/disagg/core.py b/openquake/calculators/hazard/disagg/core.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/hazard/disagg/core.py
+++ b/openquake/calculators/hazard/disagg/core.py
@@ -156,9 +156,6 @@ def compute_disagg(job_id, sites, lt_rlz_id):
for poe in hc.poes_disagg:
iml = numpy.interp(poe, curve.poes[::-1], imls)
- # TODO: for each disagg poe, interpolate IML for the curve
- # TODO: load the site model, if there is one
- # TODO: Prepare the args for the calculator.
calc_kwargs = {
'sources': sources,
'site': site,
|
calcs/hazard/disagg/core: removed some TODOs
Former-commit-id: cc<I>a<I>e2c<I>d<I>e<I>a<I>c<I>
|
gem_oq-engine
|
train
|
bfc51b959d546f5fa8c6741b8283b9cc88942893
|
diff --git a/sos/plugins/s390.py b/sos/plugins/s390.py
index <HASH>..<HASH> 100644
--- a/sos/plugins/s390.py
+++ b/sos/plugins/s390.py
@@ -55,7 +55,6 @@ class S390(Plugin, RedHatPlugin):
"lscss",
"lsdasd",
"lstape",
- "find /sys -type f",
"find /proc/s390dbf -type f",
"qethconf list_all",
"lsqeth",
|
[s<I>] remove "find /sys" from plugin
|
sosreport_sos
|
train
|
7dd90d22ae72ff227a5ba8343a5aa12b98613038
|
diff --git a/src/main/java/com/j256/ormlite/android/AndroidDatabaseConnection.java b/src/main/java/com/j256/ormlite/android/AndroidDatabaseConnection.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/j256/ormlite/android/AndroidDatabaseConnection.java
+++ b/src/main/java/com/j256/ormlite/android/AndroidDatabaseConnection.java
@@ -112,15 +112,15 @@ public class AndroidDatabaseConnection implements DatabaseConnection {
db.setTransactionSuccessful();
db.endTransaction();
if (savepoint == null) {
- logger.trace("{}: transaction is successfuly ended", this);
+ logger.trace("{}: transaction is successfully ended", this);
} else {
- logger.trace("{}: transaction {} is successfuly ended", this, savepoint.getSavepointName());
+ logger.trace("{}: transaction {} is successfully ended", this, savepoint.getSavepointName());
}
} catch (android.database.SQLException e) {
if (savepoint == null) {
- throw SqlExceptionUtil.create("problems commiting transaction", e);
+ throw SqlExceptionUtil.create("problems committing transaction", e);
} else {
- throw SqlExceptionUtil.create("problems commiting transaction " + savepoint.getSavepointName(), e);
+ throw SqlExceptionUtil.create("problems committing transaction " + savepoint.getSavepointName(), e);
}
}
}
@@ -131,9 +131,9 @@ public class AndroidDatabaseConnection implements DatabaseConnection {
// no setTransactionSuccessful() means it is a rollback
db.endTransaction();
if (savepoint == null) {
- logger.trace("{}: transaction is ended, unsuccessfuly", this);
+ logger.trace("{}: transaction is ended, unsuccessfully", this);
} else {
- logger.trace("{}: transaction {} is ended, unsuccessfuly", this, savepoint.getSavepointName());
+ logger.trace("{}: transaction {} is ended, unsuccessfully", this, savepoint.getSavepointName());
}
} catch (android.database.SQLException e) {
if (savepoint == null) {
|
Fixing typo in AndroidDatabaseConnection
successfuly -> successfully
unsuccessfuly -> unsuccessfully
commiting -> committing
|
j256_ormlite-android
|
train
|
7d1d48329e511d0f3a2b96e7dfba6368db5093ab
|
diff --git a/pysolr.py b/pysolr.py
index <HASH>..<HASH> 100644
--- a/pysolr.py
+++ b/pysolr.py
@@ -90,6 +90,11 @@ __all__ = ['Solr']
class SolrError(Exception):
pass
+class Results(object):
+ def __init__(self, docs, hits):
+ self.docs = docs
+ self.hits = hits
+
class Solr(object):
def __init__(self, host, port=8983):
self.host = host
@@ -182,6 +187,7 @@ class Solr(object):
# TODO: make result retrieval lazy and allow custom result objects
et = ElementTree.parse(response)
result = et.find('result')
+ hits = int(result.get('numFound'))
docs = result.findall('doc')
results = []
for doc in docs:
@@ -191,7 +197,7 @@ class Solr(object):
converter = getattr(self, converter_name)
result[element.get('name')] = converter(element.text)
results.append(result)
- return results
+ return Results(results, hits)
def add(self, docs, commit=True):
"""Adds or updates documents. For now, docs is a list of dictionaies
|
Broke results out into a separate object with docs and hits attributes.
|
django-haystack_pysolr
|
train
|
4a5eba2971e7bea68b3844f2837a11228384f498
|
diff --git a/generator/lib/behavior/sluggable/SluggableBehavior.php b/generator/lib/behavior/sluggable/SluggableBehavior.php
index <HASH>..<HASH> 100644
--- a/generator/lib/behavior/sluggable/SluggableBehavior.php
+++ b/generator/lib/behavior/sluggable/SluggableBehavior.php
@@ -91,8 +91,12 @@ if (\$this->isColumnModified($const) && \$this->{$this->getColumnGetter()}()) {
$count = preg_match_all('/{([a-zA-Z]+)}/', $pattern, $matches, PREG_PATTERN_ORDER);
foreach ($matches[1] as $key => $match) {
-
- $column = $this->getTable()->getColumn($this->underscore(ucfirst($match)));
+ $columnName = $this->underscore(ucfirst($match));
+ $column = $this->getTable()->getColumn($columnName);
+ if ((null == $column) && $this->getTable()->hasBehavior('symfony_i18n')) {
+ $i18n = $this->getTable()->getBehavior('symfony_i18n');
+ $column = $i18n->getI18nTable()->getColumn($columnName);
+ }
if (null == $column) {
throw new \InvalidArgumentException(sprintf('The pattern %s is invalid the column %s is not found', $pattern, $match));
}
|
Fixed Sluggable behavior combining with symfony_i<I>n
|
propelorm_Propel
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.