hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
89a9ff3345943d7e0bfcfe1043c64f76dad7edb9
|
diff --git a/api/server/apps_delete.go b/api/server/apps_delete.go
index <HASH>..<HASH> 100644
--- a/api/server/apps_delete.go
+++ b/api/server/apps_delete.go
@@ -28,7 +28,7 @@ func handleAppDelete(c *gin.Context) {
return
}
- err = Api.FireAfterAppDelete(ctx, appName)
+ err = Api.FireBeforeAppDelete(ctx, appName)
if err != nil {
log.WithError(err).Errorln(models.ErrAppsRemoving)
c.JSON(http.StatusInternalServerError, simpleError(err))
|
fix app delete listener call (#<I>)
|
iron-io_functions
|
train
|
167138fd6535d6ac994e6c6f4ed8b7a4536d0586
|
diff --git a/cmd/cammount/cammount.go b/cmd/cammount/cammount.go
index <HASH>..<HASH> 100644
--- a/cmd/cammount/cammount.go
+++ b/cmd/cammount/cammount.go
@@ -74,8 +74,13 @@ func main() {
sigc := make(chan os.Signal, 1)
go func() {
var buf [1]byte
- os.Stdin.Read(buf[:])
- log.Printf("Read from stdin; shutting down.")
+ for {
+ os.Stdin.Read(buf[:])
+ if buf[0] == 'q' {
+ break
+ }
+ }
+ log.Printf("Read 'q' from stdin; shutting down.")
sigc <- syscall.SIGUSR2
}()
waitc := make(chan error, 1)
diff --git a/dev-cammount b/dev-cammount
index <HASH>..<HASH> 100755
--- a/dev-cammount
+++ b/dev-cammount
@@ -38,6 +38,7 @@ $ENV{"CAMLI_AUTH"} = "userpass:camlistore:pass3179";
my $in_child = "false";
if ($^O eq "darwin") {
$in_child = "true";
+ print "############################################################################\n## Press 'q' <enter> to shut down.\n##\n";
}
exec("$cammount", "--mount_in_child=$in_child", "--server=http://localhost:3179/bs", $dir, @blobref_arg)
@@ -46,9 +47,7 @@ warn "Failed to unmount\n" unless try_unmount();
sub try_unmount {
if ($^O eq "darwin") {
- print "Try unmount darwin...\n";
unless (`df -n` =~ /\Q$dir\E/) {
- print "Not mounted.\n";
return 1;
}
print "Running: diskutil unmount force $dir ...\n";
diff --git a/pkg/fs/fs.go b/pkg/fs/fs.go
index <HASH>..<HASH> 100644
--- a/pkg/fs/fs.go
+++ b/pkg/fs/fs.go
@@ -301,7 +301,6 @@ func (fs *CamliFileSystem) Root() (fuse.Node, fuse.Error) {
}
func (fs *CamliFileSystem) Statfs(req *fuse.StatfsRequest, res *fuse.StatfsResponse, intr fuse.Intr) fuse.Error {
- log.Printf("CAMLI StatFS")
// Make some stuff up, just to see if it makes "lsof" happy.
res.Blocks = 1 << 35
res.Bfree = 1 << 34
diff --git a/pkg/fs/root.go b/pkg/fs/root.go
index <HASH>..<HASH> 100644
--- a/pkg/fs/root.go
+++ b/pkg/fs/root.go
@@ -90,6 +90,8 @@ func (n *root) Lookup(name string, intr fuse.Intr) (fuse.Node, fuse.Error) {
return n.getRootsDir(), nil
case "sha1-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx":
return notImplementDirNode{}, nil
+ case "mach_kernel", ".hidden", "._.":
+ return nil, fuse.ENOENT
}
br := blobref.Parse(name)
|
cammount: quieter. and only exit when 'q' is pressed.
Change-Id: I2c<I>f<I>d<I>e<I>cd<I>ce<I>dd<I>
|
perkeep_perkeep
|
train
|
582d563098f5fcf244bf0e7bbcd1d1d9fcbf8cf2
|
diff --git a/packages/idyll-cli/src/client/build.js b/packages/idyll-cli/src/client/build.js
index <HASH>..<HASH> 100644
--- a/packages/idyll-cli/src/client/build.js
+++ b/packages/idyll-cli/src/client/build.js
@@ -19,6 +19,7 @@ require('__IDYLL_SYNTAX_HIGHLIGHT__');
var opts = require('__IDYLL_OPTS__');
var layout = opts.layout;
var theme = opts.theme;
+var authorView = opts.authorView;
var context = require('__IDYLL_CONTEXT__');
@@ -30,7 +31,8 @@ ReactDOM[mountMethod](
context: context,
datasets: datasets,
layout: layout,
- theme: theme
+ theme: theme,
+ authorView: authorView
}),
mountNode
);
diff --git a/packages/idyll-cli/src/pipeline/bundle-js.js b/packages/idyll-cli/src/pipeline/bundle-js.js
index <HASH>..<HASH> 100644
--- a/packages/idyll-cli/src/pipeline/bundle-js.js
+++ b/packages/idyll-cli/src/pipeline/bundle-js.js
@@ -14,7 +14,7 @@ const toStream = (k, o) => {
if (['ast', 'data', 'opts'].indexOf(k) > -1) {
if (k === 'opts') {
-
+
src = `
var out = ${JSON.stringify(o)};
out.context = ${(o.context || function() {}).toString()};
diff --git a/packages/idyll-cli/src/pipeline/index.js b/packages/idyll-cli/src/pipeline/index.js
index <HASH>..<HASH> 100644
--- a/packages/idyll-cli/src/pipeline/index.js
+++ b/packages/idyll-cli/src/pipeline/index.js
@@ -68,7 +68,8 @@ const build = (opts, paths, resolvers) => {
opts: {
ssr: opts.ssr,
theme: opts.theme,
- layout: opts.layout
+ layout: opts.layout,
+ authorView: opts.authorView
}
};
if (!opts.ssr) {
|
have authorView value flow to runtime
|
idyll-lang_idyll
|
train
|
17908008f90ab56a7f3dff41ea036c3eadfb3dfa
|
diff --git a/spec/httmultiparty_spec.rb b/spec/httmultiparty_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/httmultiparty_spec.rb
+++ b/spec/httmultiparty_spec.rb
@@ -13,7 +13,7 @@ describe HTTMultiParty do
let(:klass) { Class.new.tap { |k| k.instance_eval { include HTTMultiParty} } }
it "should include HTTParty module" do
- klass.included_modules.should include HTTParty
+ klass.included_modules.should include HTTParty
end
it "should extend HTTParty::Request::SupportedHTTPMethods with Multipart methods" do
@@ -37,13 +37,13 @@ describe HTTMultiParty do
it "should return false if none of the values in the passed hash is a file" do
klass.send(:hash_contains_files?, {:a => 1, :b => 'nope'}).should be_false
end
-
+
it "should return true if passed hash includes an a array of files" do
- klass.send(:hash_contains_files?, {:somefiles => [somefile, somefile]}).should be_true
+ klass.send(:hash_contains_files?, {:somefiles => [somefile, somefile]}).should be_true
end
end
-
- describe '#post' do
+
+ describe '#post' do
it "should respond to post" do
klass.should respond_to :post
end
@@ -54,10 +54,10 @@ describe HTTMultiParty do
.and_return(mock("mock response", :perform => nil))
klass.post('http://example.com/', {})
end
-
+
describe 'when :query contains a file' do
let(:query) { {:somefile => somefile } }
-
+
it "should setup new request with Net::HTTP::Post::Multipart" do
HTTParty::Request.should_receive(:new) \
.with(HTTMultiParty::MultipartPost, anything, anything) \
@@ -65,7 +65,7 @@ describe HTTMultiParty do
klass.post('http://example.com/', :query => query)
end
end
-
+
describe 'when :body contains a file' do
let(:body) { {:somefile => somefile } }
@@ -77,7 +77,7 @@ describe HTTMultiParty do
end
end
end
-
+
describe "#file_to_upload_io" do
it "should get the physical name of a file" do
HTTMultiParty.file_to_upload_io(somefile)\
@@ -137,17 +137,17 @@ describe HTTMultiParty do
].sort_by(&:join)
end
end
-
+
describe "#query_string_normalizer" do
subject { HTTMultiParty.query_string_normalizer }
it "should map a file to UploadIO" do
(first_k, first_v) = subject.call({
:file => somefile
}).first
-
- first_v.should be_an UploadIO
+
+ first_v.should be_an UploadIO
end
-
+
it "should map a Tempfile to UploadIO" do
(first_k, first_v) = subject.call({
:file => sometempfile
@@ -162,6 +162,16 @@ describe HTTMultiParty do
}).each { |(k,v)| v.should be_an UploadIO }
end
+ it 'parses file and non-file parameters properly irrespective of their position' do
+ response = subject.call(
+ :name => 'foo',
+ :file => somefile,
+ :title => 'bar'
+ )
+ response.first.should == ['name', 'foo']
+ response.last.should == ['title', 'bar']
+ end
+
describe "when :detect_mime_type is true" do
subject { HTTMultiParty.query_string_normalizer(detect_mime_type: true) }
|
Added test case for verifying that position of file and non-file params does not matter
|
jwagener-soundcloud_httmultiparty
|
train
|
37adfb8ed5c1f821af731be16513b88414732ad8
|
diff --git a/telemetry/telemetry/core/backends/form_based_credentials_backend.py b/telemetry/telemetry/core/backends/form_based_credentials_backend.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/core/backends/form_based_credentials_backend.py
+++ b/telemetry/telemetry/core/backends/form_based_credentials_backend.py
@@ -78,9 +78,14 @@ class FormBasedCredentialsBackend(object):
logging.debug('Logging into %s account...' % self.credentials_type)
+ if 'url' in config:
+ url = config['url']
+ else:
+ url = self.url
+
try:
- logging.info('Loading %s...', self.url)
- tab.Navigate(self.url)
+ logging.info('Loading %s...', url)
+ tab.Navigate(url)
_WaitForLoginFormToLoad(self, self.login_form_id, tab)
if self.IsAlreadyLoggedIn(tab):
@@ -88,7 +93,7 @@ class FormBasedCredentialsBackend(object):
return True
tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
- logging.info('Loaded page: %s', self.url)
+ logging.info('Loaded page: %s', url)
email_id = 'document.querySelector("#%s").%s.value = "%s"; ' % (
self.login_form_id, self.login_input_id, config['username'])
@@ -102,7 +107,7 @@ class FormBasedCredentialsBackend(object):
self._logged_in = True
return True
except util.TimeoutException:
- logging.warning('Timed out while loading: %s', self.url)
+ logging.warning('Timed out while loading: %s', url)
return False
def LoginNoLongerNeeded(self, tab): # pylint: disable=W0613
|
[telemetry] Add credentials login url to be overridden
When working with staging systems, you need to be able to provide an
alternative login url.
R=tonyg,dtu
Review URL: <URL>
|
catapult-project_catapult
|
train
|
d9fc41ed7421a5765522de6d4f8300771254ae3b
|
diff --git a/tests/unit/concurrently/test_HTCondorJobSubmitter.py b/tests/unit/concurrently/test_HTCondorJobSubmitter.py
index <HASH>..<HASH> 100644
--- a/tests/unit/concurrently/test_HTCondorJobSubmitter.py
+++ b/tests/unit/concurrently/test_HTCondorJobSubmitter.py
@@ -6,6 +6,8 @@ import textwrap
import pytest
+pytestmark = pytest.mark.skip
+
try:
import unittest.mock as mock
except ImportError:
diff --git a/tests/unit/concurrently/test_condor.py b/tests/unit/concurrently/test_condor.py
index <HASH>..<HASH> 100644
--- a/tests/unit/concurrently/test_condor.py
+++ b/tests/unit/concurrently/test_condor.py
@@ -3,6 +3,8 @@ import sys
import pytest
+pytestmark = pytest.mark.skip
+
try:
import unittest.mock as mock
except ImportError:
|
skit tests for htcondor
|
alphatwirl_alphatwirl
|
train
|
e73f867464caf5d3fd030d41513768512b60010b
|
diff --git a/sdc/rabbit/publisher.py b/sdc/rabbit/publisher.py
index <HASH>..<HASH> 100644
--- a/sdc/rabbit/publisher.py
+++ b/sdc/rabbit/publisher.py
@@ -101,11 +101,6 @@ class QueuePublisher(object):
logger.debug("Publishing message")
try:
self._connect()
- except pika.exceptions.AMQPConnectionError:
- logger.error("Message not published. RetryableError raised")
- raise PublishMessageError
-
- try:
result = self._channel.basic_publish(exchange='',
routing_key=self._queue,
mandatory=mandatory,
@@ -119,6 +114,9 @@ class QueuePublisher(object):
logger.info('Published message to queue queue={}'.format(self._queue))
return result
+ except pika.exceptions.AMQPConnectionError:
+ logger.error("Message not published. RetryableError raised")
+ raise PublishMessageError
except NackError:
# raised when a message published in publisher-acknowledgments mode
# is returned via `Basic.Return` followed by `Basic.Ack`.
|
Reduce the about of try/except blocks
|
ONSdigital_sdc-rabbit
|
train
|
4da1be0423975ca5da8282802e949fac3058f5a2
|
diff --git a/openstack_dashboard/dashboards/project/images/images/forms.py b/openstack_dashboard/dashboards/project/images/images/forms.py
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/dashboards/project/images/images/forms.py
+++ b/openstack_dashboard/dashboards/project/images/images/forms.py
@@ -84,7 +84,6 @@ class CreateImageForm(forms.SelfHandlingForm):
name = forms.CharField(max_length=255, label=_("Name"))
description = forms.CharField(max_length=255, label=_("Description"),
required=False)
-
source_type = forms.ChoiceField(
label=_('Image Source'),
required=False,
@@ -93,19 +92,17 @@ class CreateImageForm(forms.SelfHandlingForm):
widget=forms.Select(attrs={
'class': 'switchable',
'data-slug': 'source'}))
-
- image_url = forms.CharField(max_length=255,
- label=_("Image Location"),
- help_text=_("An external (HTTP) URL to load "
- "the image from."),
- widget=forms.TextInput(attrs={
- 'class': 'switched',
- 'data-switch-on': 'source',
- 'data-source-url': _('Image Location'),
- 'ng-model': 'copyFrom',
- 'ng-change':
- 'selectImageFormat(copyFrom)'}),
- required=False)
+ image_url = forms.URLField(label=_("Image Location"),
+ help_text=_("An external (HTTP) URL to load "
+ "the image from."),
+ widget=forms.TextInput(attrs={
+ 'class': 'switched',
+ 'data-switch-on': 'source',
+ 'data-source-url': _('Image Location'),
+ 'ng-model': 'copyFrom',
+ 'ng-change':
+ 'selectImageFormat(copyFrom)'}),
+ required=False)
image_file = forms.FileField(label=_("Image File"),
help_text=_("A local image to upload."),
widget=forms.FileInput(attrs={
|
Use URLField instead of CharField for image_url
The image location for 'create image' is an external url to load the
image from, so it's more suitable to use URLField instead of CharField.
Change-Id: Ib<I>dbd<I>ec<I>df<I>b<I>ffe<I>a0a
Closes-bug: #<I>
|
openstack_horizon
|
train
|
5b13909aba6bd04e643a7c2063cc293807010f31
|
diff --git a/src/level/TMXTiledMap.js b/src/level/TMXTiledMap.js
index <HASH>..<HASH> 100644
--- a/src/level/TMXTiledMap.js
+++ b/src/level/TMXTiledMap.js
@@ -99,6 +99,9 @@
* @ignore
*/
function readImageLayer(map, data, z) {
+ // Normalize properties
+ me.TMXUtils.applyTMXProperties(data.properties, data);
+
// create the layer
var imageLayer = new me.ImageLayer(
+data.x || 0,
diff --git a/src/level/TMXUtils.js b/src/level/TMXUtils.js
index <HASH>..<HASH> 100644
--- a/src/level/TMXUtils.js
+++ b/src/level/TMXUtils.js
@@ -27,7 +27,11 @@
* @ignore
*/
function setTMXValue(name, value) {
- value = "" + value;
+ if (typeof(value) !== "string") {
+ // Value is already normalized
+ return value;
+ }
+
if (!value || value.isBoolean()) {
// if value not defined or boolean
value = value ? (value === "true") : true;
|
Fix ImageLayer property normalization with JSON format maps
- Broken by 6cec<I>c4c1a1ecab<I>edb<I>d<I>a7bcb<I>a<I>c
|
melonjs_melonJS
|
train
|
a4ce9ebfe5d8a1336cd441ee68baf1db04abdcea
|
diff --git a/cf/app_files/app_files.go b/cf/app_files/app_files.go
index <HASH>..<HASH> 100644
--- a/cf/app_files/app_files.go
+++ b/cf/app_files/app_files.go
@@ -139,9 +139,9 @@ func (appfiles ApplicationFiles) WalkAppFiles(dir string, onEachFile func(string
}
if runtime.GOOS == "windows" {
- fi, err := os.Lstat(`\\?\` + fullPath)
- if err != nil {
- return err
+ fi, statErr := os.Lstat(`\\?\` + fullPath)
+ if statErr != nil {
+ return statErr
}
if fi.IsDir() {
|
Fix go vet issue in app_files
|
cloudfoundry_cli
|
train
|
7b923d6c72be29e2fe57740c9ea3a2135e7db6f7
|
diff --git a/tests/thread/stress_aes.py b/tests/thread/stress_aes.py
index <HASH>..<HASH> 100644
--- a/tests/thread/stress_aes.py
+++ b/tests/thread/stress_aes.py
@@ -235,7 +235,7 @@ class LockedCounter:
count = LockedCounter()
-def thread_entry():
+def thread_entry(n_loop):
global count
aes = AES(256)
@@ -244,7 +244,7 @@ def thread_entry():
data = bytearray(128)
# from now on we don't use the heap
- for loop in range(5):
+ for loop in range(n_loop):
# encrypt
aes.set_key(key)
aes.set_iv(iv)
@@ -265,8 +265,20 @@ def thread_entry():
if __name__ == "__main__":
- n_thread = 20
+ import sys
+
+ if sys.platform == "rp2":
+ n_thread = 1
+ n_loop = 2
+ elif sys.platform in ("esp32", "pyboard"):
+ n_thread = 2
+ n_loop = 2
+ else:
+ n_thread = 20
+ n_loop = 5
for i in range(n_thread):
- _thread.start_new_thread(thread_entry, ())
+ _thread.start_new_thread(thread_entry, (n_loop,))
+ thread_entry(n_loop)
while count.value < n_thread:
time.sleep(1)
+ print("done")
|
tests/thread: Make stress_aes.py test run on bare-metal ports.
This is a long-running test, so make it run in reasonable time on slower,
bare-metal ports.
|
micropython_micropython
|
train
|
a01947e1e9c214490fb628516d625e028b76cd43
|
diff --git a/django_geoip/models.py b/django_geoip/models.py
index <HASH>..<HASH> 100644
--- a/django_geoip/models.py
+++ b/django_geoip/models.py
@@ -159,13 +159,13 @@ class GeoLocationFacade(models.Model):
class GeoLocationFascade(GeoLocationFacade):
""" Old alias with a typo """
- def __init__(self, **kwargs):
+ def __init__(self, *args, **kwargs):
warnings.warn(
_("GeoLocationFascade has been renamed to GeoLocationFacade, please update your code."
"Alias will be removed in 0.3"),
DeprecationWarning
)
- super(GeoLocationFascade, self).__init__(**kwargs)
+ super(GeoLocationFascade, self).__init__(*args, **kwargs)
class Meta:
abstract = True
\ No newline at end of file
|
Fixing init signature for deprecated class
#<I>
|
futurecolors_django-geoip
|
train
|
31c0f0a911c16ad854bc11cac1bb602c5f0a8ef0
|
diff --git a/pkg/cmd/cli/describer.go b/pkg/cmd/cli/describer.go
index <HASH>..<HASH> 100644
--- a/pkg/cmd/cli/describer.go
+++ b/pkg/cmd/cli/describer.go
@@ -1,6 +1,7 @@
package cli
import (
+ "fmt"
"strings"
"text/tabwriter"
@@ -40,8 +41,37 @@ type BuildDescriber struct {
client.Interface
}
+func (d *BuildDescriber) DescribeUser(out *tabwriter.Writer, label string, u buildapi.SourceControlUser) {
+ if len(u.Name) > 0 && len(u.Email) > 0 {
+ formatString(out, label, fmt.Sprintf("%s <%s>", u.Name, u.Email))
+ return
+ }
+ if len(u.Name) > 0 {
+ formatString(out, label, u.Name)
+ return
+ }
+ if len(u.Email) > 0 {
+ formatString(out, label, u.Email)
+ }
+}
+
func (d *BuildDescriber) DescribeParameters(p buildapi.BuildParameters, out *tabwriter.Writer) {
formatString(out, "Strategy", p.Strategy.Type)
+ switch p.Strategy.Type {
+ case buildapi.DockerBuildStrategyType:
+ if p.Strategy.DockerStrategy != nil && len(p.Strategy.DockerStrategy.ContextDir) == 0 {
+ formatString(out, "Context Directory", p.Strategy.DockerStrategy.ContextDir)
+ }
+ if p.Strategy.DockerStrategy != nil && p.Strategy.DockerStrategy.NoCache {
+ formatString(out, "No Cache", "yes")
+ }
+
+ case buildapi.STIBuildStrategyType:
+ formatString(out, "Builder Image", p.Strategy.STIStrategy.BuilderImage)
+ if p.Strategy.STIStrategy.Clean {
+ formatString(out, "Clean Build", "yes")
+ }
+ }
formatString(out, "Source Type", p.Source.Type)
if p.Source.Git != nil {
formatString(out, "URL", p.Source.Git.URI)
@@ -51,6 +81,14 @@ func (d *BuildDescriber) DescribeParameters(p buildapi.BuildParameters, out *tab
}
formatString(out, "Output Image", p.Output.ImageTag)
formatString(out, "Output Registry", p.Output.Registry)
+ if p.Revision != nil && p.Revision.Type == buildapi.BuildSourceGit && p.Revision.Git != nil {
+ formatString(out, "Git Commit", p.Revision.Git.Commit)
+ d.DescribeUser(out, "Revision Author", p.Revision.Git.Author)
+ d.DescribeUser(out, "Revision Committer", p.Revision.Git.Committer)
+ if len(p.Revision.Git.Message) > 0 {
+ formatString(out, "Revision Message", p.Revision.Git.Message)
+ }
+ }
}
func (d *BuildDescriber) Describe(namespace, name string) (string, error) {
|
Add strategy and revision output to Build describer
|
openshift_origin
|
train
|
b2f869d8a23f891d2c1d52da9d63666fbbdf954d
|
diff --git a/tasklib/tests.py b/tasklib/tests.py
index <HASH>..<HASH> 100644
--- a/tasklib/tests.py
+++ b/tasklib/tests.py
@@ -4,7 +4,7 @@ import shutil
import tempfile
import unittest
-from .task import TaskWarrior
+from .task import TaskWarrior, Task
class TasklibTest(unittest.TestCase):
@@ -23,24 +23,24 @@ class TaskFilterTest(TasklibTest):
self.assertEqual(len(self.tw.tasks.all()), 0)
def test_all_non_empty(self):
- self.tw.execute_command(['add', 'test task'])
+ Task(self.tw, description="test task").save()
self.assertEqual(len(self.tw.tasks.all()), 1)
self.assertEqual(self.tw.tasks.all()[0]['description'], 'test task')
self.assertEqual(self.tw.tasks.all()[0]['status'], 'pending')
def test_pending_non_empty(self):
- self.tw.execute_command(['add', 'test task'])
+ Task(self.tw, description="test task").save()
self.assertEqual(len(self.tw.tasks.pending()), 1)
self.assertEqual(self.tw.tasks.pending()[0]['description'],
'test task')
self.assertEqual(self.tw.tasks.pending()[0]['status'], 'pending')
def test_completed_empty(self):
- self.tw.execute_command(['add', 'test task'])
+ Task(self.tw, description="test task").save()
self.assertEqual(len(self.tw.tasks.completed()), 0)
def test_completed_non_empty(self):
- self.tw.execute_command(['add', 'test task'])
+ Task(self.tw, description="test task").save()
self.assertEqual(len(self.tw.tasks.completed()), 0)
self.tw.tasks.all()[0].done()
self.assertEqual(len(self.tw.tasks.completed()), 1)
@@ -50,7 +50,7 @@ class AnnotationTest(TasklibTest):
def setUp(self):
super(AnnotationTest, self).setUp()
- self.tw.execute_command(['add', 'test task'])
+ Task(self.tw, description="test task").save()
def test_adding_annotation(self):
task = self.tw.tasks.get()
@@ -83,9 +83,9 @@ class AnnotationTest(TasklibTest):
class UnicodeTest(TasklibTest):
def test_unicode_task(self):
- self.tw.execute_command(['add', '†åßk'])
+ Task(self.tw, description="†åßk").save()
self.tw.tasks.get()
def test_non_unicode_task(self):
- self.tw.execute_command(['add', 'task'])
+ Task(self.tw, description="test task").save()
self.tw.tasks.get()
|
tests: Do not use TW directly to create tasks
|
robgolding_tasklib
|
train
|
1e68b834a6bb047ca83d3c588847d34f47a6a637
|
diff --git a/xwiki-commons-core/xwiki-commons-job/src/test/java/org/xwiki/job/internal/DefaultJobProgressTest.java b/xwiki-commons-core/xwiki-commons-job/src/test/java/org/xwiki/job/internal/DefaultJobProgressTest.java
index <HASH>..<HASH> 100644
--- a/xwiki-commons-core/xwiki-commons-job/src/test/java/org/xwiki/job/internal/DefaultJobProgressTest.java
+++ b/xwiki-commons-core/xwiki-commons-job/src/test/java/org/xwiki/job/internal/DefaultJobProgressTest.java
@@ -376,6 +376,7 @@ public class DefaultJobProgressTest
Object source1 = "source1";
Object source11 = "source11";
Object source12 = "source12";
+ Object source1b = "source1b";
// Root level
this.observation.notify(new PushLevelProgressEvent(), source1, null);
@@ -391,7 +392,7 @@ public class DefaultJobProgressTest
assertEquals(1, this.progress.getRootStep().getChildren().size());
assertEquals(1, this.progress.getRootStep().getChildren().get(0).getChildren().size());
- // Close the step, back to source1 level
+ // Close the step
this.observation.notify(new EndStepProgressEvent(), source11, null);
// Start first step in source12 level
@@ -400,7 +401,7 @@ public class DefaultJobProgressTest
assertEquals(1, this.progress.getRootStep().getChildren().size());
assertEquals(2, this.progress.getRootStep().getChildren().get(0).getChildren().size());
- // Close the step, back to source1 level
+ // Close the step
this.observation.notify(new EndStepProgressEvent(), source12, null);
// Start second step in source1 level
@@ -408,5 +409,17 @@ public class DefaultJobProgressTest
assertEquals(2, this.progress.getRootStep().getChildren().size());
assertEquals(2, this.progress.getRootStep().getChildren().get(0).getChildren().size());
+ assertEquals(0, this.progress.getRootStep().getChildren().get(1).getChildren().size());
+
+ // Close the step
+ this.observation.notify(new EndStepProgressEvent(), source1, null);
+
+ // Start third step in source1 level (but with a different source)
+ this.observation.notify(new StartStepProgressEvent(), source1b, null);
+
+ assertEquals(3, this.progress.getRootStep().getChildren().size());
+ assertEquals(2, this.progress.getRootStep().getChildren().get(0).getChildren().size());
+ assertEquals(0, this.progress.getRootStep().getChildren().get(1).getChildren().size());
+ assertEquals(0, this.progress.getRootStep().getChildren().get(2).getChildren().size());
}
}
|
XCOMMONS-<I>: When starting/stoping a progress step with a different source, the progress tree might get broken
|
xwiki_xwiki-commons
|
train
|
c008d010f9fa6ec9c4ea8ccd25641d10833ee61a
|
diff --git a/stories/RenderCounter/DivRefreshable.js b/stories/RenderCounter/DivRefreshable.js
index <HASH>..<HASH> 100644
--- a/stories/RenderCounter/DivRefreshable.js
+++ b/stories/RenderCounter/DivRefreshable.js
@@ -10,7 +10,7 @@ import withNestHandlers from './withNestHandlers';
const DivRefreshable = ({ label, onRefresh, children, cloneChild, ...rest }) => (
<div {..._.pick(rest, ['style'])}>
- <button onClick={() => onRefresh()}>{label}</button>
+ <button onClick={onRefresh}>{label}</button>
{children && (cloneChild ? React.cloneElement(children) : children)}
</div>
);
@@ -31,11 +31,13 @@ const defaultProps = {
DivRefreshable.propTypes = propTypes;
DivRefreshable.defaultProps = defaultProps;
+const onRefresh = ({ setState }) => (/* event */) => setState();
+
const hoc = Component => compose(
extendPropTypes({ onRefresh: T.func }),
copyStatics(Component),
- withState('state', '_onRefresh'),
- withNestHandlers({ onRefresh: '_onRefresh' }),
+ withState('state', 'setState'),
+ withNestHandlers({ onRefresh }),
)(Component);
export default hoc(DivRefreshable);
diff --git a/stories/RenderCounter/RenderCounter.story.js b/stories/RenderCounter/RenderCounter.story.js
index <HASH>..<HASH> 100644
--- a/stories/RenderCounter/RenderCounter.story.js
+++ b/stories/RenderCounter/RenderCounter.story.js
@@ -41,14 +41,15 @@ const description = (
</div>
);
-const onRefreshInPossibitly = (possibility = 0.5, log = action('onRefresh')) => (context) => {
- if (Math.random() < possibility) {
- context.next();
- log('hit', context.props);
- } else {
- log('miss', context.props);
- }
-};
+const onRefreshInPossibitly = (possibility = 0.5, log = action('onRefresh')) =>
+ (props, next) => (event) => {
+ if (Math.random() < possibility) {
+ next();
+ log('hit', props, event);
+ } else {
+ log('miss', props, event);
+ }
+ };
stories.addWithInfo('inside DivRefreshable', description, () => {
const possibility = number('possibility', 0.5);
diff --git a/stories/RenderCounter/withNestHandlers.js b/stories/RenderCounter/withNestHandlers.js
index <HASH>..<HASH> 100644
--- a/stories/RenderCounter/withNestHandlers.js
+++ b/stories/RenderCounter/withNestHandlers.js
@@ -1,11 +1,17 @@
import _ from 'lodash';
import withHandlers from 'recompose/withHandlers';
-const createCallbackStyleHandler = ({ innerHandler, outerHandler, ...rest }) =>
- (...args) => outerHandler({
- ...rest,
- next: () => innerHandler(...args),
- }, ...args);
+const createCallbackStyleHandler = ({ innerHandler, outerHandler, props }) => (...args) => {
+ const next = () => innerHandler(...args);
+ let handler;
+ if (outerHandler.length > 1) {
+ handler = outerHandler(props, next);
+ } else {
+ next();
+ handler = outerHandler(props);
+ }
+ return handler(...args);
+};
export const nestHandler = (innerName, outerName) => (props) => {
let innerHandler;
diff --git a/stories/__tests__/__snapshots__/stories.test.js.snap b/stories/__tests__/__snapshots__/stories.test.js.snap
index <HASH>..<HASH> 100644
--- a/stories/__tests__/__snapshots__/stories.test.js.snap
+++ b/stories/__tests__/__snapshots__/stories.test.js.snap
@@ -1620,14 +1620,14 @@ exports[`Storyshots RenderCounter inside DivRefreshable 1`] = `
}
}
>
- function (context) {
- if (Math.random() < possibility) {
- context.next();
- log('hit', context.props);
- } else {
- log('miss', context.props);
- }
- }()
+ function (props, next) {return function (event) {
+ if (Math.random() < possibility) {
+ next();
+ log('hit', props, event);
+ } else {
+ log('miss', props, event);
+ }
+ };}()
</span>
</span>
</span>
|
refactor(withNestHandlers): pass next if argLen>1
|
Stupidism_stupid-rc-starter
|
train
|
dea1343e749fcf998b0d283e738917d193491f50
|
diff --git a/test/k8sT/Services.go b/test/k8sT/Services.go
index <HASH>..<HASH> 100644
--- a/test/k8sT/Services.go
+++ b/test/k8sT/Services.go
@@ -1037,7 +1037,7 @@ Secondary Interface %s :: IPv4: (%s, %s), IPv6: (%s, %s)`, helpers.DualStackSupp
})
})
- Context("Tests with direct routing", func() {
+ SkipContextIf(helpers.SkipQuarantined, "Tests with direct routing", func() {
var directRoutingOpts = map[string]string{
"tunnel": "disabled",
|
test/Services: Quarantine 'Tests with direct routing'
CC: Martynas Pumputis <<EMAIL>>
|
cilium_cilium
|
train
|
1ba8128445cf7f6751c8a3ecb2565e7e02be5ada
|
diff --git a/src/RangeCalendar.js b/src/RangeCalendar.js
index <HASH>..<HASH> 100644
--- a/src/RangeCalendar.js
+++ b/src/RangeCalendar.js
@@ -1,4 +1,5 @@
import React, { PropTypes } from 'react';
+import { findDOMNode } from 'react-dom';
import GregorianCalendar from 'gregorian-calendar';
import classnames from 'classnames';
import CalendarPart from './range-calendar/CalendarPart';
@@ -204,6 +205,10 @@ const RangeCalendar = React.createClass({
props.onValueChange(value);
},
+ focus() {
+ findDOMNode(this).focus();
+ },
+
clear() {
this.fireSelectValueChange([], true);
this.props.onClear();
|
Fix RangePicker focus error
close ant-design/ant-design#<I>
|
react-component_calendar
|
train
|
a6b18ae120f4a8ba74b255975c21ce9c730266a6
|
diff --git a/modules/adfBidAdapter.js b/modules/adfBidAdapter.js
index <HASH>..<HASH> 100644
--- a/modules/adfBidAdapter.js
+++ b/modules/adfBidAdapter.js
@@ -15,7 +15,10 @@ const { getConfig } = config;
const BIDDER_CODE = 'adf';
const GVLID = 50;
-const BIDDER_ALIAS = [ { code: 'adformOpenRTB', gvlid: GVLID } ];
+const BIDDER_ALIAS = [
+ { code: 'adformOpenRTB', gvlid: GVLID },
+ { code: 'adform', gvlid: GVLID }
+];
const NATIVE_ASSET_IDS = { 0: 'title', 2: 'icon', 3: 'image', 5: 'sponsoredBy', 4: 'body', 1: 'cta' };
const NATIVE_PARAMS = {
title: {
diff --git a/test/spec/modules/adfBidAdapter_spec.js b/test/spec/modules/adfBidAdapter_spec.js
index <HASH>..<HASH> 100644
--- a/test/spec/modules/adfBidAdapter_spec.js
+++ b/test/spec/modules/adfBidAdapter_spec.js
@@ -1,12 +1,10 @@
// jshint esversion: 6, es3: false, node: true
-import {assert, expect} from 'chai';
-import {spec} from 'modules/adfBidAdapter.js';
-import { NATIVE } from 'src/mediaTypes.js';
+import { assert } from 'chai';
+import { spec } from 'modules/adfBidAdapter.js';
import { config } from 'src/config.js';
import { createEidsArray } from 'modules/userId/eids.js';
describe('Adf adapter', function () {
- let serverResponse, bidRequest, bidResponses;
let bids = [];
describe('backwards-compatibility', function () {
@@ -14,6 +12,11 @@ describe('Adf adapter', function () {
assert.equal(spec.aliases[0].code, 'adformOpenRTB');
assert.equal(spec.aliases[0].gvlid, 50);
});
+
+ it('should have adform alias defined', function () {
+ assert.equal(spec.aliases[1].code, 'adform');
+ assert.equal(spec.aliases[1].gvlid, 50);
+ });
});
describe('isBidRequestValid', function () {
|
Adf Bid Adapter: add adform alias (#<I>)
|
prebid_Prebid.js
|
train
|
f489a00deec0e8ebe8574c83d8cca3f5b856ce4f
|
diff --git a/packages/node_modules/@webex/internal-plugin-conversation/test/integration/spec/verbs.js b/packages/node_modules/@webex/internal-plugin-conversation/test/integration/spec/verbs.js
index <HASH>..<HASH> 100644
--- a/packages/node_modules/@webex/internal-plugin-conversation/test/integration/spec/verbs.js
+++ b/packages/node_modules/@webex/internal-plugin-conversation/test/integration/spec/verbs.js
@@ -4,9 +4,8 @@
import '@webex/internal-plugin-conversation';
-import {Defer, patterns} from '@webex/common';
+import {patterns} from '@webex/common';
import WebexCore, {WebexHttpError} from '@webex/webex-core';
-import sinon from 'sinon';
import {assert} from '@webex/test-helper-chai';
import testUsers from '@webex/test-helper-test-users';
import {find, map} from 'lodash';
@@ -465,30 +464,14 @@ describe('plugin-conversation', function () {
});
describe('#updateTypingStatus()', () => {
- let blockUntilMercuryStart;
- const startTypingSpy = sinon.spy();
-
- beforeEach(() => {
- blockUntilMercuryStart = new Defer();
- mccoy.webex.internal.mercury.on('event:status.start_typing', () => {
- startTypingSpy();
- blockUntilMercuryStart.resolve();
- });
-
- return webex.internal.conversation.create({participants, comment: 'THIS IS A COMMENT'})
- .then((c) => {
- conversation = c;
- });
- });
-
- afterEach(() => {
- startTypingSpy.resetHistory();
- });
+ beforeEach(() => webex.internal.conversation.create({participants, comment: 'THIS IS A COMMENT'})
+ .then((c) => {
+ conversation = c;
+ }));
it('sets the typing indicator for the specified conversation', () => webex.internal.conversation.updateTypingStatus(conversation, {typing: true})
- .then(() => blockUntilMercuryStart.promise)
- .then(() => {
- assert.calledOnce(startTypingSpy);
+ .then(({statusCode}) => {
+ assert.equal(statusCode, 204);
}));
it('clears the typing indicator for the specified conversation', () => webex.internal.conversation.updateTypingStatus(conversation, {typing: false})
@@ -512,9 +495,8 @@ describe('plugin-conversation', function () {
Reflect.deleteProperty(conversation, 'id');
return webex.internal.conversation.updateTypingStatus(conversation, {typing: true})
- .then(() => blockUntilMercuryStart.promise)
- .then(() => {
- assert.called(startTypingSpy);
+ .then(({statusCode}) => {
+ assert.equal(statusCode, 204);
});
});
});
|
test(i-p-conversation): remove mercury logic from typing tests
|
webex_spark-js-sdk
|
train
|
f734d842f5ee2e67be253dd78784664e8fc3bac0
|
diff --git a/client/driver/qemu.go b/client/driver/qemu.go
index <HASH>..<HASH> 100644
--- a/client/driver/qemu.go
+++ b/client/driver/qemu.go
@@ -33,6 +33,7 @@ var (
// Prior to qemu 2.10.1, monitor socket paths are truncated to 108 bytes.
// We should consider this if driver.qemu.version is < 2.10.1 and the
// generated monitor path is too long.
+
//
// Relevant fix is here:
// https://github.com/qemu/qemu/commit/ad9579aaa16d5b385922d49edac2c96c79bcfb6
@@ -240,11 +241,14 @@ func (d *QemuDriver) Start(ctx *ExecContext, task *structs.Task) (*StartResponse
var monitorPath string
if d.driverConfig.GracefulShutdown {
+ if runtime.GOOS == "windows" {
+ return nil, errors.New("QEMU graceful shutdown is unsupported on the Windows platform")
+ }
// This socket will be used to manage the virtual machine (for example,
// to perform graceful shutdowns)
monitorPath, err := d.getMonitorPath(ctx.TaskDir.Dir)
if err != nil {
- d.logger.Printf("[ERR] driver.qemu: could not get qemu monitor path - error: %s", err)
+ d.logger.Printf("[ERR] driver.qemu: could not get qemu monitor path: %s", err)
return nil, err
}
d.logger.Printf("[DEBUG] driver.qemu: got monitor path OK: %s", monitorPath)
@@ -292,6 +296,9 @@ func (d *QemuDriver) Start(ctx *ExecContext, task *structs.Task) (*StartResponse
// If using KVM, add optimization args
if accelerator == "kvm" {
+ if runtime.GOOS == "windows" {
+ return nil, errors.New("KVM accelerator is unsupported on the Windows platform")
+ }
args = append(args,
"-enable-kvm",
"-cpu", "host",
@@ -444,10 +451,19 @@ func (h *qemuHandle) Signal(s os.Signal) error {
}
func (h *qemuHandle) Kill() error {
- // First, try sending a graceful shutdown command via the qemu monitor
- if err := sendQemuShutdown(h.logger, h.monitorPath, h.userPid); err != nil {
- h.logger.Printf("[DEBUG] driver.qemu: error sending graceful shutdown for user process pid %d: %s", h.userPid, err)
- // Issue an interrupt to the qemu process as a last resort
+ gracefulShutdownSent := false
+ // Attempt a graceful shutdown only if it was configured in the job
+ if h.monitorPath != "" {
+ if err := sendQemuShutdown(h.logger, h.monitorPath, h.userPid); err == nil {
+ gracefulShutdownSent = true
+ } else {
+ h.logger.Printf("[DEBUG] driver.qemu: error sending graceful shutdown for user process pid %d: %s", h.userPid, err)
+ }
+ }
+
+ // If Nomad did not send a graceful shutdown signal, issue an interrupt to
+ // the qemu process as a last resort
+ if gracefulShutdownSent == false {
if err := h.executor.ShutDown(); err != nil {
if h.pluginClient.Exited() {
return nil
@@ -501,7 +517,6 @@ func (h *qemuHandle) run() {
// monitor
func sendQemuShutdown(logger *log.Logger, monitorPath string, userPid int) error {
if monitorPath == "" {
- logger.Printf("[DEBUG] driver.qemu: monitorPath not set; will not attempt graceful shutdown for user process pid %d", userPid)
return errors.New("monitorPath not set")
}
monitorSocket, err := net.Dial("unix", monitorPath)
|
Qemu driver: clean up logging; fail unsupported features on Windows
|
hashicorp_nomad
|
train
|
de444867d3de7abcb6e15e456a63672b3b2a6cb0
|
diff --git a/packer/environment_test.go b/packer/environment_test.go
index <HASH>..<HASH> 100644
--- a/packer/environment_test.go
+++ b/packer/environment_test.go
@@ -3,6 +3,7 @@ package packer
import (
"bytes"
"cgl.tideland.biz/asserts"
+ "errors"
"fmt"
"os"
"strings"
@@ -67,6 +68,31 @@ func TestEnvironment_Builder(t *testing.T) {
assert.Equal(returnedBuilder, builder, "should return correct builder")
}
+func TestEnvironment_Builder_NilError(t *testing.T) {
+ assert := asserts.NewTestingAsserts(t, true)
+
+ config := DefaultEnvironmentConfig()
+ config.BuilderFunc = func(n string) (Builder, error) { return nil, nil }
+
+ env, _ := NewEnvironment(config)
+ returnedBuilder, err := env.Builder("foo")
+ assert.NotNil(err, "should be an error")
+ assert.Nil(returnedBuilder, "should be no builder")
+}
+
+func TestEnvironment_Builder_Error(t *testing.T) {
+ assert := asserts.NewTestingAsserts(t, true)
+
+ config := DefaultEnvironmentConfig()
+ config.BuilderFunc = func(n string) (Builder, error) { return nil, errors.New("foo") }
+
+ env, _ := NewEnvironment(config)
+ returnedBuilder, err := env.Builder("foo")
+ assert.NotNil(err, "should be an error")
+ assert.Equal(err.Error(), "foo", "should be correct error")
+ assert.Nil(returnedBuilder, "should be no builder")
+}
+
func TestEnvironment_Cli_CallsRun(t *testing.T) {
assert := asserts.NewTestingAsserts(t, true)
|
packer: Tests for the Builder error cases
|
hashicorp_packer
|
train
|
d92690dd9ff4c365b0ed73e838843e0add528de7
|
diff --git a/connection.go b/connection.go
index <HASH>..<HASH> 100644
--- a/connection.go
+++ b/connection.go
@@ -162,20 +162,26 @@ func (connection *redisConnection) getConsumingQueues() ([]string, error) {
// heartbeat keeps the heartbeat key alive
func (connection *redisConnection) heartbeat(errors chan<- error) {
+ errorCount := 0 // number of consecutive errors
for range time.NewTicker(heartbeatInterval).C {
if connection.heartbeatStopped {
return
}
- if err := connection.updateHeartbeat(); err != nil {
- select { // try to add error to channel, but don't block
- // TODO!: add error count or similar?
- case errors <- &HeartbeatError{RedisErr: err}:
- default:
- }
+ err := connection.updateHeartbeat()
+ if err == nil { // success
+ errorCount = 0
+ continue
+ }
+ // unexpected redis error
- // TODO!: stop all consuming at some point (after 40s?)
+ errorCount++
+ select { // try to add error to channel, but don't block
+ case errors <- &HeartbeatError{RedisErr: err, Count: errorCount}:
+ default:
}
+
+ // TODO!: stop all consuming at some point (after 40s?)
}
}
diff --git a/errors.go b/errors.go
index <HASH>..<HASH> 100644
--- a/errors.go
+++ b/errors.go
@@ -1,17 +1,21 @@
package rmq
+import "fmt"
+
type ConsumeError struct {
RedisErr error
+ Count int // number of consecutive errors
}
func (e *ConsumeError) Error() string {
- return "rmq.ConsumeError: " + e.RedisErr.Error()
+ return fmt.Sprintf("rmq.ConsumeError (%d): %s", e.Count, e.RedisErr.Error())
}
type HeartbeatError struct {
RedisErr error
+ Count int // number of consecutive errors
}
func (e *HeartbeatError) Error() string {
- return "rmq.HeartbeatError: " + e.RedisErr.Error()
+ return fmt.Sprintf("rmq.HeartbeatError (%d): %s", e.Count, e.RedisErr.Error())
}
diff --git a/queue.go b/queue.go
index <HASH>..<HASH> 100644
--- a/queue.go
+++ b/queue.go
@@ -327,7 +327,7 @@ func (queue *redisQueue) consume(errors chan<- error) {
default: // redis error
errorCount++
select { // try to add error to channel, but don't block
- case errors <- &ConsumeError{RedisErr: err}:
+ case errors <- &ConsumeError{RedisErr: err, Count: errorCount}:
default:
}
time.Sleep(queue.pollDuration) // sleep before retry
@@ -349,7 +349,7 @@ func (queue *redisQueue) consumeBatch() error {
batchSize := queue.prefetchLimit - unackedCount
if batchSize <= 0 {
// already at prefetch limit, wait for consumers to finish
- time.Sleep(queue.pollDuration)
+ time.Sleep(queue.pollDuration) // sleep before retry
return nil
}
|
Add error count to heartbeat and consume errors
So the caller can see how often these errors happened consecutively.
|
adjust_rmq
|
train
|
80d9d7cc31f3ee99da6af0e66fa608cfa60ad703
|
diff --git a/packages/material-ui/src/Tooltip/Tooltip.js b/packages/material-ui/src/Tooltip/Tooltip.js
index <HASH>..<HASH> 100644
--- a/packages/material-ui/src/Tooltip/Tooltip.js
+++ b/packages/material-ui/src/Tooltip/Tooltip.js
@@ -482,6 +482,19 @@ const Tooltip = React.forwardRef(function Tooltip(props, ref) {
}
}
+ // Avoid the creation of a new Popper.js instance at each render.
+ const popperOptions = React.useMemo(
+ () => ({
+ modifiers: {
+ arrow: {
+ enabled: Boolean(arrowRef),
+ element: arrowRef,
+ },
+ },
+ }),
+ [arrowRef],
+ );
+
return (
<React.Fragment>
{React.cloneElement(children, { ref: handleRef, ...childrenProps })}
@@ -495,14 +508,7 @@ const Tooltip = React.forwardRef(function Tooltip(props, ref) {
open={childNode ? open : false}
id={childrenProps['aria-describedby']}
transition
- popperOptions={{
- modifiers: {
- arrow: {
- enabled: Boolean(arrowRef),
- element: arrowRef,
- },
- },
- }}
+ popperOptions={popperOptions}
{...interactiveWrapperListeners}
{...PopperProps}
>
diff --git a/packages/material-ui/src/Tooltip/Tooltip.test.js b/packages/material-ui/src/Tooltip/Tooltip.test.js
index <HASH>..<HASH> 100644
--- a/packages/material-ui/src/Tooltip/Tooltip.test.js
+++ b/packages/material-ui/src/Tooltip/Tooltip.test.js
@@ -220,10 +220,10 @@ describe('<Tooltip />', () => {
it('should use hysteresis with the enterDelay', () => {
const { container } = render(
<Tooltip
+ {...defaultProps}
enterDelay={111}
leaveDelay={5}
TransitionProps={{ timeout: 6 }}
- {...defaultProps}
/>,
);
const children = container.querySelector('#testChild');
@@ -466,4 +466,20 @@ describe('<Tooltip />', () => {
);
});
});
+
+ it('should use the same popper.js instance between two renders', () => {
+ const popperRef = React.createRef();
+ const { forceUpdate } = render(
+ <Tooltip
+ {...defaultProps}
+ open
+ PopperProps={{
+ popperRef,
+ }}
+ />,
+ );
+ const firstPopperInstance = popperRef.current;
+ forceUpdate();
+ expect(firstPopperInstance).to.equal(popperRef.current);
+ });
});
diff --git a/test/utils/createClientRender.js b/test/utils/createClientRender.js
index <HASH>..<HASH> 100644
--- a/test/utils/createClientRender.js
+++ b/test/utils/createClientRender.js
@@ -63,6 +63,15 @@ function clientRender(element, options = {}) {
return result;
};
+ result.forceUpdate = function forceUpdate() {
+ result.rerender(
+ React.cloneElement(element, {
+ 'data-force-update': String(Math.random()),
+ }),
+ );
+ return result;
+ };
+
return result;
}
|
[Tooltip] Fix popper.js re-instantiation (#<I>)
|
mui-org_material-ui
|
train
|
6fde40915316dbc378f5932136ddb14a522cb416
|
diff --git a/src/Backbone.CollectionView.js b/src/Backbone.CollectionView.js
index <HASH>..<HASH> 100755
--- a/src/Backbone.CollectionView.js
+++ b/src/Backbone.CollectionView.js
@@ -781,7 +781,14 @@
if( clickedItemId )
{
- // a list item was clicked
+ // Exit if an unselectable item was clicked
+ if( _.isFunction( this.selectableModelsFilter ) &&
+ ! this.selectableModelsFilter.call( this, this._getModelByReferenceId( clickedItemId ) ) )
+ {
+ return;
+ }
+
+ // a selectable list item was clicked
if( this.selectMultiple && theEvent.shiftKey )
{
var firstSelectedItemIndex = -1;
|
Fixed bug with the behavior of clicking an unselectable item
|
rotundasoftware_backbone.collectionView
|
train
|
505077c6878734248c33a09b0b5bf755f720bb40
|
diff --git a/extension/rsb/com/src/main/java/org/openbase/jul/extension/rsb/com/RSBRemoteService.java b/extension/rsb/com/src/main/java/org/openbase/jul/extension/rsb/com/RSBRemoteService.java
index <HASH>..<HASH> 100644
--- a/extension/rsb/com/src/main/java/org/openbase/jul/extension/rsb/com/RSBRemoteService.java
+++ b/extension/rsb/com/src/main/java/org/openbase/jul/extension/rsb/com/RSBRemoteService.java
@@ -906,10 +906,13 @@ public abstract class RSBRemoteService<M extends GeneratedMessage> implements RS
throw ex;
} catch (final InvalidStateException ex) {
// reinit remote service because middleware connection lost!
- try {
- reinit();
- } catch (final CouldNotPerformException exx) {
- ExceptionPrinter.printHistory("Recovering middleware connection failed!", exx, logger);
+ // only if the connection has not been lost because of reconnecting
+ if (connectionState != ConnectionState.RECONNECTING) {
+ try {
+ reinit();
+ } catch (final CouldNotPerformException exx) {
+ ExceptionPrinter.printHistory("Recovering middleware connection failed!", exx, logger);
+ }
}
throw ex;
}
@@ -1514,10 +1517,13 @@ public abstract class RSBRemoteService<M extends GeneratedMessage> implements RS
throw ex;
} catch (final InvalidStateException ex) {
// reinit remote service because middleware connection lost!
- try {
- reinit();
- } catch (final CouldNotPerformException exx) {
- ExceptionPrinter.printHistory("Recovering middleware connection failed!", exx, logger);
+ // only if the connection has not been lost because of reconnecting
+ if (connectionState != ConnectionState.RECONNECTING) {
+ try {
+ reinit();
+ } catch (final CouldNotPerformException exx) {
+ ExceptionPrinter.printHistory("Recovering middleware connection failed!", exx, logger);
+ }
}
throw ex;
} catch (CouldNotPerformException ex) {
|
reinit in RSBRemoteService is now skipped from ping and asynMethodCall of the InvalidState is triggered by another thread reinitializing
|
openbase_jul
|
train
|
cb285221eccd51e76a8ed9db948c3f4806b7ead5
|
diff --git a/Lib/fontMath/mathKerning.py b/Lib/fontMath/mathKerning.py
index <HASH>..<HASH> 100644
--- a/Lib/fontMath/mathKerning.py
+++ b/Lib/fontMath/mathKerning.py
@@ -62,6 +62,22 @@ class MathKerning(object):
g[groupName].append(glyphName)
return g
+ def getGroupsForGlyph(self, glyphName):
+ """
+ >>> groups = {
+ ... "@A1" : ["A", "B"],
+ ... "@A2" : ["A"],
+ ... "@A3" : ["A"],
+ ... "@A4" : ["A"],
+ ... }
+ >>> obj = MathKerning({}, groups)
+ >>> sorted(obj.getGroupsForGlyph("A"))
+ ['@A1', '@A2', '@A3', '@A4']
+ >>> sorted(obj.getGroupsForGlyph("B"))
+ ['@A1']
+ """
+ return list(self._groupMap.get(glyphName, []))
+
def __getitem__(self, pair):
"""
>>> kerning = {
|
Added a method for getting the list of groups that a glyph belongs to.
|
robotools_fontMath
|
train
|
94e7ceb700b8d7f5171e1d615ac7fd09068e63b7
|
diff --git a/nion/swift/model/DocumentModel.py b/nion/swift/model/DocumentModel.py
index <HASH>..<HASH> 100644
--- a/nion/swift/model/DocumentModel.py
+++ b/nion/swift/model/DocumentModel.py
@@ -1104,6 +1104,8 @@ class DocumentModel(Observable.Observable, ReferenceCounting.ReferenceCounted, P
self.__data_channel_states_updated_listeners = dict()
self.__last_data_items_dict = dict() # maps hardware source to list of data items for that hardware source
+ self.__hardware_source_call_soon_event_listeners = dict()
+
self.__pending_data_item_updates_lock = threading.RLock()
self.__pending_data_item_updates = list()
@@ -2073,6 +2075,7 @@ class DocumentModel(Observable.Observable, ReferenceCounting.ReferenceCounted, P
hardware_source.data_item_states_changed(data_item_states)
def __hardware_source_added(self, hardware_source: HardwareSource.HardwareSource) -> None:
+ self.__hardware_source_call_soon_event_listeners[hardware_source.hardware_source_id] = hardware_source.call_soon_event.listen(self.__call_soon)
self.__data_channel_states_updated_listeners[hardware_source.hardware_source_id] = hardware_source.data_channel_states_updated.listen(functools.partial(self.__data_channel_states_updated, hardware_source))
for data_channel in hardware_source.data_channels:
data_channel_updated_listener = data_channel.data_channel_updated_event.listen(functools.partial(self.__data_channel_updated, hardware_source, data_channel))
@@ -2087,6 +2090,8 @@ class DocumentModel(Observable.Observable, ReferenceCounting.ReferenceCounted, P
hardware_source.clean_data_item(data_item, data_channel)
def __hardware_source_removed(self, hardware_source):
+ self.__hardware_source_call_soon_event_listeners[hardware_source.hardware_source_id].close()
+ del self.__hardware_source_call_soon_event_listeners[hardware_source.hardware_source_id]
self.__data_channel_states_updated_listeners[hardware_source.hardware_source_id].close()
del self.__data_channel_states_updated_listeners[hardware_source.hardware_source_id]
for listener in self.__data_channel_updated_listeners.get(hardware_source.hardware_source_id, list()):
diff --git a/nion/swift/model/HardwareSource.py b/nion/swift/model/HardwareSource.py
index <HASH>..<HASH> 100644
--- a/nion/swift/model/HardwareSource.py
+++ b/nion/swift/model/HardwareSource.py
@@ -565,6 +565,7 @@ class HardwareSource:
self.abort_event = Event.Event()
self.acquisition_state_changed_event = Event.Event()
self.data_item_states_changed_event = Event.Event()
+ self.call_soon_event = Event.Event()
self.__break_for_closing = False
self.__acquire_thread_trigger = threading.Event()
self.__tasks = dict() # type: typing.Dict[str, AcquisitionTask]
@@ -586,6 +587,9 @@ class HardwareSource:
self.__acquire_thread.join()
self.__acquire_thread = None
+ def _call_soon(self, fn):
+ self.call_soon_event.fire_any(fn)
+
def __acquire_thread_loop(self):
# acquire_thread_trigger should be set whenever the task list change.
while self.__acquire_thread_trigger.wait():
|
Allow hardware sources to put function calls on main thread (call_soon).
|
nion-software_nionswift
|
train
|
19b2cddc3c2f8346b36d8ad50afaefbf150b9686
|
diff --git a/source/php/Responses.php b/source/php/Responses.php
index <HASH>..<HASH> 100644
--- a/source/php/Responses.php
+++ b/source/php/Responses.php
@@ -159,6 +159,10 @@ class Responses
*/
public function addPageSummaryMetaBox($postType, $post)
{
+ if (!isset($post->ID)) {
+ return;
+ }
+
$answers = Responses::getResponses($post->ID);
if (count($answers) === 0) {
|
Do not run code if $post is null
|
helsingborg-stad_Customer-feedback
|
train
|
d4393e51401ed36ea7e4d8aa0bb6d7c301b05da9
|
diff --git a/salt/cloud/clouds/joyent.py b/salt/cloud/clouds/joyent.py
index <HASH>..<HASH> 100644
--- a/salt/cloud/clouds/joyent.py
+++ b/salt/cloud/clouds/joyent.py
@@ -1134,5 +1134,3 @@ def query(action=None,
return_content = yaml.safe_load(content)
return [result['status'], return_content]
-
-
|
Remove blank lines at end of file to satisfy linter
|
saltstack_salt
|
train
|
30f2dec97f5f7e72cf539d4d80a54813744a5e6d
|
diff --git a/core/src/main/java/hudson/model/ListView.java b/core/src/main/java/hudson/model/ListView.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/model/ListView.java
+++ b/core/src/main/java/hudson/model/ListView.java
@@ -172,11 +172,18 @@ public class ListView extends View implements DirectlyModifiableView {
}
- public List<TopLevelItem> getItems() {
+ /**
+ * Returns a read-only view of all {@link Job}s in this view.
+ *
+ * <p>
+ * This method returns a separate copy each time to avoid
+ * concurrent modification issue.
+ */
+ @Override
+ public List<TopLevelItem> getItems() {
return getItems(this.recurse);
}
-
/**
* Returns a read-only view of all {@link Job}s in this view.
*
@@ -187,7 +194,7 @@ public class ListView extends View implements DirectlyModifiableView {
* @param recurse {@code false} not to recurse in ItemGroups
* true to recurse in ItemGroups
*/
- private List<TopLevelItem> getItems(boolean recurse) {
+ private List<TopLevelItem> getItems(boolean recurse) {
SortedSet<String> names;
List<TopLevelItem> items = new ArrayList<TopLevelItem>();
|
Cleanup the code integrated in #<I>
|
jenkinsci_jenkins
|
train
|
ad9d699d98fc224b922bcd8533cc6771238720ff
|
diff --git a/messages/sync.js b/messages/sync.js
index <HASH>..<HASH> 100644
--- a/messages/sync.js
+++ b/messages/sync.js
@@ -26,7 +26,7 @@ module.exports = {
}
}
- data.push(entries[i][0], meta)
+ data.unshift(entries[i][0], meta)
}
this.syncing += 1
diff --git a/test/sync.test.js b/test/sync.test.js
index <HASH>..<HASH> 100644
--- a/test/sync.test.js
+++ b/test/sync.test.js
@@ -343,8 +343,8 @@ it('fixes created time', function () {
it('supports multiple actions in sync', function () {
return createTest().then(function (test) {
test.rightSync.sendSync(2, [
- [{ type: 'a' }, { id: [1, 'test2', 0], time: 1, added: 1 }],
- [{ type: 'b' }, { id: [2, 'test2', 0], time: 2, added: 2 }]
+ [{ type: 'b' }, { id: [2, 'test2', 0], time: 2, added: 2 }],
+ [{ type: 'a' }, { id: [1, 'test2', 0], time: 1, added: 1 }]
])
return test.wait('right')
}).then(function (test) {
@@ -399,8 +399,12 @@ it('changes multiple actions in map', function () {
it('synchronizes actions on connect', function () {
var test
+ var added = []
return createTest().then(function (created) {
test = created
+ test.leftSync.log.on('add', function (action) {
+ added.push(action.type)
+ })
return Promise.all([
test.leftSync.log.add({ type: 'a' }),
test.rightSync.log.add({ type: 'b' })
@@ -416,7 +420,8 @@ it('synchronizes actions on connect', function () {
return Promise.all([
test.leftSync.log.add({ type: 'c' }),
test.leftSync.log.add({ type: 'd' }),
- test.rightSync.log.add({ type: 'e' })
+ test.rightSync.log.add({ type: 'e' }),
+ test.rightSync.log.add({ type: 'f' })
])
}).then(function () {
return test.left.connect()
@@ -425,6 +430,7 @@ it('synchronizes actions on connect', function () {
return test.leftSync.waitFor('synchronized')
}).then(function () {
expect(actions(test.leftSync.log)).toEqual([
+ { type: 'f' },
{ type: 'e' },
{ type: 'd' },
{ type: 'c' },
@@ -432,5 +438,6 @@ it('synchronizes actions on connect', function () {
{ type: 'a' }
])
expect(actions(test.leftSync.log)).toEqual(actions(test.rightSync.log))
+ expect(added).toEqual(['a', 'b', 'c', 'd', 'e', 'f'])
})
})
|
Fix actions adding order on sync with multiple actions
|
logux_core
|
train
|
ffef34c1a92ca8299914988df8b289c935215c80
|
diff --git a/Form/DataType.php b/Form/DataType.php
index <HASH>..<HASH> 100644
--- a/Form/DataType.php
+++ b/Form/DataType.php
@@ -51,6 +51,9 @@ class DataType extends \Sidus\EAVModelBundle\Form\DataType
{
$resolver->setDefaults([
'data_class' => $this->dataClass,
+ 'attr' => [
+ 'novalidate' => 'novalidate',
+ ],
]);
}
diff --git a/Resources/public/js/sortable.collection.js b/Resources/public/js/sortable.collection.js
index <HASH>..<HASH> 100644
--- a/Resources/public/js/sortable.collection.js
+++ b/Resources/public/js/sortable.collection.js
@@ -6,6 +6,9 @@
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
+ /**
+ * Make bootstrap collection sortable, reorder properly the name of the input
+ */
$(document).ready(function() {
/* Initialize bootstrap collection sortable */
$('.bootstrap-collection').sortable({
|
Minor changes: disabling html5 validation by default, adding comment in sortable js
|
VincentChalnot_SidusEAVBootstrapBundle
|
train
|
d7f31a3322ea2d2aa6c10e6ae07efbfb8b331552
|
diff --git a/lib/discordrb/data.rb b/lib/discordrb/data.rb
index <HASH>..<HASH> 100644
--- a/lib/discordrb/data.rb
+++ b/lib/discordrb/data.rb
@@ -247,7 +247,7 @@ module Discordrb
# (Coincidentally, Manage Permissions is the same permission as Manage Roles, and a
# Manage Permissions deny overwrite will override Manage Roles, so we can just check for
# Manage Roles once and call it a day.)
- return true if defined_permission?(:administrate, channel)
+ return true if defined_permission?(:administrator, channel)
# Otherwise, defer to defined_permission
defined_permission?(action, channel)
|
Update permission name in data.rb
|
meew0_discordrb
|
train
|
6292375f261d92479a4d31b5beb6bf1fb180c2fb
|
diff --git a/lib/node-libnmap.js b/lib/node-libnmap.js
index <HASH>..<HASH> 100644
--- a/lib/node-libnmap.js
+++ b/lib/node-libnmap.js
@@ -317,21 +317,16 @@ var version = 'v0.0.3'
},
/**
- * @function replace
- * @abstract Performs recursive replacement on array of hosts to split
- * CIDR & ranges into equal number of blocks
+ * @function perform
+ * @abstract Perform user specified regex test on string
*
- * @param {Array} hosts - Array of host/cidr/range
+ * @param {Object} regex - Regex test case
+ * @param {String} str - String to perform test on
*
- * @returns {Array} Array of ranges
+ * @returns {Boolean}
*/
- replace: function(hosts){
- var results = []
-
- hosts.forEach(function(item){
-
- })
- return results
+ perform: function(regex, str){
+ return regex.test(str)
}
}
|
validate method
Methods:
validate: Structure for API now the following -
net: Object of REGEX pattern matching
perform(regex, str): Function to perform specified
pattern matching test on string
|
jas-_node-libnmap
|
train
|
4f9123ebe2fa382b1d1b2c6f3cc78869cc924bb8
|
diff --git a/pkg/services/provisioning/plugins/plugin_provisioner.go b/pkg/services/provisioning/plugins/plugin_provisioner.go
index <HASH>..<HASH> 100644
--- a/pkg/services/provisioning/plugins/plugin_provisioner.go
+++ b/pkg/services/provisioning/plugins/plugin_provisioner.go
@@ -47,7 +47,6 @@ func (ap *PluginProvisioner) apply(cfg *pluginsAsConfig) error {
}
} else {
app.PluginVersion = query.Result.PluginVersion
- app.Pinned = query.Result.Pinned
}
ap.log.Info("Updating app from configuration ", "type", app.PluginID, "enabled", app.Enabled)
|
Provisioning: always pin app to the sidebar when enabled (#<I>)
|
grafana_grafana
|
train
|
223730cae46c069038ae0b8f0256315d9bf5ca06
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -12,7 +12,7 @@ setup(
long_description=get_readme(),
author="nGen Works",
author_email='tech@ngenworks.com',
- url='http://www.ngenworks.com',
+ url='https://github.com/ngenworks/rest_framework_ember',
license='BSD',
keywords="EmberJS Django REST",
packages=find_packages(),
|
Change url in setup.py
|
django-json-api_django-rest-framework-json-api
|
train
|
e34b34d2a3241b1079b91a781cd48d80f838de9e
|
diff --git a/src/Models/User.php b/src/Models/User.php
index <HASH>..<HASH> 100644
--- a/src/Models/User.php
+++ b/src/Models/User.php
@@ -56,7 +56,7 @@ class User extends ActiveRecord
TigerApp::log("Password for {$this->username} rehashed.");
}
return true;
- }else {
+ } else {
return false;
}
}
@@ -65,7 +65,7 @@ class User extends ActiveRecord
{
if (self::getCurrent() instanceof User) {
return false;
- }else {
+ } else {
header("Location: /login");
exit;
}
diff --git a/src/TigerApp.php b/src/TigerApp.php
index <HASH>..<HASH> 100644
--- a/src/TigerApp.php
+++ b/src/TigerApp.php
@@ -88,6 +88,9 @@ class TigerApp
self::$tigerApp->getLogger()->write($message, $level);
}
+ /**
+ * @param string $appRoot
+ */
public function __construct($appRoot)
{
$this->appRoot = $appRoot;
@@ -98,33 +101,33 @@ class TigerApp
return self::$tigerApp->appRoot;
}
- static public function WebHost(){
+ static public function WebHost() {
return self::$tigerApp->slimApp->request()->getHost();
}
- static public function WebPort(){
+ static public function WebPort() {
return self::$tigerApp->slimApp->request()->getPort();
}
- static public function WebIsSSL(){
- return self::WebPort()==443?true:false;
+ static public function WebIsSSL() {
+ return self::WebPort() == 443 ? true : false;
}
- static public function WebRoot(){
- return(self::WebIsSSL()?"https":"http") . "://" . self::WebHost() . rtrim(dirname($_SERVER['SCRIPT_NAME']), "/\\") . "/";
+ static public function WebRoot() {
+ return(self::WebIsSSL() ? "https" : "http") . "://" . self::WebHost() . rtrim(dirname($_SERVER['SCRIPT_NAME']), "/\\") . "/";
}
/**
* @param string $key
* @return string|array|false
*/
- static public function Config($key){
+ static public function Config($key) {
$indexes = explode(".", $key);
$configData = self::$tigerApp->config;
- foreach($indexes as $index){
- if(isset($configData[$index])) {
+ foreach ($indexes as $index) {
+ if (isset($configData[$index])) {
$configData = $configData[$index];
- } else{
+ }else {
TigerApp::log("No such config index: {$key}");
return false;
}
@@ -138,7 +141,7 @@ class TigerApp
foreach ($indexes as $index) {
if (isset($treeData[$index])) {
$treeData = $treeData[$index];
- }else {
+ } else {
throw new TigerException("No such tree node index: {$key}");
}
}
@@ -158,7 +161,7 @@ class TigerApp
return self::AppRoot() . "/public/cache/";
}
- static public function LogRoot(){
+ static public function LogRoot() {
return self::AppRoot() . "/logs/";
}
@@ -209,7 +212,7 @@ class TigerApp
$loggerHandlers = [];
// Set up file logger.
- if(!file_exists(TigerApp::LogRoot())){
+ if (!file_exists(TigerApp::LogRoot())) {
mkdir(TigerApp::LogRoot(), 0777, true);
}
$fileLoggerHandler = new LogHandler\StreamHandler(TigerApp::LogRoot() . date('Y-m-d') . '.log', null, null, 0664);
@@ -235,7 +238,7 @@ class TigerApp
private function parseRoutes() {
$app = $this->slimApp;
$routesFile = APP_ROOT . "/config/Routes.php";
- if(file_exists($routesFile)) {
+ if (file_exists($routesFile)) {
require($routesFile);
}
}
diff --git a/src/TigerView.php b/src/TigerView.php
index <HASH>..<HASH> 100644
--- a/src/TigerView.php
+++ b/src/TigerView.php
@@ -18,7 +18,7 @@ class TigerView extends View
}
if (isset($data['noWrapper'])) {
return parent::render($template, $data);
- }else {
+ } else {
$data['view'] = $this;
$data['template'] = $template;
return parent::render("decorator/decorator.phtml", $data);
@@ -85,7 +85,7 @@ class TigerView extends View
public function getSiteTitle($decorate = true) {
if ($this->_page_title && $decorate) {
return "{$this->_site_title} - {$this->_page_title}";
- }else {
+ } else {
return "{$this->_site_title}";
}
}
|
Scrutinizer Auto-Fixes
This commit consists of patches automatically generated for this project on <URL>
|
Thruio_TigerKit
|
train
|
fa26a94edca6b064d16a8d40700d63090af6bd4d
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@
* [#2175](https://github.com/bbatsov/rubocop/pull/2175): Files that are excluded from a cop (e.g. using the `Exclude:` config option) are no longer being processed by that cop. ([@bquorning][])
* `Rails/ActionFilter` now handles complete list of methods found in the Rails 4.2 [release notes](https://github.com/rails/rails/blob/4115a12da1409c753c747fd4bab6e612c0c6e51a/guides/source/4_2_release_notes.md#notable-changes-1). ([@MGerrior][])
* [*2138](https://github.com/bbatsov/rubocop/issues/2138): Change the offense in `Style/Next` to highlight the condition instead of the iteration. ([@rrosenblum][])
+* `Style/EmptyLineBetweenDefs` now handles class methods as well. ([@unmanbearpig][])
### Bug Fixes
diff --git a/lib/rubocop/cop/style/empty_line_between_defs.rb b/lib/rubocop/cop/style/empty_line_between_defs.rb
index <HASH>..<HASH> 100644
--- a/lib/rubocop/cop/style/empty_line_between_defs.rb
+++ b/lib/rubocop/cop/style/empty_line_between_defs.rb
@@ -6,9 +6,10 @@ module RuboCop
# This cop checks whether method definitions are
# separated by empty lines.
class EmptyLineBetweenDefs < Cop
+ include OnMethodDef
MSG = 'Use empty lines between method definitions.'
- def on_def(node)
+ def on_method_def(node, _method_name, _args, _body)
return unless node.parent && node.parent.begin_type?
nodes = [prev_node(node), node]
@@ -24,7 +25,8 @@ module RuboCop
private
def def_node?(node)
- node && node.def_type?
+ return unless node
+ node.def_type? || node.defs_type?
end
def blank_lines_between?(first_def_node, second_def_node)
diff --git a/spec/rubocop/cop/style/empty_line_between_defs_spec.rb b/spec/rubocop/cop/style/empty_line_between_defs_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rubocop/cop/style/empty_line_between_defs_spec.rb
+++ b/spec/rubocop/cop/style/empty_line_between_defs_spec.rb
@@ -89,6 +89,72 @@ describe RuboCop::Cop::Style::EmptyLineBetweenDefs, :config do
end
end
+ context 'class methods' do
+ context 'adjacent class methods' do
+ let(:offending_source) do
+ ['class Test',
+ ' def self.foo',
+ ' true',
+ ' end',
+ ' def self.bar',
+ ' true',
+ ' end',
+ 'end']
+ end
+
+ it 'registers an offense for missing blank line between methods' do
+ inspect_source(cop, offending_source)
+ expect(cop.offenses.size).to eq(1)
+ end
+
+ it 'autocorrects it' do
+ corrected = autocorrect_source(cop, offending_source)
+ expect(corrected).to eq(['class Test',
+ ' def self.foo',
+ ' true',
+ ' end',
+ '',
+ ' def self.bar',
+ ' true',
+ ' end',
+ 'end']
+ .join("\n"))
+ end
+ end
+
+ context 'mixed instance and class methods' do
+ let(:offending_source) do
+ ['class Test',
+ ' def foo',
+ ' true',
+ ' end',
+ ' def self.bar',
+ ' true',
+ ' end',
+ 'end']
+ end
+
+ it 'registers an offense for missing blank line between methods' do
+ inspect_source(cop, offending_source)
+ expect(cop.offenses.size).to eq(1)
+ end
+
+ it 'autocorrects it' do
+ corrected = autocorrect_source(cop, offending_source)
+ expect(corrected).to eq(['class Test',
+ ' def foo',
+ ' true',
+ ' end',
+ '',
+ ' def self.bar',
+ ' true',
+ ' end',
+ 'end']
+ .join("\n"))
+ end
+ end
+ end
+
# Only one def, so rule about empty line *between* defs does not
# apply.
it 'accepts a def that follows a line with code' do
|
Handle class methods in EmptyLineBetweenDefs
I've made it check `defs` node type as well as `def`, that's the
only change that was needed to make it work with class methods.
|
rubocop-hq_rubocop
|
train
|
82e936cc81f75d35fc83b49f91a1cf1ce22f9508
|
diff --git a/ga4gh/cli.py b/ga4gh/cli.py
index <HASH>..<HASH> 100644
--- a/ga4gh/cli.py
+++ b/ga4gh/cli.py
@@ -192,6 +192,18 @@ class AbstractSearchRunner(FormattedOutputRunner):
for readGroupSet in iterator:
yield readGroupSet
+ def getAllReadGroups(self):
+ """
+ Get all read groups in a read group set
+ """
+ for dataset in self.getAllDatasets():
+ iterator = self._client.searchReadGroupSets(
+ datasetId=dataset.id)
+ for readGroupSet in iterator:
+ readGroupSet = self._client.getReadGroupSet(readGroupSet.id)
+ for readGroup in readGroupSet.readGroups:
+ yield readGroup.id
+
def getAllReferenceSets(self):
"""
Returns all reference sets on the server.
@@ -385,13 +397,34 @@ class SearchReadsRunner(AbstractSearchRunner):
if args.readGroupIds is not None:
self._readGroupIds = args.readGroupIds.split(",")
+ def _run(self, referenceGroupId, referenceId=None):
+ """
+ automatically guess reference id if not passed
+ """
+ # check if we can get reference id from rg
+ if referenceId is None:
+ referenceId = self._referenceId
+ if referenceId is None:
+ rg = self._client.getReadGroup(readGroupId=referenceGroupId)
+ iterator = self._client.searchReferences(rg.referenceSetId)
+ for reference in iterator:
+ self._run(referenceGroupId, reference.id)
+ else:
+ iterator = self._client.searchReads(
+ readGroupIds=[referenceGroupId], referenceId=referenceId,
+ start=self._start, end=self._end)
+ self._output(iterator)
+
def run(self):
- # TODO add support for looking up ReadGroupSets and References
- # like we do with SearchVariants and others.
- iterator = self._client.searchReads(
- readGroupIds=self._readGroupIds, referenceId=self._referenceId,
- start=self._start, end=self._end)
- self._output(iterator)
+ """
+ Iterate passed read group ids, or go through all available read groups
+ """
+ if not self._readGroupIds:
+ for referenceGroupId in self.getAllReadGroups():
+ self._run(referenceGroupId)
+ else:
+ for referenceGroupId in self._readGroupIds:
+ self._run(referenceGroupId)
def _textOutput(self, gaObjects):
"""
diff --git a/tests/end_to_end/test_client_json.py b/tests/end_to_end/test_client_json.py
index <HASH>..<HASH> 100644
--- a/tests/end_to_end/test_client_json.py
+++ b/tests/end_to_end/test_client_json.py
@@ -73,3 +73,8 @@ class TestClientJson(unittest.TestCase):
for dataset in self._client.searchDatasets():
self.verifyParsedOutputsEqual(
[dataset], "datasets-get", dataset.id)
+
+ def testSearchAllReadGroups(self):
+ # TODO: add more rigorous testing here
+ cliOutput = self.captureJsonOutput("reads-search")
+ self.assertGreater(len(cliOutput), 0)
|
Added support for finding all read groups when no read group specified
Fixes issue #<I>
|
ga4gh_ga4gh-server
|
train
|
14ab43a310d9391b8b3eded0e20700bd7e8f9cde
|
diff --git a/src/Tenant/Views/SpaRepository.php b/src/Tenant/Views/SpaRepository.php
index <HASH>..<HASH> 100644
--- a/src/Tenant/Views/SpaRepository.php
+++ b/src/Tenant/Views/SpaRepository.php
@@ -34,7 +34,7 @@ class Tenant_Views_SpaRepository extends Pluf_Views
{
// request param
$backend = Pluf::f('marketplace.backend', 'http://marketplace.webpich.com');
- $path = '/api/marketplace/spa/find';
+ $path = '/api/v2/marketplace/spas';
$param = $request->REQUEST;
// Do request
@@ -60,7 +60,7 @@ class Tenant_Views_SpaRepository extends Pluf_Views
// request param
$backend = Pluf::f('marketplace.backend', 'http://marketplace.webpich.com');
- $path = '/api/marketplace/spa/'.$match['modelId'];
+ $path = '/api/v2/marketplace/spas/'.$match['modelId'];
$param = $request->REQUEST;
// Do request
|
Edit used API to connection with remote repository
|
pluf_tenant
|
train
|
d032af4205fd6be01f1574025e820ebf28015fe4
|
diff --git a/src/main/java/org/asteriskjava/manager/action/SipPeersAction.java b/src/main/java/org/asteriskjava/manager/action/SipPeersAction.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/asteriskjava/manager/action/SipPeersAction.java
+++ b/src/main/java/org/asteriskjava/manager/action/SipPeersAction.java
@@ -25,11 +25,11 @@ import org.asteriskjava.manager.event.ResponseEvent;
* the details. When all peers have been reported a PeerlistCompleteEvent is
* sent.<p>
* Available since Asterisk 1.2
- *
- * @see org.asteriskjava.manager.event.PeerEntryEvent
- * @see org.asteriskjava.manager.event.PeerlistCompleteEvent
+ *
* @author srt
* @version $Id$
+ * @see org.asteriskjava.manager.event.PeerEntryEvent
+ * @see org.asteriskjava.manager.event.PeerlistCompleteEvent
* @since 0.2
*/
public class SipPeersAction extends AbstractManagerAction implements EventGeneratingAction
@@ -48,7 +48,7 @@ public class SipPeersAction extends AbstractManagerAction implements EventGenera
}
@Override
- public String getAction()
+ public String getAction()
{
return "SIPPeers";
}
diff --git a/src/main/java/org/asteriskjava/manager/response/SipShowPeerResponse.java b/src/main/java/org/asteriskjava/manager/response/SipShowPeerResponse.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/asteriskjava/manager/response/SipShowPeerResponse.java
+++ b/src/main/java/org/asteriskjava/manager/response/SipShowPeerResponse.java
@@ -528,9 +528,9 @@ public class SipShowPeerResponse extends ManagerResponse
{
qualifyFreq = qualifyFreq.substring(2);
}
- if (qualifyFreq.lastIndexOf('\n') > -1)
+ if (qualifyFreq.indexOf('\n') > -1)
{
- qualifyFreq = qualifyFreq.substring(0, qualifyFreq.lastIndexOf('\n'));
+ qualifyFreq = qualifyFreq.substring(0, qualifyFreq.indexOf('\n'));
}
this.qualifyFreq = stringToInteger(qualifyFreq, "ms");
}
diff --git a/src/test/java/org/asteriskjava/manager/response/SipShowPeerResponseTest.java b/src/test/java/org/asteriskjava/manager/response/SipShowPeerResponseTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/asteriskjava/manager/response/SipShowPeerResponseTest.java
+++ b/src/test/java/org/asteriskjava/manager/response/SipShowPeerResponseTest.java
@@ -22,4 +22,10 @@ public class SipShowPeerResponseTest extends TestCase
response.setQualifyFreq(": 6000 ms\n");
assertEquals("Incorrect qualifyFreq", 6000, (int) response.getQualifyFreq());
}
+
+ public void testSetQualifyFreqWithWorkaroundAndChanVariable()
+ {
+ response.setQualifyFreq(": 60000 ms\nChanVariable:\n PHBX_ID,191");
+ assertEquals("Incorrect qualifyFreq", 60000, (int) response.getQualifyFreq());
+ }
}
|
[AJ-<I>] Fixed workaround for Asterisk bug in SipShowPeerResponse
|
asterisk-java_asterisk-java
|
train
|
a0743e9a6e3c193f92e0e796714f8bebac424381
|
diff --git a/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAdapters.java b/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAdapters.java
index <HASH>..<HASH> 100644
--- a/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAdapters.java
+++ b/xchange-binance/src/main/java/org/knowm/xchange/binance/BinanceAdapters.java
@@ -127,7 +127,7 @@ public class BinanceAdapters {
|| order.type.equals(org.knowm.xchange.binance.dto.trade.OrderType.LIMIT_MAKER)) {
builder = new LimitOrder.Builder(type, currencyPair).limitPrice(order.price);
} else {
- builder = new StopOrder.Builder(type, currencyPair).limitPrice(order.price);
+ builder = new StopOrder.Builder(type, currencyPair).stopPrice(order.stopPrice);
}
builder
.orderStatus(adaptOrderStatus(order.status))
@@ -140,13 +140,7 @@ public class BinanceAdapters {
order.cummulativeQuoteQty.divide(order.executedQty, MathContext.DECIMAL32));
}
if (order.clientOrderId != null) {
- builder.flag(
- new BinanceOrderFlags() {
- @Override
- public String getClientId() {
- return order.clientOrderId;
- }
- });
+ builder.flag((BinanceOrderFlags) () -> order.clientOrderId);
}
return builder.build();
}
diff --git a/xchange-coinbasepro/src/main/java/org/knowm/xchange/coinbasepro/CoinbaseProAdapters.java b/xchange-coinbasepro/src/main/java/org/knowm/xchange/coinbasepro/CoinbaseProAdapters.java
index <HASH>..<HASH> 100644
--- a/xchange-coinbasepro/src/main/java/org/knowm/xchange/coinbasepro/CoinbaseProAdapters.java
+++ b/xchange-coinbasepro/src/main/java/org/knowm/xchange/coinbasepro/CoinbaseProAdapters.java
@@ -185,57 +185,34 @@ public class CoinbaseProAdapters {
public static Order adaptOrder(CoinbaseProOrder order) {
OrderType type = order.getSide().equals("buy") ? OrderType.BID : OrderType.ASK;
CurrencyPair currencyPair = new CurrencyPair(order.getProductId().replace('-', '/'));
-
- Date createdAt = parseDate(order.getCreatedAt());
-
- OrderStatus orderStatus = adaptOrderStatus(order);
-
- final BigDecimal averagePrice;
- if (order.getFilledSize().signum() == 0) {
- averagePrice = BigDecimal.ZERO;
- } else {
- averagePrice = order.getExecutedvalue().divide(order.getFilledSize(), new MathContext(8));
- }
-
+ Order.Builder builder = null;
if (order.getType().equals("market")) {
- return new MarketOrder(
- type,
- order.getSize(),
- currencyPair,
- order.getId(),
- createdAt,
- averagePrice,
- order.getFilledSize(),
- order.getFillFees(),
- orderStatus);
+ builder = new MarketOrder.Builder(type, currencyPair);
} else if (order.getType().equals("limit")) {
if (order.getStop() == null) {
- return new LimitOrder(
- type,
- order.getSize(),
- currencyPair,
- order.getId(),
- createdAt,
- order.getPrice(),
- averagePrice,
- order.getFilledSize(),
- order.getFillFees(),
- orderStatus);
+ builder = new LimitOrder.Builder(type, currencyPair).limitPrice(order.getPrice());
} else {
- return new StopOrder(
- type,
- order.getSize(),
- currencyPair,
- order.getId(),
- createdAt,
- order.getStopPrice(),
- averagePrice,
- order.getFilledSize(),
- orderStatus);
+ builder = new StopOrder.Builder(type, currencyPair).stopPrice(order.getStopPrice());
}
}
-
- return null;
+ if (builder == null) {
+ return null;
+ }
+ builder
+ .orderStatus(adaptOrderStatus(order))
+ .originalAmount(order.getSize())
+ .id(order.getId())
+ .timestamp(parseDate(order.getCreatedAt()))
+ .cumulativeAmount(order.getFilledSize())
+ .fee(order.getFillFees());
+ BigDecimal averagePrice;
+ if (order.getFilledSize().signum() != 0 && order.getExecutedvalue().signum() != 0) {
+ averagePrice = order.getExecutedvalue().divide(order.getFilledSize(), MathContext.DECIMAL32);
+ } else {
+ averagePrice = BigDecimal.ZERO;
+ }
+ builder.averagePrice(averagePrice);
+ return builder.build();
}
public static OrderStatus[] adaptOrderStatuses(CoinbaseProOrder[] orders) {
diff --git a/xchange-core/src/main/java/org/knowm/xchange/dto/Order.java b/xchange-core/src/main/java/org/knowm/xchange/dto/Order.java
index <HASH>..<HASH> 100644
--- a/xchange-core/src/main/java/org/knowm/xchange/dto/Order.java
+++ b/xchange-core/src/main/java/org/knowm/xchange/dto/Order.java
@@ -136,6 +136,13 @@ public abstract class Order implements Serializable {
this.cumulativeAmount = cumulativeAmount;
}
+ public BigDecimal getCumulativeCounterAmount() {
+ if (cumulativeAmount != null && averagePrice != null && averagePrice.compareTo(BigDecimal.ZERO) > 0) {
+ return cumulativeAmount.multiply(averagePrice);
+ }
+ return null;
+ }
+
/** @return The remaining order amount */
public BigDecimal getRemainingAmount() {
if (cumulativeAmount != null && originalAmount != null) {
|
Added cumulativeQuoteAmount method into Order & refactored CoinbasePro adaptOrder
|
knowm_XChange
|
train
|
6752cf8e32ba7fbf27d38288ef9c5ee0abd89f87
|
diff --git a/snappy-core/src/main/java/io/joshworks/snappy/SnappyServer.java b/snappy-core/src/main/java/io/joshworks/snappy/SnappyServer.java
index <HASH>..<HASH> 100644
--- a/snappy-core/src/main/java/io/joshworks/snappy/SnappyServer.java
+++ b/snappy-core/src/main/java/io/joshworks/snappy/SnappyServer.java
@@ -432,7 +432,8 @@ public class SnappyServer {
} catch (Exception e) {
started = false;
logger.error("Error while starting the server", e);
- throw new RuntimeException(e);
+ stop();
+ System.exit(1);
}
}
|
Exiting process if exception on startup occurs
|
josueeduardo_snappy
|
train
|
866fb866f0460cf27c31ff2f4ae0253e9abddd61
|
diff --git a/CHANGES.md b/CHANGES.md
index <HASH>..<HASH> 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -7,6 +7,7 @@ Change Log
* Fixed a bug that caused an 'added' and a 'shown' event for "Unnamed Item" to be logged to Google Analytics when previewing an item in the catalog.
* Added a 'preview' Google Analytics event when a catalog item is shown on the preview map in the catalog.
+* Fixed a bug that prevented csv files with missing dates from loading.
### 5.1.0
diff --git a/lib/Models/RegionMapping.js b/lib/Models/RegionMapping.js
index <HASH>..<HASH> 100644
--- a/lib/Models/RegionMapping.js
+++ b/lib/Models/RegionMapping.js
@@ -427,7 +427,10 @@ function calculateRegionIndices(regionMapping, time, failedMatches, ambiguousMat
var timeColumn = tableStructure.activeTimeColumn;
if (defined(time) && defined(timeColumn) && timeColumn.timeIntervals) {
regionColumnValues = regionColumnValues.map(function(value, index) {
- return (TimeInterval.contains(timeColumn.timeIntervals[index], time) ? value : undefined);
+ // If there's a missing time value, ignore it.
+ if (defined(timeColumn.timeIntervals[index])) {
+ return (TimeInterval.contains(timeColumn.timeIntervals[index], time) ? value : undefined);
+ }
});
}
var disambigColumn = defined(regionDetail.disambigColumnName) ? tableStructure.getColumnWithNameIdOrIndex(regionDetail.disambigColumnName) : undefined;
diff --git a/test/Models/CsvCatalogItemSpec.js b/test/Models/CsvCatalogItemSpec.js
index <HASH>..<HASH> 100644
--- a/test/Models/CsvCatalogItemSpec.js
+++ b/test/Models/CsvCatalogItemSpec.js
@@ -968,6 +968,34 @@ describe('CsvCatalogItem with region mapping', function() {
}).otherwise(fail).then(done);
});
+ it('supports region-mapped files with missing dates', function(done) {
+ csvItem.updateFromJson({
+ url: 'test/csv/postcode_date_value_missing_date.csv'
+ });
+ csvItem.load().then(function() {
+ var regionMapping = csvItem.regionMapping;
+ var j = JulianDate.fromIso8601;
+ regionMapping._catalogItem.terria.clock.currentTime = j('2015-08-08');
+ csvItem.isEnabled = true;
+ var regionDetails = regionMapping.regionDetails;
+ expect(regionDetails).toBeDefined();
+ var regionDetail = regionDetails[0];
+ expect(csvItem.tableStructure.columns[0].values.length).toEqual(10);
+ expect(csvItem.tableStructure.columnsByType[VarType.TIME].length).toEqual(1);
+ expect(csvItem.tableStructure.columnsByType[VarType.TIME][0].julianDates[0]).toEqual(j('2015-08-07'));
+ // Test that the right regions have been colored (since the datasource doesn't expose the entities).
+ // On 2015-08-07, only postcodes 3121 and 3122 have values. On neighboring dates, so do 3123 and 3124.
+ var recolorFunction = ImageryProviderHooks.addRecolorFunc.calls.argsFor(0)[1];
+ var regionNames = regionDetail.regionProvider.regions.map(getId);
+
+ expect(recolorFunction(regionNames.indexOf('3121'))).toBeDefined();
+ expect(recolorFunction(regionNames.indexOf('3122'))).not.toBeDefined(); // This one was eliminated.
+ expect(recolorFunction(regionNames.indexOf('3123'))).not.toBeDefined();
+ expect(recolorFunction(regionNames.indexOf('3124'))).not.toBeDefined();
+ expect(csvItem.legendUrl).toBeDefined();
+ }).otherwise(fail).then(done);
+ });
+
it('supports region-mapped files with displayDuration and dates', function(done) {
csvItem.updateFromJson({
url: 'test/csv/postcode_date_value.csv',
|
fix csv files with missing dates fail to load
|
TerriaJS_terriajs
|
train
|
16b9271e5c684cd7729fa3906032536509e3a4a0
|
diff --git a/lib/async.js b/lib/async.js
index <HASH>..<HASH> 100644
--- a/lib/async.js
+++ b/lib/async.js
@@ -139,7 +139,8 @@
}
while (running < limit && started < arr.length) {
- iterator(arr[started], function (err) {
+ started += 1;
+ iterator(arr[started - 1], function (err) {
if (err) {
callback(err);
callback = function () {};
@@ -155,7 +156,6 @@
}
}
});
- started += 1;
running += 1;
}
})();
diff --git a/test/test-async.js b/test/test-async.js
index <HASH>..<HASH> 100644
--- a/test/test-async.js
+++ b/test/test-async.js
@@ -635,6 +635,18 @@ exports['forEachLimit no callback'] = function(test){
async.forEachLimit([1], 1, forEachNoCallbackIterator.bind(this, test));
};
+exports['forEachLimit synchronous'] = function(test){
+ var args = [];
+ var arr = [0,1,2];
+ async.forEachLimit(arr, 5, function(x,callback){
+ args.push(x);
+ callback();
+ }, function(err){
+ test.same(args, arr);
+ test.done();
+ });
+};
+
exports['map'] = function(test){
var call_order = [];
async.map([1,3,2], mapIterator.bind(this, call_order), function(err, results){
|
fix occasional synchronous use of forEachLimit
|
caolan_async
|
train
|
e29c5c9f4b22b427dc51ca7c39f458f5f5e3e595
|
diff --git a/icrawler/builtin/bing.py b/icrawler/builtin/bing.py
index <HASH>..<HASH> 100644
--- a/icrawler/builtin/bing.py
+++ b/icrawler/builtin/bing.py
@@ -4,12 +4,7 @@ import re
import six
from bs4 import BeautifulSoup
-try:
- import html
- unescape = html.unescape
-except ImportError:
- from six.moves import html_parser
- unescape = html_parser.HTMLParser().unescape
+import html
from icrawler import Crawler, Parser, Feeder, ImageDownloader
from icrawler.builtin.filter import Filter
@@ -127,7 +122,7 @@ class BingParser(Parser):
image_divs = soup.find_all('div', class_='imgpt')
pattern = re.compile(r'murl\":\"(.*?)\.jpg')
for div in image_divs:
- href_str = unescape(div.a['m'])
+ href_str = html.unescape(div.a['m'])
match = pattern.search(href_str)
if match:
name = (match.group(1)
|
Remove <I> and <I> - <I> Support
|
hellock_icrawler
|
train
|
a84a738360f1986f67b4a2d72005ef6848761601
|
diff --git a/internal/ui/ui_glfw_darwin.go b/internal/ui/ui_glfw_darwin.go
index <HASH>..<HASH> 100644
--- a/internal/ui/ui_glfw_darwin.go
+++ b/internal/ui/ui_glfw_darwin.go
@@ -147,13 +147,13 @@ package ui
//
// // Even though EbitenWindowDelegate is used, this hack is still required.
// // toggleFullscreen doesn't work when the window is not resizable.
-// bool origResizable = window.styleMask & NSWindowStyleMaskResizable;
-// if (!origResizable) {
-// window.styleMask |= NSWindowStyleMaskResizable;
+// bool origFullscreen = window.collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary;
+// if (!origFullscreen) {
+// window.collectionBehavior |= NSWindowCollectionBehaviorFullScreenPrimary;
// }
// [window toggleFullScreen:nil];
-// if (!origResizable) {
-// window.styleMask &= ~NSWindowStyleMaskResizable;
+// if (!origFullscreen) {
+// window.collectionBehavior &= ~NSWindowCollectionBehaviorFullScreenPrimary;
// }
// }
//
|
internal/ui: bug fix: collectionBehavior mattered for fullscreen
Closes #<I>
|
hajimehoshi_ebiten
|
train
|
4326c47b24f7e3c58010e97f31d176bf960c5182
|
diff --git a/telemetry/telemetry/core/cast_interface.py b/telemetry/telemetry/core/cast_interface.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/core/cast_interface.py
+++ b/telemetry/telemetry/core/cast_interface.py
@@ -3,6 +3,14 @@
# found in the LICENSE file.
"""A wrapper for common operations on a device with Cast capabilities."""
+import os
+
+from telemetry.core import util
+
CAST_BROWSERS = [
'platform_app'
]
+
+_DEFAULT_CAST_CORE_DIR = os.path.join(util.GetCatapultDir(), '..', 'cast_core',
+ 'prebuilts')
+_DEFAULT_CWR_EXE = os.path.join(util.GetCatapultDir(), '..', 'cast_web_runtime')
diff --git a/telemetry/telemetry/internal/backends/chrome/remote_cast_browser_backend.py b/telemetry/telemetry/internal/backends/chrome/remote_cast_browser_backend.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/internal/backends/chrome/remote_cast_browser_backend.py
+++ b/telemetry/telemetry/internal/backends/chrome/remote_cast_browser_backend.py
@@ -132,7 +132,7 @@ class RemoteCastBrowserBackend(cast_browser_backend.CastBrowserBackend):
def _InstallCastWebRuntime(self):
ssh = self._platform_backend.GetSSHSession()
- deploy_path = os.join(_CAST_ROOT, _CAST_DEPLOY_PATH)
+ deploy_path = os.path.join(_CAST_ROOT, _CAST_DEPLOY_PATH)
self._SendCommand(ssh, 'cd %s && umask 0022' % deploy_path)
if self._CheckExistenceOnDevice(ssh, 'cast_runtime'):
self._SendCommand(ssh, 'rm -rf cast_runtime')
diff --git a/telemetry/telemetry/internal/browser/browser_options.py b/telemetry/telemetry/internal/browser/browser_options.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/internal/browser/browser_options.py
+++ b/telemetry/telemetry/internal/browser/browser_options.py
@@ -279,9 +279,9 @@ class BrowserFinderOptions(optparse.Values):
help='Output directory for Cast Core.')
group.add_option('--cast-runtime-exe',
help='Path to Cast Web Runtime executable.')
- group.add_option('--remote-cast',
+ group.add_option('--local-cast',
action="store_true", default=False,
- help='Use a remote casting receiver.')
+ help='Use a local casting receiver on the host.')
group.add_option('--cast-device-ip',
help='IP address of the Cast device.')
diff --git a/telemetry/telemetry/internal/platform/cast_device.py b/telemetry/telemetry/internal/platform/cast_device.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/internal/platform/cast_device.py
+++ b/telemetry/telemetry/internal/platform/cast_device.py
@@ -42,9 +42,12 @@ def FindAllAvailableDevices(options):
options.cast_receiver_type not in cast_interface.CAST_BROWSERS):
return []
- if options.remote_cast and not options.cast_device_ip:
- cast_device_ip = os.environ.get('CAST_DEVICE_IP')
- else:
- cast_device_ip = options.cast_device_ip
+ if not options.local_cast:
+ if not options.cast_device_ip:
+ options.cast_device_ip = os.environ.get('CAST_DEVICE_IP')
+ if not options.cast_output_dir:
+ options.cast_output_dir = cast_interface._DEFAULT_CAST_CORE_DIR
+ if not options.cast_runtime_exe:
+ options.cast_runtime_exe = cast_interface._DEFAULT_CWR_EXE
return [CastDevice(options.cast_output_dir, options.cast_runtime_exe,
- cast_device_ip)]
+ options.cast_device_ip)]
|
[cast3p] Set defaults for Cast Core remote device testing
This makes it easier for developers to use our base test scenario,
where the binaries are checked out in Chromium.
Bug: chromium:<I>
Change-Id: I<I>ad<I>b6a4f<I>e<I>e<I>e7e2bde<I>b<I>f
Reviewed-on: <URL>
|
catapult-project_catapult
|
train
|
bc39baa13253da299d062565be1406e69b90a4f1
|
diff --git a/apio/managers/scons.py b/apio/managers/scons.py
index <HASH>..<HASH> 100644
--- a/apio/managers/scons.py
+++ b/apio/managers/scons.py
@@ -216,13 +216,13 @@ class SCons(object):
def get_serial_port(self, board, board_data, ext_serial_port):
# Search Serial port by USB id
- device = self._check_serial(board_data, ext_serial_port)
+ device = self._check_serial(board, board_data, ext_serial_port)
if device is None:
- # Board not available
- raise Exception('board ' + board + ' not available')
+ # Board not connected
+ raise Exception('board ' + board + ' not connected')
return device
- def _check_serial(self, board_data, ext_serial_port):
+ def _check_serial(self, board, board_data, ext_serial_port):
if 'usb' not in board_data:
raise Exception('Missing board configuration: usb')
@@ -233,7 +233,11 @@ class SCons(object):
)
# Match the discovered serial ports
- for serial_port_data in util.get_serial_ports():
+ serial_ports = util.get_serial_ports()
+ if len(serial_ports) == 0:
+ # Board not available
+ raise Exception('board ' + board + ' not available')
+ for serial_port_data in serial_ports:
port = serial_port_data.get('port')
if ext_serial_port and ext_serial_port != port:
# If the --device options is set but it doesn't match
@@ -261,20 +265,24 @@ class SCons(object):
def get_ftdi_id(self, board, board_data, ext_ftdi_id):
# Search device by FTDI id
- ftdi_id = self._check_ftdi(board_data, ext_ftdi_id)
+ ftdi_id = self._check_ftdi(board, board_data, ext_ftdi_id)
if ftdi_id is None:
- # Board not available
- raise Exception('board ' + board + ' not available')
+ # Board not connected
+ raise Exception('board ' + board + ' not connected')
return ftdi_id
- def _check_ftdi(self, board_data, ext_ftdi_id):
+ def _check_ftdi(self, board, board_data, ext_ftdi_id):
if 'ftdi' not in board_data:
raise Exception('Missing board configuration: ftdi')
desc_pattern = '^' + board_data.get('ftdi').get('desc') + '$'
# Match the discovered FTDI chips
- for ftdi_device in System().get_ftdi_devices():
+ ftdi_devices = System().get_ftdi_devices()
+ if len(ftdi_devices) == 0:
+ # Board not available
+ raise Exception('board ' + board + ' not available')
+ for ftdi_device in ftdi_devices:
index = ftdi_device.get('index')
if ext_ftdi_id and ext_ftdi_id != index:
# If the --device options is set but it doesn't match
|
Throw error "board not available" only if no serial/ftdi devices are found
|
FPGAwars_apio
|
train
|
3d72d47f0905772b83d02159400a7d7f9af40c4e
|
diff --git a/src/transformers/models/mpnet/modeling_tf_mpnet.py b/src/transformers/models/mpnet/modeling_tf_mpnet.py
index <HASH>..<HASH> 100644
--- a/src/transformers/models/mpnet/modeling_tf_mpnet.py
+++ b/src/transformers/models/mpnet/modeling_tf_mpnet.py
@@ -348,15 +348,22 @@ class TFMPNetEncoder(tf.keras.layers.Layer):
self.n_heads = config.num_attention_heads
self.output_attentions = config.output_attentions
self.output_hidden_states = config.output_hidden_states
+ self.relative_attention_num_buckets = config.relative_attention_num_buckets
+ self.initializer_range = config.initializer_range
self.layer = [TFMPNetLayer(config, name="layer_._{}".format(i)) for i in range(config.num_hidden_layers)]
- self.relative_attention_bias = tf.keras.layers.Embedding(
- config.relative_attention_num_buckets,
- self.n_heads,
- name="relative_attention_bias",
- )
self.relative_attention_num_buckets = config.relative_attention_num_buckets
+ def build(self, input_shape):
+ with tf.name_scope("relative_attention_bias"):
+ self.relative_attention_bias = self.add_weight(
+ name="embeddings",
+ shape=[self.relative_attention_num_buckets, self.n_heads],
+ initializer=get_initializer(self.initializer_range),
+ )
+
+ return super().build(input_shape)
+
def call(
self,
hidden_states,
@@ -405,18 +412,16 @@ class TFMPNetEncoder(tf.keras.layers.Layer):
n = -relative_position
num_buckets //= 2
- ret += tf.dtypes.cast(tf.math.less(n, 0), tf.int32) * num_buckets
+ ret += tf.cast(tf.math.less(n, 0), dtype=relative_position.dtype) * num_buckets
n = tf.math.abs(n)
# now n is in the range [0, inf)
max_exact = num_buckets // 2
is_small = tf.math.less(n, max_exact)
- val_if_large = max_exact + tf.dtypes.cast(
- tf.math.log(tf.dtypes.cast(n, tf.float32) / max_exact)
- / math.log(max_distance / max_exact)
- * (num_buckets - max_exact),
- tf.int32,
+ val_if_large = max_exact + tf.cast(
+ tf.math.log(n / max_exact) / math.log(max_distance / max_exact) * (num_buckets - max_exact),
+ dtype=relative_position.dtype,
)
val_if_large = tf.math.minimum(val_if_large, num_buckets - 1)
@@ -441,7 +446,7 @@ class TFMPNetEncoder(tf.keras.layers.Layer):
relative_position,
num_buckets=self.relative_attention_num_buckets,
)
- values = self.relative_attention_bias(rp_bucket) # shape (qlen, klen, num_heads)
+ values = tf.gather(self.relative_attention_bias, rp_bucket) # shape (qlen, klen, num_heads)
values = tf.expand_dims(tf.transpose(values, [2, 0, 1]), axis=0) # shape (1, num_heads, qlen, klen)
return values
@@ -541,7 +546,9 @@ class TFMPNetMainLayer(tf.keras.layers.Layer):
# Since we are adding it to the raw scores before the softmax, this is
# effectively the same as removing these entirely.
extended_attention_mask = tf.cast(extended_attention_mask, embedding_output.dtype)
- extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
+ one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
+ ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
+ extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
diff --git a/tests/test_modeling_tf_mpnet.py b/tests/test_modeling_tf_mpnet.py
index <HASH>..<HASH> 100644
--- a/tests/test_modeling_tf_mpnet.py
+++ b/tests/test_modeling_tf_mpnet.py
@@ -232,10 +232,6 @@ class TFMPNetModelTest(TFModelTesterMixin, unittest.TestCase):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_mpnet_for_token_classification(*config_and_inputs)
- def test_xla_mode(self):
- # TODO JP: Make MPNet XLA compliant
- pass
-
@slow
def test_model_from_pretrained(self):
for model_name in ["microsoft/mpnet-base"]:
|
Making TF MPNet model compliant with XLA (#<I>)
* Fix XLA
* Rework cast
* Apply style
|
huggingface_pytorch-pretrained-BERT
|
train
|
f037acaed7b057a8124624b20bcfbd083fc8ecff
|
diff --git a/pandas/tests/io/pytables/__init__.py b/pandas/tests/io/pytables/__init__.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/io/pytables/__init__.py
+++ b/pandas/tests/io/pytables/__init__.py
@@ -6,4 +6,7 @@ pytestmark = [
"ignore:a closed node found in the registry:UserWarning"
),
pytest.mark.filterwarnings(r"ignore:tostring\(\) is deprecated:DeprecationWarning"),
+ pytest.mark.filterwarnings(
+ r"ignore:`np\.object` is a deprecated alias:DeprecationWarning"
+ ),
]
diff --git a/pandas/tests/window/__init__.py b/pandas/tests/window/__init__.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/window/__init__.py
+++ b/pandas/tests/window/__init__.py
@@ -0,0 +1,8 @@
+import pytest
+
+pytestmark = [
+ # 2021-02-01 needed until numba updates their usage
+ pytest.mark.filterwarnings(
+ r"ignore:`np\.int` is a deprecated alias:DeprecationWarning"
+ ),
+]
|
CI: numpy warnings produced by pytables (#<I>)
|
pandas-dev_pandas
|
train
|
ba51f1097db26a15b984b02c40a868d081f18d9a
|
diff --git a/.azure-pipelines.yml b/.azure-pipelines.yml
index <HASH>..<HASH> 100644
--- a/.azure-pipelines.yml
+++ b/.azure-pipelines.yml
@@ -2,53 +2,51 @@ trigger:
- master
jobs:
- - job: PyTest
- pool:
- vmImage: 'ubuntu-16.04'
- strategy:
- matrix:
- Python37:
- python.version: '3.7'
- Python36:
- python.version: '3.6'
- anndata_dev:
- python.version: '3.7'
- ANNDATA_DEV: yes
-
- steps:
- - task: UsePythonVersion@0
- inputs:
- versionSpec: '$(python.version)'
- displayName: 'Use Python $(python.version)'
-
- - script: |
- export MPLBACKEND="agg"
- echo $MPLBACKEND
- displayName: 'Set env'
-
- - script: |
- python -m pip install --upgrade pip
- pip install docutils sphinx
- pip install pytest-azurepipelines
- pip install -e .[dev,doc,test,louvain,leiden,magic,scvi,harmony]
- displayName: 'Install dependencies'
-
- - script: |
- pip install git+https://github.com/theislab/anndata
- displayName: 'Install development anndata'
- condition: eq(variables['ANNDATA_DEV'], 'yes')
-
- - script: |
- pip install black
- black . --check --diff
- python -m scanpy.tests.blackdiff 10
- displayName: 'Black'
-
- - script: |
- pytest --ignore=scanpy/tests/_images
- displayName: 'PyTest'
-
- - script: |
- python setup.py check --restructuredtext --strict
- rst2html.py --halt=2 README.rst >/dev/null
- displayName: 'rst2html'
+- job: PyTest
+ pool:
+ vmImage: 'ubuntu-16.04'
+ strategy:
+ matrix:
+ Python37:
+ python.version: '3.7'
+ Python36:
+ python.version: '3.6'
+ anndata_dev:
+ python.version: '3.7'
+ ANNDATA_DEV: yes
+ steps:
+ - task: UsePythonVersion@0
+ inputs:
+ versionSpec: '$(python.version)'
+ displayName: 'Use Python $(python.version)'
+
+ - script: |
+ export MPLBACKEND="agg"
+ echo $MPLBACKEND
+ displayName: 'Set env'
+
+ - script: |
+ python -m pip install --upgrade pip
+ pip install pytest-azurepipelines wheel
+ pip install -e .[dev,doc,test,louvain,leiden,magic,scvi,harmony]
+ displayName: 'Install dependencies'
+
+ - script: |
+ pip install git+https://github.com/theislab/anndata
+ displayName: 'Install development anndata'
+ condition: eq(variables['ANNDATA_DEV'], 'yes')
+
+ - script: |
+ pip install black
+ black . --check --diff
+ python -m scanpy.tests.blackdiff 10
+ displayName: 'Black'
+
+ - script: |
+ pytest --ignore=scanpy/tests/_images
+ displayName: 'PyTest'
+
+ - script: |
+ python setup.py check --restructuredtext --strict
+ rst2html.py --halt=2 README.rst >/dev/null
+ displayName: 'rst2html'
diff --git a/scanpy/__init__.py b/scanpy/__init__.py
index <HASH>..<HASH> 100644
--- a/scanpy/__init__.py
+++ b/scanpy/__init__.py
@@ -22,6 +22,7 @@ set_figure_params = settings.set_figure_params
# has to be done at the end, after everything has been imported
import sys
+sys.modules.update({f'{__name__}.{m}': globals()[m] for m in ['tl', 'pp', 'pl']})
from ._utils import annotate_doc_types
annotate_doc_types(sys.modules[__name__], 'scanpy')
del sys, annotate_doc_types
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -39,7 +39,7 @@ setup(
harmony=['harmonypy'],
dev=['setuptools_scm', 'pytoml', 'black>=20.8b1'],
doc=[
- 'sphinx<3.1, >3',
+ 'sphinx>=3.2',
'sphinx_rtd_theme>=0.3.1',
'sphinx_autodoc_typehints',
'scanpydoc>=0.5',
|
New pip resolver (#<I>)
|
theislab_scanpy
|
train
|
1e4543c30e065ff07c3acd55053648c6fd481c44
|
diff --git a/cli/src/main/java/org/jboss/as/cli/impl/DefaultOperationRequestParser.java b/cli/src/main/java/org/jboss/as/cli/impl/DefaultOperationRequestParser.java
index <HASH>..<HASH> 100644
--- a/cli/src/main/java/org/jboss/as/cli/impl/DefaultOperationRequestParser.java
+++ b/cli/src/main/java/org/jboss/as/cli/impl/DefaultOperationRequestParser.java
@@ -67,13 +67,19 @@ public class DefaultOperationRequestParser implements OperationRequestParser {
cmd = cmd.trim();
- int colonIndex = cmd.indexOf(ADDRESS_OPERATION_SEPARATOR);
+ int addrSepIndex = cmd.indexOf(ADDRESS_OPERATION_SEPARATOR);
+ int argListStartIndex = cmd.indexOf(ARG_LIST_START);
+ if(argListStartIndex > 0 && addrSepIndex > argListStartIndex) {
+ // the symbol belongs to an argument value
+ addrSepIndex = - 1;
+ }
+
/* if(colonIndex < 0) {
throw new CommandFormatException("Couldn't locate '" + ADDRESS_OPERATION_SEPARATOR + "'. Command '" + cmd + "' doesn't follow the format " + FORMAT);
}
*/
- if (colonIndex > 0) {
- String address = cmd.substring(0, colonIndex).trim();
+ if (addrSepIndex > 0) {
+ String address = cmd.substring(0, addrSepIndex).trim();
if (address.isEmpty()) {
throw new CommandFormatException(
"The address part is missing. Command '" + cmd
@@ -140,16 +146,15 @@ public class DefaultOperationRequestParser implements OperationRequestParser {
}
String operation;
- int argListStartIndex = cmd.indexOf(ARG_LIST_START, colonIndex + 1);
if(argListStartIndex < 0) {
//throw new CommandFormatException("Couldn't locate '" + ARG_LIST_START + "'. Command '" + cmd + "' doesn't follow the format " + FORMAT);
- int argListEndIndex = cmd.indexOf(ARG_LIST_END, colonIndex + 1);
+ int argListEndIndex = cmd.indexOf(ARG_LIST_END, addrSepIndex + 1);
if(argListEndIndex != -1)
throw new CommandFormatException("Couldn't locate '" + ARG_LIST_START + "' but found '" + ARG_LIST_END + "'. Command '" + cmd + "' doesn't follow the format " + FORMAT);
- operation = cmd.substring(colonIndex + 1);
+ operation = cmd.substring(addrSepIndex + 1);
}
else {
- operation = cmd.substring(colonIndex + 1, argListStartIndex).trim();
+ operation = cmd.substring(addrSepIndex + 1, argListStartIndex).trim();
}
if(operation.isEmpty()) {
throw new CommandFormatException("The operation name is missing: '" + cmd + "'");
|
differentiate between ':' being an address/operation name separator and a part of a parameter value
|
wildfly_wildfly
|
train
|
8652dc996e0d25784954a998aeadd5413af02f10
|
diff --git a/src/main/java/edu/ksu/canvas/impl/UserImpl.java b/src/main/java/edu/ksu/canvas/impl/UserImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/edu/ksu/canvas/impl/UserImpl.java
+++ b/src/main/java/edu/ksu/canvas/impl/UserImpl.java
@@ -39,7 +39,7 @@ public class UserImpl extends BaseImpl<User, UserReader, UserWriter> implements
Map<String, String> postParameters = new HashMap<>();
postParameters.put("name", user.getName());
postParameters.put("pseudonym[unique_id]", user.getLoginId());
- String createdUrl = buildCanvasUrl(CanvasConstants.ACCOUNT_ID + "/users", Collections.emptyMap());
+ String createdUrl = buildCanvasUrl( "accounts/" +CanvasConstants.ACCOUNT_ID + "/users", Collections.emptyMap());
LOG.debug("create URl for user creation : "+ createdUrl);
Response response = canvasMessenger.sendToCanvas(oauthToken, createdUrl, postParameters);
if (response.getErrorHappened() || ( response.getResponseCode() != 200)) {
|
corrected url for userImpl.
|
kstateome_canvas-api
|
train
|
2bd317e9288823f4c602b0ac314e72407bcb5ef6
|
diff --git a/src/js/form-builder.js b/src/js/form-builder.js
index <HASH>..<HASH> 100644
--- a/src/js/form-builder.js
+++ b/src/js/form-builder.js
@@ -2017,15 +2017,18 @@ const FormBuilder = function (opts, element, $) {
}
})
- $stage.children(rowWrapperClassSelector).each((i, elem) => {
- if ($(elem).children().length == 0 && !$(elem).hasClass(invisibleRowPlaceholderClass)) {
- const rowValue = h.getRowValue($(elem).attr('class'))
- formRows = formRows.filter(x => x != rowValue)
- $(elem).remove()
- } else {
- removeColumnInsertButtons($(elem))
- }
- })
+ $stage
+ .children(rowWrapperClassSelector)
+ .not(tmpRowPlaceholderClassSelector)
+ .each((i, elem) => {
+ if ($(elem).children(colWrapperClassSelector).length == 0) {
+ const rowValue = h.getRowValue($(elem).attr('class'))
+ formRows = formRows.filter(x => x != rowValue)
+ $(elem).remove()
+ } else {
+ removeColumnInsertButtons($(elem))
+ }
+ })
}
function stageHasFields() {
|
Ensure row is deleted when no more cols exist
|
kevinchappell_formBuilder
|
train
|
3c44fc3e6bc81b77c611078907d62070cdb0e873
|
diff --git a/rdopkg/utils/specfile.py b/rdopkg/utils/specfile.py
index <HASH>..<HASH> 100644
--- a/rdopkg/utils/specfile.py
+++ b/rdopkg/utils/specfile.py
@@ -325,11 +325,10 @@ class Spec(object):
"""Return a tuple (version, number_of_commits) that are parsed
from the patches_base in the specfile.
"""
- match = re.search(r'(?<=patches_base=)[\w.+?%{}]+', self.txt)
- if not match:
+ patches_base = self.get_magic_comment('patches_base')
+ if patches_base is None:
return None, 0
- patches_base = match.group()
if expand_macros and has_macros(patches_base):
# don't parse using rpm unless required
patches_base = self.expand_macro(patches_base)
@@ -355,11 +354,9 @@ class Spec(object):
Only a very limited subset of characters are accepted so no fancy stuff
like matching groups etc.
"""
- match = re.search(r'# *patches_ignore=([\w *.+?[\]|{,}\-_]+)',
- self.txt)
- if not match:
+ regex_string = self.get_magic_comment('patches_ignore')
+ if regex_string is None:
return None
- regex_string = match.group(1)
try:
return re.compile(regex_string)
except Exception:
|
specfile: convert to using get_magic_comment
* now that we have functionality swap out duplicate
regex for get_magic_comment method which is available
* replace duplicate logic in get_patches_base and get_patches_ignore_regex
Change-Id: Id<I>da2be1b9a<I>d4f<I>
|
softwarefactory-project_rdopkg
|
train
|
c27c344ffd0e30029b613cc0c0e8718a0789a9ee
|
diff --git a/src/circuit.js b/src/circuit.js
index <HASH>..<HASH> 100644
--- a/src/circuit.js
+++ b/src/circuit.js
@@ -43,7 +43,9 @@ class Circuit {
this.dialer = new CircuitDialer(swarm, options)
- this.swarm.on('peer-mux-established', this.dialer.canHop.bind(this.dialer))
+ this.swarm.on('peer-mux-established', (peerInfo) => {
+ this.dialer.canHop(peerInfo)
+ })
this.swarm.on('peer-mux-closed', (peerInfo) => {
this.dialer.relayPeers.delete(peerInfo.id.toB58String())
})
|
fix: connection establishment event handling (#<I>)
|
libp2p_js-libp2p-circuit
|
train
|
78d6dda005ca304d5e021e977d361a8d09d736df
|
diff --git a/builder/digitalocean/api.go b/builder/digitalocean/api.go
index <HASH>..<HASH> 100644
--- a/builder/digitalocean/api.go
+++ b/builder/digitalocean/api.go
@@ -5,12 +5,16 @@
package digitalocean
type Region struct {
- Id uint `json:"id,omitempty"` //only in v1 api
- Slug string `json:"slug"` //presen in both api
- Name string `json:"name"` //presen in both api
- Sizes []string `json:"sizes,omitempty"` //only in v2 api
- Available bool `json:"available,omitempty"` //only in v2 api
- Features []string `json:"features,omitempty"` //only in v2 api
+ Slug string `json:"slug"`
+ Name string `json:"name"`
+
+ // v1 only
+ Id uint `json:"id,omitempty"`
+
+ // v2 only
+ Sizes []string `json:"sizes,omitempty"`
+ Available bool `json:"available,omitempty"`
+ Features []string `json:"features,omitempty"`
}
type RegionsResp struct {
@@ -18,16 +22,19 @@ type RegionsResp struct {
}
type Size struct {
- Id uint `json:"id,omitempty"` //only in v1 api
- Name string `json:"name,omitempty"` //only in v1 api
- Slug string `json:"slug"` //presen in both api
- Memory uint `json:"memory,omitempty"` //only in v2 api
- VCPUS uint `json:"vcpus,omitempty"` //only in v2 api
- Disk uint `json:"disk,omitempty"` //only in v2 api
- Transfer float64 `json:"transfer,omitempty"` //only in v2 api
- PriceMonthly float64 `json:"price_monthly,omitempty"` //only in v2 api
- PriceHourly float64 `json:"price_hourly,omitempty"` //only in v2 api
- Regions []string `json:"regions,omitempty"` //only in v2 api
+ Slug string `json:"slug"`
+
+ // v1 only
+ Id uint `json:"id,omitempty"`
+ Name string `json:"name,omitempty"`
+
+ // v2 only
+ Memory uint `json:"memory,omitempty"`
+ VCPUS uint `json:"vcpus,omitempty"`
+ Disk uint `json:"disk,omitempty"`
+ Transfer float64 `json:"transfer,omitempty"`
+ PriceMonthly float64 `json:"price_monthly,omitempty"`
+ PriceHourly float64 `json:"price_hourly,omitempty"`
}
type SizesResp struct {
@@ -35,14 +42,15 @@ type SizesResp struct {
}
type Image struct {
- Id uint `json:"id"` //presen in both api
- Name string `json:"name"` //presen in both api
- Slug string `json:"slug"` //presen in both api
- Distribution string `json:"distribution"` //presen in both api
- Public bool `json:"public,omitempty"` //only in v2 api
- Regions []string `json:"regions,omitempty"` //only in v2 api
- ActionIds []string `json:"action_ids,omitempty"` //only in v2 api
- CreatedAt string `json:"created_at,omitempty"` //only in v2 api
+ Id uint `json:"id"`
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ Distribution string `json:"distribution"`
+
+ // v2 only
+ Public bool `json:"public,omitempty"`
+ ActionIds []string `json:"action_ids,omitempty"`
+ CreatedAt string `json:"created_at,omitempty"`
}
type ImagesResp struct {
|
builder/digitalocean: fix response decoding after api changes
|
hashicorp_packer
|
train
|
7f2837ea4c6250bb566ec8b0ed8d87d2c58c89f7
|
diff --git a/eos/eos.go b/eos/eos.go
index <HASH>..<HASH> 100644
--- a/eos/eos.go
+++ b/eos/eos.go
@@ -11,6 +11,7 @@ import (
"strconv"
"github.com/itchio/httpkit/httpfile"
+ "github.com/itchio/httpkit/retrycontext"
"github.com/itchio/wharf/eos/option"
"github.com/pkg/errors"
)
@@ -105,6 +106,10 @@ func realOpen(name string, opts ...option.Option) (File, error) {
res := &simpleHTTPResource{name}
hf, err := httpfile.New(res.GetURL, res.NeedsRenewal, &httpfile.Settings{
Client: settings.HTTPClient,
+ RetrySettings: &retrycontext.Settings{
+ MaxTries: settings.MaxTries,
+ Consumer: settings.Consumer,
+ },
})
if err != nil {
diff --git a/eos/option/option.go b/eos/option/option.go
index <HASH>..<HASH> 100644
--- a/eos/option/option.go
+++ b/eos/option/option.go
@@ -6,15 +6,20 @@ import (
"time"
"github.com/itchio/httpkit/timeout"
+ "github.com/itchio/wharf/state"
)
type EOSSettings struct {
HTTPClient *http.Client
+ Consumer *state.Consumer
+ MaxTries int
}
func DefaultSettings() *EOSSettings {
return &EOSSettings{
HTTPClient: defaultHTTPClient(),
+ Consumer: nil,
+ MaxTries: 2,
}
}
@@ -44,3 +49,44 @@ func defaultHTTPClient() *http.Client {
type Option interface {
Apply(*EOSSettings)
}
+
+//
+
+type httpClientOption struct {
+ client *http.Client
+}
+
+func (o *httpClientOption) Apply(settings *EOSSettings) {
+ settings.HTTPClient = o.client
+}
+
+func WithHTTPClient(client *http.Client) Option {
+ return &httpClientOption{client}
+}
+
+//
+
+type consumerOption struct {
+ consumer *state.Consumer
+}
+
+func (o *consumerOption) Apply(settings *EOSSettings) {
+ settings.Consumer = o.consumer
+}
+func WithConsumer(consumer *state.Consumer) Option {
+ return &consumerOption{consumer}
+}
+
+//
+
+type maxTriesOption struct {
+ maxTries int
+}
+
+func (o *maxTriesOption) Apply(settings *EOSSettings) {
+ settings.MaxTries = o.maxTries
+}
+
+func WithMaxTries(maxTries int) Option {
+ return &maxTriesOption{maxTries}
+}
|
Add a bunch of options for eos.Open (HTTPClient, MaxTries, Consumer)
|
itchio_wharf
|
train
|
fcfc99d92df9738d712ef0250335c2ee65dabd15
|
diff --git a/lib/seeder.js b/lib/seeder.js
index <HASH>..<HASH> 100644
--- a/lib/seeder.js
+++ b/lib/seeder.js
@@ -2,11 +2,12 @@ var Seed = require('./seed');
var log = require('./log');
var dbmUtil = require('./util');
var Promise = require('bluebird');
+var SeederInterface = require( './interface/seederInterface.js');
var internals = {};
Seeder = function (driver, seedsDir, versionControlled, intern) {
- this.driver = driver;
+ this.driver = dbmUtil.reduceToInterface( driver, SeederInterface );
this.seedDir = seedsDir;
this.isVC = versionControlled;
internals = intern;
|
add reducteToInterface to seeder
|
db-migrate_node-db-migrate
|
train
|
c33cae8bc099908fc5ce58f03d469601417cc10d
|
diff --git a/jsmpp-examples/src/main/java/org/jsmpp/examples/SimpleSubmitExample.java b/jsmpp-examples/src/main/java/org/jsmpp/examples/SimpleSubmitExample.java
index <HASH>..<HASH> 100644
--- a/jsmpp-examples/src/main/java/org/jsmpp/examples/SimpleSubmitExample.java
+++ b/jsmpp-examples/src/main/java/org/jsmpp/examples/SimpleSubmitExample.java
@@ -71,7 +71,7 @@ public class SimpleSubmitExample {
LOGGER.error("Receive invalid response", e);
} catch (NegativeResponseException e) {
// Receiving negative response (non-zero command_status)
- LOGGER.error("Receive negative response, e");
+ LOGGER.error("Receive negative response", e);
} catch (IOException e) {
LOGGER.error("IO error occurred", e);
}
|
Correcting double quotation mark position
at NegativeResponseException case
|
opentelecoms-org_jsmpp
|
train
|
03bcf911253b3195c6afe5ea70a6e61c73c93575
|
diff --git a/lib/giston/commands.rb b/lib/giston/commands.rb
index <HASH>..<HASH> 100644
--- a/lib/giston/commands.rb
+++ b/lib/giston/commands.rb
@@ -30,11 +30,16 @@ module Giston
msg "Local revision: #{local_revision}. Remote revision: #{remote_revision}"
if git.local_directory_exists?(mirror["dir"])
- if local_revision.to_i >= remote_revision.to_i
+ if local_revision.to_i > remote_revision.to_i
msg %(Skipping "#{mirror["dir"]} (local revision is greater than remote revision)")
return
end
+ if local_revision.to_i == remote_revision.to_i
+ msg %(Skipping "#{mirror["dir"]} (no changes between local and remote revision)")
+ return
+ end
+
if git.local_changes?(mirror["dir"])
msg "There are local changes in the directory you're trying to update"
return
|
Add a friendlier message when the remote and local revsions are the same [Ferdinand Svehla]
|
cristibalan_braid
|
train
|
03916cd0e367bbf20d7acd2f01844f64e4aef7d3
|
diff --git a/src/dar/UnpackedDarFolderStorage.js b/src/dar/UnpackedDarFolderStorage.js
index <HASH>..<HASH> 100644
--- a/src/dar/UnpackedDarFolderStorage.js
+++ b/src/dar/UnpackedDarFolderStorage.js
@@ -3,7 +3,7 @@ import FSStorage from './FSStorage'
/**
* A storage implementation that is bound to a single folder.
*/
-export default class SingleDarFolderStorage extends FSStorage {
+export default class UnpackedDarFolderStorage extends FSStorage {
constructor (darFolder) {
super()
diff --git a/test/Storage.test.js b/test/Storage.test.js
index <HASH>..<HASH> 100644
--- a/test/Storage.test.js
+++ b/test/Storage.test.js
@@ -1,6 +1,6 @@
import { testAsync } from 'substance-test'
import { uuid } from 'substance'
-import { DarFileStorage } from '../index'
+import { DarFileStorage, UnpackedDarFolderStorage } from '../index'
import { promisify } from './shared/testHelpers'
// ATTENTION: these tests can not be run in the browser
@@ -48,6 +48,16 @@ testAsync('Storage: reading the kitchen-sink.dar', async t => {
t.end()
})
+testAsync('Storage: reading a DAR folder', async t => {
+ let darPath = path.join(process.cwd(), 'data', 'blank')
+ let storage = new UnpackedDarFolderStorage(darPath)
+ let rawArchive = await promisify(cb => {
+ storage.read(null, cb)
+ })
+ t.deepEqual(Object.keys(rawArchive.resources), ['manifest.xml', 'manuscript.xml'], 'archive should contain correct resources')
+ t.end()
+})
+
testAsync('Storage: cloning a .dar file', async t => {
let storageDir = _getTmpFolder()
let storage = new DarFileStorage(storageDir)
|
Add test for reading a dar from folder.
|
substance_texture
|
train
|
e922bbb7e6c26ae81e679f4ec03fff0c1e602758
|
diff --git a/test/filter_hc_somatic_test.py b/test/filter_hc_somatic_test.py
index <HASH>..<HASH> 100644
--- a/test/filter_hc_somatic_test.py
+++ b/test/filter_hc_somatic_test.py
@@ -47,8 +47,8 @@ class FilterSomaticTestCase(unittest.TestCase):
in_files = [input1, input2]
somatic_positions = {}
-
- excluded_variants = write_somatic(in_files, output_dir.path, somatic_positions)
+ execution_context = ["##foo", "##bar"]
+ excluded_variants = write_somatic(in_files, output_dir.path, somatic_positions, execution_context)
self.assertEqual(["mutect_HCsomatic.vcf", "varscan_HCsomatic.vcf"], output_dir.actual())
|
ex-<I> fixed erroneous test
|
umich-brcf-bioinf_Jacquard
|
train
|
a08cd04f3429b90b123f6e505411704558273e34
|
diff --git a/location_provider_impl.go b/location_provider_impl.go
index <HASH>..<HASH> 100644
--- a/location_provider_impl.go
+++ b/location_provider_impl.go
@@ -24,7 +24,10 @@ func testCallerInfo(skip int) (testName string, path string, line int) {
}
func callerInfo(skip int) (methodName string, path string, line int) {
- pc, path, line, _ := runtime.Caller(skip + 1)
+ pc, path, line, ok := runtime.Caller(skip + 1)
+ if !ok {
+ panic("you shall not pass!")
+ }
methodName = methodNameFromPC(pc)
return
}
diff --git a/location_provider_test.go b/location_provider_test.go
index <HASH>..<HASH> 100644
--- a/location_provider_test.go
+++ b/location_provider_test.go
@@ -21,3 +21,13 @@ func TestLocationProviderCalledFromAnotherFunction(t *testing.T) {
&location{"TestLocationProviderCalledFromAnotherFunction", "location_provider_test.go", 6},
)
}
+
+func TestLocationProviderPanicsWhenUsedIncorrectly(t *testing.T) {
+ assert := Setup(t)
+ defer func() {
+ r := recover()
+ assert.That(r).IsEqualTo("you shall not pass!")
+ }()
+ provideLocation(1)
+ t.Fail()
+}
|
you shall not pass wrong arguments to provideLocation
|
assertgo_assert
|
train
|
79a6989abb9363393f48cbd16a084b63ede3281b
|
diff --git a/src/main/java/hex/gbm/DHistogram.java b/src/main/java/hex/gbm/DHistogram.java
index <HASH>..<HASH> 100755
--- a/src/main/java/hex/gbm/DHistogram.java
+++ b/src/main/java/hex/gbm/DHistogram.java
@@ -73,6 +73,7 @@ public abstract class DHistogram<TDH extends DHistogram> extends Iced {
old = _maxIn;
}
+ private static int MAX_FACTOR_BINS=1024; // Allow more bins for factors
public DHistogram( String name, final int nbins, final byte isInt, final float min, final float maxEx, long nelems, int min_rows, boolean doGrpSplit ) {
assert nelems > 0;
assert nbins >= 1;
@@ -88,17 +89,15 @@ public abstract class DHistogram<TDH extends DHistogram> extends Iced {
// See if we can show there are fewer unique elements than nbins.
// Common for e.g. boolean columns, or near leaves.
int xbins = nbins;
- float step;
- if( isInt>0 && maxEx-min <= nbins ) {
+ if( isInt>0 && maxEx-min <= Math.max(nbins,(isInt==2?MAX_FACTOR_BINS:nbins)) ) {
assert ((long)min)==min; // No overflow
xbins = (char)((long)maxEx-(long)min); // Shrink bins
assert xbins > 1; // Caller ensures enough range to bother
- step = 1.0f; // Fixed stepsize
+ _step = 1.0f; // Fixed stepsize
} else {
- step = (maxEx-min)/nbins; // Step size for linear interpolation
- assert step > 0;
+ _step = nbins/(maxEx-min);
+ assert _step > 0 && !Float.isInfinite(_step);
}
- _step = 1.0f/step; // Use multiply instead of division during frequent binning math
_nbin = (char)xbins;
// Do not allocate the big arrays here; wait for scoreCols to pick which cols will be used.
}
@@ -174,7 +173,8 @@ public abstract class DHistogram<TDH extends DHistogram> extends Iced {
static public float find_maxEx(float maxIn, int isInt ) {
float ulp = Math.ulp(maxIn);
if( isInt > 0 && 1 > ulp ) ulp = 1;
- return maxIn+ulp;
+ float res = maxIn+ulp;
+ return Float.isInfinite(res) ? maxIn : res;
}
// Compute a "score" for a column; lower score "wins" (is a better split).
|
Fix categorical handling to always use bitsets. Was doing ordinal comparison (treating categoricals as numerical) for #factors < #bins.
This is related to HEXDEV-<I>.
|
h2oai_h2o-2
|
train
|
0f019d31146ebe4bafff110095e909e0f66dec6e
|
diff --git a/plugins/UserCountryMap/js/realtime-map.js b/plugins/UserCountryMap/js/realtime-map.js
index <HASH>..<HASH> 100644
--- a/plugins/UserCountryMap/js/realtime-map.js
+++ b/plugins/UserCountryMap/js/realtime-map.js
@@ -203,8 +203,8 @@ RealTimeMap.run = function(config) {
function visitSymbolAttrs(r) {
return {
fill: visitColor(r),
- 'fill-opacity': Math.pow(age(r),2),
- 'stroke-opacity': Math.pow(age(r),1.7),
+ 'fill-opacity': Math.pow(age(r),2) * 0.8 + 0.2,
+ 'stroke-opacity': Math.pow(age(r),1.7) * 0.8 + 0.2,
stroke: '#fff',
'stroke-width': age(r),
r: visitRadius(r)
@@ -338,28 +338,6 @@ RealTimeMap.run = function(config) {
//console.info('added', newSymbols.length, visitSymbols.symbols.length, $('circle').length);
visitSymbols.layout().render();
- // remove all symbols
- // if (!firstRun && map.symbolGroups.length-1) {
- // console.info('remove all symbols');
- // map.removeSymbols();
- // }
-
- // console.info('add new symbols');
- // visitSymbols = map.addSymbols({
- // data: lastVisits.reverse(),
- // type: Kartograph.Bubble,
- // sortBy: function(r) { return r.lastActionTimestamp; },
- // radius: visitRadius,
- // location: function(r) { return [r.longitude, r.latitude]; },
- // attrs: visitSymbolAttrs,
- // tooltip: visitTooltip,
- // mouseenter: highlightVisit,
- // mouseleave: unhighlightVisit,
- // click: function(r, s, evt) {
- // evt.stopPropagation();
- // }
- // });
-
//console.info('rendered', visitSymbols.symbols.length, $('circle').length);
$.each(newSymbols, function(i, s) {
|
minimum opacity set to <I>
|
matomo-org_matomo
|
train
|
69275c6b2d22bee629d50aa2e05d09b320707993
|
diff --git a/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java b/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java
index <HASH>..<HASH> 100644
--- a/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java
+++ b/sentry-android-core/src/main/java/io/sentry/android/core/DefaultAndroidEventProcessor.java
@@ -404,7 +404,8 @@ final class DefaultAndroidEventProcessor implements EventProcessor {
private Date getBootTime() {
// if user changes time, will give a wrong answer, consider ACTION_TIME_CHANGED
- return new Date(System.currentTimeMillis() - SystemClock.elapsedRealtime());
+ return DateUtils.getDateTime(
+ new Date(System.currentTimeMillis() - SystemClock.elapsedRealtime()));
}
private String getResolution(DisplayMetrics displayMetrics) {
diff --git a/sentry-core/src/main/java/io/sentry/core/DateUtils.java b/sentry-core/src/main/java/io/sentry/core/DateUtils.java
index <HASH>..<HASH> 100644
--- a/sentry-core/src/main/java/io/sentry/core/DateUtils.java
+++ b/sentry-core/src/main/java/io/sentry/core/DateUtils.java
@@ -83,4 +83,15 @@ public final class DateUtils {
DateFormat df = new SimpleDateFormat(ISO_FORMAT, Locale.US);
return df.format(date);
}
+
+ /**
+ * Converts the given Date and time to UTC timezone
+ *
+ * @param date the Date with local timezone
+ * @return the Date UTC timezone
+ */
+ public static Date getDateTime(Date date) {
+ String timestampIsoFormat = getTimestampIsoFormat(date);
+ return getDateTime(timestampIsoFormat);
+ }
}
|
boot time should be UTC (getsentry/sentry-android#<I>)
|
getsentry_sentry-java
|
train
|
e02c90887e2c6e5a0d51d2e825a03ea029123973
|
diff --git a/changelog.txt b/changelog.txt
index <HASH>..<HASH> 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -14,7 +14,7 @@ to clearly indicate the caller is specifying a message with arguments to use in
* Introduced the ComparatorUtils.nullSafeArgumentsComparator(:Comparator) to protect against null arguments passed
to the Comparator implementation during the comparison operation.
* Introduced the ComparatorsUtils.nullSafeComparator(:Comparator) to guard against null Comparator reference,
-providing a null-safe default, Comparable Comparator implementation.
+providing a null-safe, default, Comparable Comparator implementation.
* Created the org.cp.elements.text.FormatUtils abstract utility class for working with text content.
* Refactored and polished the org.cp.elements.lang.ThrowableUtils class; added a null-safe getCause(:Throwable) method.
* ?
diff --git a/src/main/java/org/cp/elements/util/PropertiesBuilder.java b/src/main/java/org/cp/elements/util/PropertiesBuilder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/cp/elements/util/PropertiesBuilder.java
+++ b/src/main/java/org/cp/elements/util/PropertiesBuilder.java
@@ -91,10 +91,10 @@ public class PropertiesBuilder {
* @see java.util.Map
* @see #from(Properties)
*/
- public static PropertiesBuilder from(Map<String, Object> map) {
+ public static PropertiesBuilder from(Map<String, ?> map) {
Properties properties = new Properties();
- for (Map.Entry<String, Object> entry : map.entrySet()) {
+ for (Map.Entry<String, ?> entry : map.entrySet()) {
properties.setProperty(entry.getKey(), String.valueOf(entry.getValue()));
}
@@ -115,7 +115,19 @@ public class PropertiesBuilder {
}
/**
- * Factory method to construct a new isntance of the {@link PropertiesBuilder} class initialized
+ * Factory method to construct a new instance of the {@link PropertiesBuilder} class initialized
+ * with the System environment variables.
+ *
+ * @return a newly constructed {@link PropertiesBuilder} initialized with the System properties.
+ * @see java.lang.System#getProperties()
+ * @see #from(Properties)
+ */
+ public static PropertiesBuilder fromEnvironmentVariables() {
+ return from(System.getenv());
+ }
+
+ /**
+ * Factory method to construct a new instance of the {@link PropertiesBuilder} class initialized
* from the System properties.
*
* @return a newly constructed {@link PropertiesBuilder} initialized with the System properties.
@@ -224,5 +236,4 @@ public class PropertiesBuilder {
public String toString() {
return getProperties().toString();
}
-
}
diff --git a/src/test/java/org/cp/elements/util/PropertiesBuilderTests.java b/src/test/java/org/cp/elements/util/PropertiesBuilderTests.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/cp/elements/util/PropertiesBuilderTests.java
+++ b/src/test/java/org/cp/elements/util/PropertiesBuilderTests.java
@@ -46,8 +46,7 @@ import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
- * The PropertiesBuilderTest class is a test suite of test cases testing the contract and functionality
- * of the {@link PropertiesBuilder} class.
+ * Unit tests for {@link PropertiesBuilder}.
*
* @author John J. Blum
* @see org.junit.Rule
@@ -164,10 +163,18 @@ public class PropertiesBuilderTests {
}
@Test
+ public void fromEnvironmentVariablesLoadsProperties() {
+ PropertiesBuilder propertiesBuilder = PropertiesBuilder.fromEnvironmentVariables();
+
+ assertThat(propertiesBuilder, is(notNullValue(PropertiesBuilder.class)));
+ assertThat(propertiesBuilder.build(), is(equalTo(System.getenv())));
+ }
+
+ @Test
public void fromSystemPropertiesLoadsProperties() {
PropertiesBuilder propertiesBuilder = PropertiesBuilder.fromSystemProperties();
- assertThat(propertiesBuilder, is(notNullValue()));
+ assertThat(propertiesBuilder, is(notNullValue(PropertiesBuilder.class)));
assertThat(propertiesBuilder.build(), is(equalTo(System.getProperties())));
}
@@ -314,5 +321,4 @@ public class PropertiesBuilderTests {
return getName();
}
}
-
}
|
Add the fromEnvironmentVariables() factory method to PropertiesBuilder to build a Properties object from System Environment Variables.
|
codeprimate-software_cp-elements
|
train
|
21e1ff4a8a2ca8fd7ea3f3a5c8adcc1e9fe3c599
|
diff --git a/pkg/sources/git/git.go b/pkg/sources/git/git.go
index <HASH>..<HASH> 100644
--- a/pkg/sources/git/git.go
+++ b/pkg/sources/git/git.go
@@ -107,7 +107,7 @@ func (s *Source) Init(aCtx context.Context, name string, jobId, sourceId int64,
}
s.git = NewGit(s.Type(), s.jobId, s.sourceId, s.name, s.verify, concurrency,
- func(file, email, commit, repository, timestamp string, line int64) *source_metadatapb.MetaData {
+ func(file, email, commit, timestamp, repository string, line int64) *source_metadatapb.MetaData {
return &source_metadatapb.MetaData{
Data: &source_metadatapb.MetaData_Git{
Git: &source_metadatapb.Git{
@@ -177,7 +177,7 @@ func (s *Source) Chunks(ctx context.Context, chunksChan chan *sources.Chunk) err
continue
}
if !strings.HasSuffix(u, "git") {
- //try paths instead of url
+ // try paths instead of url
repo, err := RepoFromPath(u)
if err != nil {
return err
@@ -431,9 +431,9 @@ func (s *Git) ScanRepo(_ context.Context, repo *git.Repository, repoPath string,
return nil
}
-//GenerateLink crafts a link to the specific file from a commit. This works in most major git providers (Github/Gitlab)
+// GenerateLink crafts a link to the specific file from a commit. This works in most major git providers (Github/Gitlab)
func GenerateLink(repo, commit, file string) string {
- //bitbucket links are commits not commit...
+ // bitbucket links are commits not commit...
if strings.Contains(repo, "bitbucket.org/") {
return repo[:len(repo)-4] + "/commits/" + commit
}
|
Fix the order to correctly match the params in NewGit. (#<I>)
|
dxa4481_truffleHog
|
train
|
3db3ac9c98e141996f4d1a7db89cbc8d8ffde443
|
diff --git a/lib/services/user.go b/lib/services/user.go
index <HASH>..<HASH> 100644
--- a/lib/services/user.go
+++ b/lib/services/user.go
@@ -8,7 +8,6 @@ import (
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/utils"
- "github.com/gravitational/configure/cstrings"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
)
@@ -379,8 +378,8 @@ func (u *UserV2) Check() error {
if u.Version == "" {
return trace.BadParameter("user version is not set")
}
- if !cstrings.IsValidUnixUser(u.Metadata.Name) {
- return trace.BadParameter("'%v' is not a valid user name", u.Metadata.Name)
+ if u.Metadata.Name == "" {
+ return trace.BadParameter("user name cannot be empty")
}
for _, id := range u.Spec.OIDCIdentities {
if err := id.Check(); err != nil {
@@ -418,8 +417,8 @@ type UserV1 struct {
// Check checks validity of all parameters
func (u *UserV1) Check() error {
- if !cstrings.IsValidUnixUser(u.Name) {
- return trace.BadParameter("'%v' is not a valid user name", u.Name)
+ if u.Name == "" {
+ return trace.BadParameter("user name cannot be empty")
}
for _, id := range u.OIDCIdentities {
if err := id.Check(); err != nil {
|
Removing unix user name check from Teleport user name.
|
gravitational_teleport
|
train
|
adf33f787ff8a981219c23cc9f0c011dc6168073
|
diff --git a/tests/python/pants_test/tasks/test_junit_tests_integration.py b/tests/python/pants_test/tasks/test_junit_tests_integration.py
index <HASH>..<HASH> 100644
--- a/tests/python/pants_test/tasks/test_junit_tests_integration.py
+++ b/tests/python/pants_test/tasks/test_junit_tests_integration.py
@@ -7,6 +7,7 @@ from __future__ import (absolute_import, division, generators, nested_scopes, pr
import os
import unittest
+from xml.etree import ElementTree
from pants.util.contextutil import temporary_dir
from pants_test.pants_run_integration_test import PantsRunIntegrationTest
@@ -137,9 +138,11 @@ class JunitTestsIntegrationTest(PantsRunIntegrationTest):
self.assertTrue(os.path.exists(
os.path.join(workdir, 'test', 'junit', 'coverage', 'html', 'index.html')))
- # TODO(Eric Ayers): Look at the xml report. I think something is broken, it is empty
- self.assertTrue(os.path.exists(
- os.path.join(workdir, 'test', 'junit', 'coverage', 'xml', 'coverage.xml')))
+ xmlf = os.path.join(workdir, 'test', 'junit', 'coverage', 'xml', 'coverage.xml')
+ self.assertTrue(os.path.exists(xmlf))
+ hits = ElementTree.parse(xmlf).findall("packages/package/classes/class/lines/line")
+ if all(i.attrib['hits'] == "0" for i in hits):
+ self.fail("no nonzero hits found in the generated coverage.xml")
def test_junit_test_requiring_cwd_fails_without_option_specified(self):
pants_run = self.run_pants([
|
sanity check on generated cobertura xml report
One of our users was getting zero hits reported in the cobertura xml
report, which is used by the cobertura jenkins plugin. His generated
html was fine. We couldn't track down the error but this patch adds a
test for that condition. We needed some kind of test on the generated
cobertura reports anyway.
pull request: <URL>
|
pantsbuild_pants
|
train
|
03df850cda40deab4160c390336f9e964b593858
|
diff --git a/Task/Collect/DataTypesCollector.php b/Task/Collect/DataTypesCollector.php
index <HASH>..<HASH> 100644
--- a/Task/Collect/DataTypesCollector.php
+++ b/Task/Collect/DataTypesCollector.php
@@ -26,6 +26,7 @@ class DataTypesCollector extends CollectorBase {
protected $testingDataTypes = [
'text' => TRUE,
'boolean' => TRUE,
+ 'label' => TRUE,
];
/**
diff --git a/Task/Collect/FieldTypesCollector.php b/Task/Collect/FieldTypesCollector.php
index <HASH>..<HASH> 100644
--- a/Task/Collect/FieldTypesCollector.php
+++ b/Task/Collect/FieldTypesCollector.php
@@ -25,6 +25,7 @@ class FieldTypesCollector extends CollectorBase {
protected $testingFieldTypes = [
'text' => TRUE,
'boolean' => TRUE,
+ 'string' => TRUE,
];
/**
|
Fixed missing data and field types from test sample collection list.
|
drupal-code-builder_drupal-code-builder
|
train
|
c914429067da588ddcf217fac0db2eec9680a02b
|
diff --git a/MAVProxy/modules/mavproxy_speech.py b/MAVProxy/modules/mavproxy_speech.py
index <HASH>..<HASH> 100644
--- a/MAVProxy/modules/mavproxy_speech.py
+++ b/MAVProxy/modules/mavproxy_speech.py
@@ -7,8 +7,12 @@ from MAVProxy.modules.lib import mp_module
class SpeechModule(mp_module.MPModule):
def __init__(self, mpstate):
super(SpeechModule, self).__init__(mpstate, "speech", "speech output")
+ self.old_mpstate_say_function = self.mpstate.functions.say
self.mpstate.functions.say = self.say
- self.settings.append(('speech', int, 1))
+ try:
+ self.settings.set('speech', 1)
+ except AttributeError:
+ self.settings.append(('speech', int, 1))
self.kill_speech_dispatcher()
for backend in [self.say_speechd, self.say_espeak, self.say_speech]:
try:
@@ -40,6 +44,9 @@ class SpeechModule(mp_module.MPModule):
def unload(self):
'''unload module'''
+ self.settings.set('speech', 0)
+ if self.mpstate.functions.say == self.mpstate.functions.say:
+ self.mpstate.functions.say = self.old_mpstate_say_function
self.kill_speech_dispatcher()
def say_speechd(self, text, priority='important'):
|
speech: stop talking when speech unloaded
Also avoid appending the speech setting multiple times
as _keys grows
|
ArduPilot_MAVProxy
|
train
|
b5437d0f693e0cf6cf7c1dd4ab4d1bd370e89c1c
|
diff --git a/spec/unit/appmgmt_spec.rb b/spec/unit/appmgmt_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/appmgmt_spec.rb
+++ b/spec/unit/appmgmt_spec.rb
@@ -197,6 +197,17 @@ EOS
end
end
+
+ context "when using a site expression" do
+ it "the site expression is not evaluated in a node compilation" do
+ catalog = compile_to_catalog(MANIFEST_WITH_SITE, Puppet::Node.new('other'))
+ types = catalog.resource_keys.map { |type, _| type }.uniq.sort
+ expect(types).to eq(["Class", "Node", "Notify", "Stage"])
+ expect(catalog.resource("Notify[on a node]")).to_not be_nil
+ expect(catalog.resource("Notify[on the site]")).to be_nil
+ end
+
+ end
end
|
(PUP-<I>) Add evaluation of site expression
This adds evaluation of the site expression. It is treated analogous to
a node expression - but it contains the resources for all cross
node resources as apposed to the resources for a specific node.
This changes the environment compiler to prune the resulting catalog
from unwanted resources instead of attemting to stop them from being
added.
This implementation allows both the pre-site-expression style (in top
scope) and that application/cross node resources are in a
site-expression. This is expected to change.
|
puppetlabs_puppet
|
train
|
139fccb31e4f1977a80acc9346552f60c9b3a715
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -638,7 +638,7 @@ This will ignored if the top navigation layout is enabled, all menu items will a
To get a dynamic item placing you can add the `key` attribute, with this you can add a unique identifier to a add before or after it new items.
-Use the `can` attribute if you want conditionally show the menu item. This integrates with Laravel's `Gate` functionality. If you need to conditionally show headers as well, you need to wrap it in an array like other menu items, using the `header` attribute:
+Use the `can` attribute if you want conditionally show the menu item. This integrates with Laravel's `Gate` functionality. If you need to conditionally show headers as well, you need to wrap it in an array like other menu items, using the `header` attribute. You can add more `can` entries as array, see the second example:
```php
[
@@ -650,7 +650,7 @@ Use the `can` attribute if you want conditionally show the menu item. This integ
[
'text' => 'Add new post',
'url' => 'admin/blog/new',
- 'can' => 'add-blog-post'
+ 'can' => ['add-blog-post', 'other-right']
],
]
```
diff --git a/src/Menu/Filters/GateFilter.php b/src/Menu/Filters/GateFilter.php
index <HASH>..<HASH> 100644
--- a/src/Menu/Filters/GateFilter.php
+++ b/src/Menu/Filters/GateFilter.php
@@ -29,10 +29,22 @@ class GateFilter implements FilterInterface
return true;
}
+ $args = [];
+
if (isset($item['model'])) {
- return $this->gate->allows($item['can'], $item['model']);
+ $args = $item['model'];
+ }
+
+ if (! is_array($item['can'])) {
+ return $this->gate->allows($item['can'], $args);
+ }
+
+ foreach ($item['can'] as $can) {
+ if ($this->gate->allows($can, $args)) {
+ return true;
+ }
}
- return $this->gate->allows($item['can']);
+ return false;
}
}
diff --git a/tests/Menu/BuilderTest.php b/tests/Menu/BuilderTest.php
index <HASH>..<HASH> 100644
--- a/tests/Menu/BuilderTest.php
+++ b/tests/Menu/BuilderTest.php
@@ -523,6 +523,47 @@ class BuilderTest extends TestCase
$this->assertEquals('About', $builder->menu[0]['text']);
}
+ public function testMultipleCan()
+ {
+ $gate = $this->makeGate();
+ $gate->define(
+ 'show-users',
+ function () {
+ return true;
+ }
+ );
+ $gate->define(
+ 'edit-user',
+ function () {
+ return false;
+ }
+ );
+ $gate->define(
+ 'show-settings',
+ function () {
+ return false;
+ }
+ );
+
+ $builder = $this->makeMenuBuilder('http://example.com', $gate);
+
+ $builder->add(
+ [
+ 'text' => 'Users',
+ 'url' => 'users',
+ 'can' => ['show-users', 'edit-user'],
+ ],
+ [
+ 'text' => 'Settings',
+ 'url' => 'settings',
+ 'can' => ['show-settings'],
+ ]
+ );
+
+ $this->assertCount(1, $builder->menu);
+ $this->assertEquals('Users', $builder->menu[0]['text']);
+ }
+
public function testCanHeaders()
{
$gate = $this->makeGate();
@@ -563,7 +604,7 @@ class BuilderTest extends TestCase
$builder->add(['text' => 'profile', 'url' => '/profile', 'label' => 'labels']);
$builder->add(['text' => 'blog', 'url' => '/blog']);
$builder->add(['header' => 'TEST']);
- $this->assertCount(5, $builder->menu);
+ $this->assertCount(4, $builder->menu);
$this->assertEquals('Profile', $builder->menu[0]['header']);
$this->assertEquals('Profile', $builder->menu[1]['text']);
$this->assertEquals('LABELS', $builder->menu[1]['label']);
@@ -575,7 +616,7 @@ class BuilderTest extends TestCase
$builder->add(['text' => 'profile', 'url' => '/profile', 'label' => 'labels']);
$builder->add(['text' => 'blog', 'url' => '/blog']);
$builder->add(['header' => 'TEST']);
- $this->assertCount(5, $builder->menu);
+ $this->assertCount(4, $builder->menu);
$this->assertEquals('Profil', $builder->menu[0]['header']);
$this->assertEquals('Profil', $builder->menu[1]['text']);
$this->assertEquals('Beschriftungen', $builder->menu[1]['label']);
|
change the gate filter for more `can` entries (#<I>)
* change the gate filter for more `can` entries
* fix cs
* code improvments
* add test for multiple can
* fix cs
* fix tests
* fix tests
|
jeroennoten_Laravel-AdminLTE
|
train
|
a70277fc9e4dd0ed4ef9a0480dd59131ca8ccf2e
|
diff --git a/container/controller.go b/container/controller.go
index <HASH>..<HASH> 100644
--- a/container/controller.go
+++ b/container/controller.go
@@ -343,13 +343,10 @@ func NewController(options ControllerOptions) (*Controller, error) {
glog.Errorf("Could not setup logstash files error:%s", err)
return c, fmt.Errorf("container: invalid LogStashFiles error:%s", err)
}
-
- // make sure we pick up any logfile that was modified within the
- // last three years
- // TODO: Either expose the 3 years a configurable or get rid of it
logforwarder, exited, err := subprocess.New(time.Second,
nil,
options.Logforwarder.Path,
+ "-e", // Log to stderr
"-c", options.Logforwarder.ConfigFile)
if err != nil {
return nil, err
@@ -507,7 +504,7 @@ func (c *Controller) rpcHealthCheck() (chan struct{}, error) {
retries := 3
failures := 0
for {
- err := client.Ping(2 * time.Second, &ts)
+ err := client.Ping(2*time.Second, &ts)
if err != nil {
failures++
glog.Warningf("RPC Server healthcheck ping to delegate failed. Error: %v", err)
diff --git a/container/logstash.go b/container/logstash.go
index <HASH>..<HASH> 100644
--- a/container/logstash.go
+++ b/container/logstash.go
@@ -14,8 +14,9 @@
package container
import (
- "bytes"
+ "bytes"
"fmt"
+
"github.com/control-center/serviced/domain/service"
"github.com/control-center/serviced/domain/servicedefinition"
"github.com/zenoss/glog"
@@ -48,12 +49,12 @@ func formatTagsForConfFile(tags map[string]string) string {
if len(tags) == 0 {
return ""
}
- var buffer bytes.Buffer
- buffer.WriteString("{")
- for k, v := range tags {
- buffer.WriteString(k + ": " + v + ", ")
- }
- buffer.WriteString("}")
+ var buffer bytes.Buffer
+ buffer.WriteString("{")
+ for k, v := range tags {
+ buffer.WriteString(k + ": " + v + ", ")
+ }
+ buffer.WriteString("}")
return buffer.String()
}
@@ -65,8 +66,8 @@ func writeLogstashAgentConfig(confPath string, hostID string, service *service.S
filebeatLogConf := ``
for _, logConfig := range service.LogConfigs {
filebeatLogConf = filebeatLogConf + `
- -
- ignore_older: 26280h
+ - ignore_older: 10s
+ close_older: 5m
paths:
- %s
fields: %s`
@@ -75,7 +76,7 @@ func writeLogstashAgentConfig(confPath string, hostID string, service *service.S
}
filebeatShipperConf :=
-`filebeat:
+ `filebeat:
idle_timeout: 5s
prospectors: %s
output:
@@ -89,18 +90,17 @@ output:
certificate_key: %s
certificate_authorities:
- %s
- timeout: 15
+ timeout: 15
logging:
- to_syslog: false`
+ level: warning`
filebeatShipperConf = fmt.Sprintf(filebeatShipperConf,
- filebeatLogConf,
-// "172.17.42.1:5043",
+ filebeatLogConf,
"127.0.0.1:5043",
resourcePath+"/filebeat.crt",
resourcePath+"/filebeat.key",
resourcePath+"/filebeat.crt",
- )
+ )
config := servicedefinition.ConfigFile{
Filename: confPath,
|
Log filebeat to container logs; update config to close file handles that don't get used; don't pick up old log files
|
control-center_serviced
|
train
|
0c7d6f974a37583ff0ca3e905fd38fb7312b9f5e
|
diff --git a/core/config/rcm-core-config.php b/core/config/rcm-core-config.php
index <HASH>..<HASH> 100644
--- a/core/config/rcm-core-config.php
+++ b/core/config/rcm-core-config.php
@@ -273,12 +273,12 @@ return [
'post-libraries' => [],
'pre-rcm' => [],
'rcm' => [
- '/modules/rcm/rcm.css' => [],
+ '/modules/rcm/rcm.css' => ['media' => 'screen,print'],
],
'post-rcm' => [],
'pre-modules' => [],
'modules' => [
- '/modules/rcm/modules.css' => [],
+ '/modules/rcm/modules.css' => ['media' => 'screen,print'],
],
'post-modules' => [],
],
|
ensure print css works in RCM
|
reliv_Rcm
|
train
|
5e60ea906620857beae12a1fa64d715ff82844d5
|
diff --git a/proton-c/bindings/python/proton/__init__.py b/proton-c/bindings/python/proton/__init__.py
index <HASH>..<HASH> 100644
--- a/proton-c/bindings/python/proton/__init__.py
+++ b/proton-c/bindings/python/proton/__init__.py
@@ -3757,6 +3757,10 @@ class Event(Wrapper, EventBase):
def _init(self):
pass
+ def copy(self):
+ copy = pn_event_copy(self._impl)
+ return Event.wrap(copy)
+
@property
def clazz(self):
cls = pn_event_class(self._impl)
diff --git a/proton-c/include/proton/cproton.i b/proton-c/include/proton/cproton.i
index <HASH>..<HASH> 100644
--- a/proton-c/include/proton/cproton.i
+++ b/proton-c/include/proton/cproton.i
@@ -613,6 +613,17 @@ typedef unsigned long int uintptr_t;
%include "proton/transport.h"
%include "proton/event.h"
+%inline %{
+ /* assume the binding does the incref in the wrapper */
+ pn_event_t* pn_event_copy(pn_event_t *evt) { return evt; }
+%}
+
+%contract pn_event_copy(pn_event_t *evt)
+{
+ require:
+ evt != NULL;
+}
+
%contract pn_message_free(pn_message_t *msg)
{
require:
diff --git a/proton-j/src/main/resources/cengine.py b/proton-j/src/main/resources/cengine.py
index <HASH>..<HASH> 100644
--- a/proton-j/src/main/resources/cengine.py
+++ b/proton-j/src/main/resources/cengine.py
@@ -1044,6 +1044,9 @@ class pn_event:
def __init__(self, impl):
self.impl = impl
+ def copy(self):
+ return pn_event(self.impl.copy())
+
def pn_collector_peek(coll):
ev = coll.peek()
if ev:
@@ -1119,3 +1122,6 @@ def pn_event_category(event):
def pn_event_attachments(event):
return event.impl.attachments()
+
+def pn_event_copy(event):
+ return event.copy()
|
PROTON-<I>: Expose Event.copy() to bindings
A handler is not supposed to keep a reference to the event.
In proton-j this is more obviaous as collector clears events before returning them to the pool.
|
apache_qpid-proton
|
train
|
a2af7bb9280f2b52da0f8af3796fbe2e388025ff
|
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
index <HASH>..<HASH> 100644
--- a/activemodel/lib/active_model/dirty.rb
+++ b/activemodel/lib/active_model/dirty.rb
@@ -58,7 +58,7 @@ module ActiveModel
#
# A newly instantiated object is unchanged:
#
- # person = Person.new 'Uncle Bob'
+ # person = Person.new('Uncle Bob')
# person.changed? # => false
#
# Change the name:
|
use parentheses here, for the beard of the Prophet! [ci skip]
|
rails_rails
|
train
|
dbd5e191b1f07288aed45b15e8ef3e0a674f6f6b
|
diff --git a/conftest.py b/conftest.py
index <HASH>..<HASH> 100644
--- a/conftest.py
+++ b/conftest.py
@@ -24,4 +24,4 @@ def pygen_output_dir(cwd_module_dir):
sys.path.append(path)
yield path
sys.path.remove(path)
- #shutil.rmtree(path, ignore_errors=False)
+ shutil.rmtree(path, ignore_errors=False)
|
reactivated cleanup of code generated during test
|
moltob_pymultigen
|
train
|
7c15121f0b41b9c9f8881bbe9c8f4c7ada81acbf
|
diff --git a/spec/qu/instrumentation/log_subscriber_spec.rb b/spec/qu/instrumentation/log_subscriber_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/qu/instrumentation/log_subscriber_spec.rb
+++ b/spec/qu/instrumentation/log_subscriber_spec.rb
@@ -7,6 +7,7 @@ describe Qu::Instrumentation::LogSubscriber do
before(:each) do
Qu.backend = Qu::Backend::Redis.new
+ Qu.clear
@original_instrumenter = Qu.instrumenter
Qu.instrumenter = ActiveSupport::Notifications
described_class.logger = Logger.new(io).tap { |logger|
|
Ensure redis is clear for log subscriber spec.
|
bkeepers_qu
|
train
|
b9e6cd48ba0e6576c32a79ddeeedeb06d8bf5a25
|
diff --git a/cherry_picker/cherry_picker/cherry_picker.py b/cherry_picker/cherry_picker/cherry_picker.py
index <HASH>..<HASH> 100755
--- a/cherry_picker/cherry_picker/cherry_picker.py
+++ b/cherry_picker/cherry_picker/cherry_picker.py
@@ -191,7 +191,7 @@ To abort the cherry-pick and cleanup:
self.username, oauth_token=gh_auth)
title, body = normalize_commit_message(commit_message)
if not self.prefix_commit:
- title = f"[{base_branch}] title"
+ title = f"[{base_branch}] {title}"
data = {
"title": title,
"body": body,
|
cherry-picker: Fix PR title (GH-<I>)
|
python_core-workflow
|
train
|
53051ff77be071873358317118a6a55ec2ef34ba
|
diff --git a/src/SmscRuApi.php b/src/SmscRuApi.php
index <HASH>..<HASH> 100644
--- a/src/SmscRuApi.php
+++ b/src/SmscRuApi.php
@@ -54,7 +54,7 @@ class SmscRuApi
'fmt' => self::FORMAT_JSON,
];
- $params = array_merge($params, $base);
+ $params = array_merge($base, $params);
try {
$response = $this->httpClient->post($this->apiUrl, ['form_params' => $params]);
|
fix issues #<I> (#<I>)
|
laravel-notification-channels_smsc-ru
|
train
|
fafc4e500b5aeb95a266605887fe8913aececf3a
|
diff --git a/bigquery/setup.py b/bigquery/setup.py
index <HASH>..<HASH> 100644
--- a/bigquery/setup.py
+++ b/bigquery/setup.py
@@ -55,7 +55,7 @@ REQUIREMENTS = [
setup(
name='google-cloud-bigquery',
- version='0.22.0',
+ version='0.22.1',
description='Python Client for Google BigQuery',
long_description=README,
namespace_packages=[
diff --git a/language/setup.py b/language/setup.py
index <HASH>..<HASH> 100644
--- a/language/setup.py
+++ b/language/setup.py
@@ -55,7 +55,7 @@ REQUIREMENTS = [
setup(
name='google-cloud-language',
- version='0.22.0',
+ version='0.22.1',
description='Python Client for Google Cloud Natural Language',
long_description=README,
namespace_packages=[
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -50,14 +50,14 @@ SETUP_BASE = {
REQUIREMENTS = [
- 'google-cloud-bigquery >= 0.22.0, < 0.23dev',
+ 'google-cloud-bigquery >= 0.22.1, < 0.23dev',
'google-cloud-bigtable >= 0.22.0, < 0.23dev',
'google-cloud-happybase >= 0.22.0, < 0.23dev',
'google-cloud-core >= 0.22.1, < 0.23dev',
'google-cloud-datastore >= 0.22.0, < 0.23dev',
'google-cloud-dns >= 0.22.0, < 0.23dev',
'google-cloud-error-reporting >= 0.22.0, < 0.23dev',
- 'google-cloud-language >= 0.22.0, < 0.23dev',
+ 'google-cloud-language >= 0.22.1, < 0.23dev',
'google-cloud-logging >= 0.22.0, < 0.23dev',
'google-cloud-monitoring >= 0.22.0, < 0.23dev',
'google-cloud-pubsub >= 0.22.0, < 0.23dev',
|
Making sub-minor updates to libraries already on <I>.x
|
googleapis_google-cloud-python
|
train
|
889f835f399b09928ebb1963c33986430caef314
|
diff --git a/src/ORM/Association/ExternalAssociationTrait.php b/src/ORM/Association/ExternalAssociationTrait.php
index <HASH>..<HASH> 100644
--- a/src/ORM/Association/ExternalAssociationTrait.php
+++ b/src/ORM/Association/ExternalAssociationTrait.php
@@ -96,10 +96,11 @@ trait ExternalAssociationTrait {
public function transformRow($row) {
$sourceAlias = $this->source()->alias();
$targetAlias = $this->target()->alias();
- $values = $row[$this->_name];
- if (isset($values[$this->_name]) && is_array($values[$this->_name])) {
- $values = $values[$this->_name];
+ if (isset($row[$this->_name . '___collection_'])) {
+ $values = $row[$this->_name . '___collection_'];
+ } else {
+ $values = $row[$this->_name];
}
$row[$sourceAlias][$this->property()] = $values;
@@ -164,7 +165,7 @@ trait ExternalAssociationTrait {
$sourceKeys[] = key($fetchQuery->aliasField($key, $sAlias));
}
- $nestKey = $tAlias . '__' . $tAlias;
+ $nestKey = $tAlias . '___collection_';
if (count($sourceKeys) > 1) {
return $this->_multiKeysInjector($resultMap, $sourceKeys, $nestKey);
diff --git a/src/ORM/ResultSet.php b/src/ORM/ResultSet.php
index <HASH>..<HASH> 100644
--- a/src/ORM/ResultSet.php
+++ b/src/ORM/ResultSet.php
@@ -305,7 +305,8 @@ class ResultSet implements Countable, Iterator, Serializable, JsonSerializable {
$map = [];
$visitor = function($level) use (&$visitor, &$map) {
foreach ($level as $assoc => $meta) {
- $map[$assoc] = [
+ $map[$meta['aliasPath']] = [
+ 'alias' => $assoc,
'instance' => $meta['instance'],
'canBeJoined' => $meta['canBeJoined'],
'entityClass' => $meta['instance']->target()->entityClass()
@@ -350,6 +351,11 @@ class ResultSet implements Countable, Iterator, Serializable, JsonSerializable {
$table = $defaultAlias;
$field = $key;
+ if (strpos($key, '___collection_') !== false) {
+ $results[$key] = $value;
+ continue;
+ }
+
if (empty($this->_map[$key])) {
$parts = explode('__', $key);
if (count($parts) > 1) {
@@ -377,21 +383,27 @@ class ResultSet implements Countable, Iterator, Serializable, JsonSerializable {
'markNew' => false,
'guard' => false
];
- foreach (array_reverse($this->_associationMap) as $alias => $assoc) {
- if (!isset($results[$alias])) {
+ foreach (array_reverse($this->_associationMap) as $assoc) {
+ $alias = $assoc['alias'];
+ if (!isset($results[$alias]) && !isset($results[$alias . '___collection_'])) {
continue;
}
+
$instance = $assoc['instance'];
$target = $instance->target();
- $results[$alias] = $this->_castValues($target, $results[$alias]);
- unset($presentAliases[$alias]);
$options['source'] = $target->alias();
+ unset($presentAliases[$alias]);
+
+ if ($assoc['canBeJoined']) {
+ $results[$alias] = $this->_castValues($target, $results[$alias]);
+ }
if ($this->_hydrate && $assoc['canBeJoined']) {
$entity = new $assoc['entityClass']($results[$alias], $options);
$entity->clean();
$results[$alias] = $entity;
}
+
$results = $instance->transformRow($results);
}
diff --git a/tests/TestCase/ORM/QueryTest.php b/tests/TestCase/ORM/QueryTest.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase/ORM/QueryTest.php
+++ b/tests/TestCase/ORM/QueryTest.php
@@ -1867,4 +1867,13 @@ class QueryTest extends TestCase {
$this->assertSame($expected, $results);
}
+ public function testRepeatedAssociationAliases() {
+ $table = TableRegistry::get('ArticlesTags');
+ $table->belongsTo('Articles');
+ $table->belongsTo('Tags');
+ TableRegistry::get('Tags')->belongsToMany('Articles');
+ $results = $table->find()->contain(['Articles', 'Tags.Articles'])->hydrate(false)->toArray();
+ debug($results);
+ }
+
}
|
Changing the way eager loaded values are nested under each result.
The old way was making ResultSet confused about hydrating results having
the same association alias in the associaitons map
|
cakephp_cakephp
|
train
|
3997f3431f479475f92dab1612abe2f99a0ab8d7
|
diff --git a/cli/compose/convert/service.go b/cli/compose/convert/service.go
index <HASH>..<HASH> 100644
--- a/cli/compose/convert/service.go
+++ b/cli/compose/convert/service.go
@@ -616,11 +616,21 @@ func convertDeployMode(mode string, replicas *uint64) (swarm.ServiceMode, error)
serviceMode := swarm.ServiceMode{}
switch mode {
+ case "global-job":
+ if replicas != nil {
+ return serviceMode, errors.Errorf("replicas can only be used with replicated or replicated-job mode")
+ }
+ serviceMode.GlobalJob = &swarm.GlobalJob{}
case "global":
if replicas != nil {
- return serviceMode, errors.Errorf("replicas can only be used with replicated mode")
+ return serviceMode, errors.Errorf("replicas can only be used with replicated or replicated-job mode")
}
serviceMode.Global = &swarm.GlobalService{}
+ case "replicated-job":
+ serviceMode.ReplicatedJob = &swarm.ReplicatedJob{
+ MaxConcurrent: replicas,
+ TotalCompletions: replicas,
+ }
case "replicated", "":
serviceMode.Replicated = &swarm.ReplicatedService{Replicas: replicas}
default:
|
Added Swarm Job support to Stack Deploy
Added the support for both `global-job` and `replicated-job` to Docker
stack deploy.
|
docker_cli
|
train
|
f9a8a1b45a01a91f8773ca344b2153d3ba038afc
|
diff --git a/src/main/java/com/shapesecurity/functional/data/ImmutableSet.java b/src/main/java/com/shapesecurity/functional/data/ImmutableSet.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/shapesecurity/functional/data/ImmutableSet.java
+++ b/src/main/java/com/shapesecurity/functional/data/ImmutableSet.java
@@ -37,6 +37,21 @@ public class ImmutableSet<T> implements Iterable<T> {
return new ImmutableSet<>(HashTable.emptyUsingIdentity());
}
+ @Nonnull
+ public static <T> ImmutableSet<T> from(@Nonnull Hasher<T> hasher, @Nonnull Iterable<T> set) {
+ return empty(hasher).union(set);
+ }
+
+ @Nonnull
+ public static <T> ImmutableSet<T> fromUsingEquality(@Nonnull Iterable<T> set) {
+ return ImmutableSet.<T>emptyUsingEquality().union(set);
+ }
+
+ @Nonnull
+ public static <T> ImmutableSet<T> fromUsingIdentity(@Nonnull Iterable<T> set) {
+ return ImmutableSet.<T>emptyUsingIdentity().union(set);
+ }
+
@Deprecated
@Nonnull
public static <T> ImmutableSet<T> empty() {
@@ -84,6 +99,15 @@ public class ImmutableSet<T> implements Iterable<T> {
return new ImmutableSet<>(this.data.merge(other.data));
}
+ @Nonnull
+ public ImmutableSet<T> union(@Nonnull Iterable<T> other) {
+ ImmutableSet<T> set = this;
+ for (T entry : other) {
+ set = set.put(entry);
+ }
+ return set;
+ }
+
// Does not guarantee ordering of elements in resulting list.
@Nonnull
public ImmutableList<T> toList() {
diff --git a/src/test/java/com/shapesecurity/functional/data/ImmutableSetTest.java b/src/test/java/com/shapesecurity/functional/data/ImmutableSetTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/shapesecurity/functional/data/ImmutableSetTest.java
+++ b/src/test/java/com/shapesecurity/functional/data/ImmutableSetTest.java
@@ -18,11 +18,16 @@ package com.shapesecurity.functional.data;
import com.shapesecurity.functional.Pair;
import com.shapesecurity.functional.TestBase;
-import com.shapesecurity.functional.Unit;
import org.junit.Test;
import javax.annotation.Nonnull;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
import static org.junit.Assert.*;
public class ImmutableSetTest extends TestBase {
@@ -107,4 +112,23 @@ public class ImmutableSetTest extends TestBase {
assertTrue(m.contains(2));
assertFalse(m.contains(3));
}
+
+ @Test
+ public void mutableUnionTest() {
+ ImmutableSet<String> expected = ImmutableSet.<String>emptyUsingEquality()
+ .put("key1")
+ .put("key2")
+ .put("key3");
+ Set<String> set = new HashSet<>();
+ set.add("key1");
+ set.add("key2");
+ set.add("key3");
+ ImmutableSet<String> table = ImmutableSet.fromUsingEquality(set);
+ assertEquals(expected, table);
+ ImmutableSet<String> doubledSet = table.union(set);
+ assertEquals(table, doubledSet);
+ set.add("key4");
+ expected = expected.put("key4");
+ assertEquals(expected, table.union(set));
+ }
}
|
ImmutableSet::union and ImmutableSet::from (#<I>)
|
shapesecurity_shape-functional-java
|
train
|
e298692eeeffbe143fdda771e01145996a488ce5
|
diff --git a/formats/code.js b/formats/code.js
index <HASH>..<HASH> 100644
--- a/formats/code.js
+++ b/formats/code.js
@@ -14,12 +14,10 @@ class CodeBlockContainer extends Container {
}
html(index, length) {
- let text = this.domNode.innerText;
- // TODO find more robust solution for <select> turning into \n
- if (text.startsWith('\n')) {
- text = text.slice(1);
- }
- text = text.slice(index, index + length);
+ const text = this.children
+ .map(child => child.domNode.innerText)
+ .join('\n')
+ .slice(index, index + length);
return `<pre>${escapeText(text)}</pre>`;
}
}
|
better code block to html conversion
also fixes firefox including <select> in innerText
|
quilljs_quill
|
train
|
aee39c15217fe64830eb52f54539ed997938ff26
|
diff --git a/lib/ui/src/core/context.js b/lib/ui/src/core/context.js
index <HASH>..<HASH> 100644
--- a/lib/ui/src/core/context.js
+++ b/lib/ui/src/core/context.js
@@ -89,6 +89,10 @@ export class Provider extends Component {
api.on(SET_STORIES, data => {
api.setStories(data.stories);
+
+ const options = api.getParameters(storyId, 'options');
+
+ api.setOptions(options);
});
api.on(SELECT_STORY, ({ kind, story, ...rest }) => {
api.selectStory(kind, story, rest);
|
FIX setting of options when stories load
|
storybooks_storybook
|
train
|
3fd0c69789c5d3896e50a76cbc6975347bde81ef
|
diff --git a/core-bundle/contao/classes/Hybrid.php b/core-bundle/contao/classes/Hybrid.php
index <HASH>..<HASH> 100644
--- a/core-bundle/contao/classes/Hybrid.php
+++ b/core-bundle/contao/classes/Hybrid.php
@@ -189,7 +189,7 @@ abstract class Hybrid extends \Frontend
*/
public function generate()
{
- if ($this->objParent instanceof \ContentModel && !BE_USER_LOGGED_IN && ($this->objParent->invisible || ($this->objParent->start > 0 && $this->objParent->start > time()) || ($this->objParent->stop > 0 && $this->objParent->stop < time())))
+ if ($this->objParent instanceof \ContentModel && TL_MODE == 'FE' && !BE_USER_LOGGED_IN && ($this->objParent->invisible || ($this->objParent->start > 0 && $this->objParent->start > time()) || ($this->objParent->stop > 0 && $this->objParent->stop < time())))
{
return '';
}
diff --git a/core-bundle/contao/elements/ContentElement.php b/core-bundle/contao/elements/ContentElement.php
index <HASH>..<HASH> 100644
--- a/core-bundle/contao/elements/ContentElement.php
+++ b/core-bundle/contao/elements/ContentElement.php
@@ -130,7 +130,7 @@ abstract class ContentElement extends \Frontend
*/
public function generate()
{
- if (!BE_USER_LOGGED_IN && ($this->invisible || ($this->start > 0 && $this->start > time()) || ($this->stop > 0 && $this->stop < time())))
+ if (TL_MODE == 'FE' && !BE_USER_LOGGED_IN && ($this->invisible || ($this->start > 0 && $this->start > time()) || ($this->stop > 0 && $this->stop < time())))
{
return '';
}
diff --git a/core-bundle/contao/elements/ContentModule.php b/core-bundle/contao/elements/ContentModule.php
index <HASH>..<HASH> 100644
--- a/core-bundle/contao/elements/ContentModule.php
+++ b/core-bundle/contao/elements/ContentModule.php
@@ -34,7 +34,7 @@ class ContentModule extends \ContentElement
*/
public function generate()
{
- if (!BE_USER_LOGGED_IN && ($this->invisible || ($this->start > 0 && $this->start > time()) || ($this->stop > 0 && $this->stop < time())))
+ if (TL_MODE == 'FE' && !BE_USER_LOGGED_IN && ($this->invisible || ($this->start > 0 && $this->start > time()) || ($this->stop > 0 && $this->stop < time())))
{
return '';
}
|
[Core] Show invisible elements in the back end preview (see #<I>)
|
contao_contao
|
train
|
d9627657ab2fdc4a7f737541476a938005f69968
|
diff --git a/jbpm-workitems/src/main/java/org/jbpm/process/workitem/rest/RESTWorkItemHandler.java b/jbpm-workitems/src/main/java/org/jbpm/process/workitem/rest/RESTWorkItemHandler.java
index <HASH>..<HASH> 100644
--- a/jbpm-workitems/src/main/java/org/jbpm/process/workitem/rest/RESTWorkItemHandler.java
+++ b/jbpm-workitems/src/main/java/org/jbpm/process/workitem/rest/RESTWorkItemHandler.java
@@ -326,7 +326,7 @@ public class RESTWorkItemHandler extends AbstractLogOrThrowWorkItemHandler {
results.put("Result", resultObject);
} catch (Throwable e) {
- throw new RuntimeException("Unable to transform respose to object", e);
+ throw new RuntimeException("Unable to transform response to object", e);
}
} else {
|
JBPM-<I> - Typo in Runtime Exception Message (#<I>)
|
kiegroup_jbpm
|
train
|
78a26d366c7c61171df9abb7dd9c2653ab42072c
|
diff --git a/config/module.config.php b/config/module.config.php
index <HASH>..<HASH> 100644
--- a/config/module.config.php
+++ b/config/module.config.php
@@ -603,7 +603,7 @@ return array(
'rcm-page-search' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => array(
- 'route' => '/rcm-page-search',
+ 'route' => '/rcm-page-search[/:language]',
'defaults' => array(
'controller' => 'rcmPageSearchApiController',
'action' => 'allSitePages',
|
Complete refactor of the product wizard.
|
reliv_Rcm
|
train
|
0379f3155660c093e9f4633da9175e0251ae1b71
|
diff --git a/lxd/device/nic_bridged.go b/lxd/device/nic_bridged.go
index <HASH>..<HASH> 100644
--- a/lxd/device/nic_bridged.go
+++ b/lxd/device/nic_bridged.go
@@ -1414,6 +1414,8 @@ func (d *nicBridged) State() (*api.InstanceStateNetwork, error) {
ips = append(ips, newIP)
}
+ hwAddr, _ := net.ParseMAC(d.config["hwaddr"])
+
if d.network != nil {
// Extract subnet sizes from bridge addresses if available.
netConfig := d.network.Config()
@@ -1442,8 +1444,7 @@ func (d *nicBridged) State() (*api.InstanceStateNetwork, error) {
if !shared.IsTrue(d.network.Config()["ipv6.dhcp.stateful"]) && v6subnet != nil {
// If stateful DHCPv6 is disabled, and IPv6 is enabled on the bridge, the the NIC
// is likely to use its MAC and SLAAC to configure its address.
- hwAddr, err := net.ParseMAC(d.config["hwaddr"])
- if err == nil {
+ if hwAddr != nil {
ip, err := eui64.ParseMAC(v6subnet.IP, hwAddr)
if err == nil {
ipStore(ip)
@@ -1454,25 +1455,25 @@ func (d *nicBridged) State() (*api.InstanceStateNetwork, error) {
}
// Get IP addresses from IP neighbour cache if present.
- neighIPs, err := network.GetNeighbourIPs(d.config["parent"], d.config["hwaddr"])
+ neighIPs, err := network.GetNeighbourIPs(d.config["parent"], hwAddr)
if err == nil {
validStates := []string{
- string(network.NeighbourIPStatePermanent),
- string(network.NeighbourIPStateNoARP),
- string(network.NeighbourIPStateReachable),
+ string(ip.NeighbourIPStatePermanent),
+ string(ip.NeighbourIPStateNoARP),
+ string(ip.NeighbourIPStateReachable),
}
// Add any valid-state neighbour IP entries first.
for _, neighIP := range neighIPs {
if shared.StringInSlice(string(neighIP.State), validStates) {
- ipStore(neighIP.IP)
+ ipStore(neighIP.Addr)
}
}
// Add any non-failed-state entries.
for _, neighIP := range neighIPs {
- if neighIP.State != network.NeighbourIPStateFailed && !shared.StringInSlice(string(neighIP.State), validStates) {
- ipStore(neighIP.IP)
+ if neighIP.State != ip.NeighbourIPStateFailed && !shared.StringInSlice(string(neighIP.State), validStates) {
+ ipStore(neighIP.Addr)
}
}
}
|
lxd/device/nic/bridged: Updated network.GetNeighbourIPs and ip package constant usage
|
lxc_lxd
|
train
|
38faa0204d0839c76865a82c627555cbdee63408
|
diff --git a/Annis-Web/src/main/webapp/javascript/annis/windowSearch.js b/Annis-Web/src/main/webapp/javascript/annis/windowSearch.js
index <HASH>..<HASH> 100644
--- a/Annis-Web/src/main/webapp/javascript/annis/windowSearch.js
+++ b/Annis-Web/src/main/webapp/javascript/annis/windowSearch.js
@@ -740,6 +740,7 @@ Ext.onReady(function()
type : 'hbox'
},
fieldLabel : 'Search',
+ labelStyle : 'display : none;',
xtype : 'textfield',
items : [ searchResultButton, btnQueryBuilder ]
});
|
added display : none to labelStyle
|
korpling_ANNIS
|
train
|
b09a1e2634d86ddc6418aadff5a41e8658ee2749
|
diff --git a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java
index <HASH>..<HASH> 100644
--- a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java
+++ b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java
@@ -4,7 +4,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
-abstract class MultiKeyPipelineBase extends PipelineBase implements
+public abstract class MultiKeyPipelineBase extends PipelineBase implements
BasicRedisPipeline, MultiKeyBinaryRedisPipeline,
MultiKeyCommandsPipeline, ClusterPipeline {
diff --git a/src/main/java/redis/clients/jedis/PipelineBase.java b/src/main/java/redis/clients/jedis/PipelineBase.java
index <HASH>..<HASH> 100644
--- a/src/main/java/redis/clients/jedis/PipelineBase.java
+++ b/src/main/java/redis/clients/jedis/PipelineBase.java
@@ -8,7 +8,7 @@ import java.util.Set;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
-abstract class PipelineBase extends Queable implements BinaryRedisPipeline,
+public abstract class PipelineBase extends Queable implements BinaryRedisPipeline,
RedisPipeline {
protected abstract Client getClient(String key);
|
MultiKeyPipelineBase and PipelineBase made public in order to make Pipeline and transaction mockable with Mockito
|
xetorthio_jedis
|
train
|
0665333e8e1ed8e92ecc09e96a9e254b5b5fa720
|
diff --git a/i18n_subsites/i18n_subsites.py b/i18n_subsites/i18n_subsites.py
index <HASH>..<HASH> 100644
--- a/i18n_subsites/i18n_subsites.py
+++ b/i18n_subsites/i18n_subsites.py
@@ -74,6 +74,7 @@ def create_lang_subsites(pelican_obj):
pelican_obj = cls(settings)
logger.debug("Generating i18n subsite for lang '{}' using class '{}'".format(lang, str(cls)))
pelican_obj.run()
+ _main_site_generated = False # for autoreload mode
@@ -148,7 +149,8 @@ def install_templates_translations(generator):
generator.context['main_siteurl'] = _main_siteurl
generator.context['main_lang'] = _main_site_lang
extra_siteurls = { lang: _main_siteurl + '/' + lang for lang in generator.settings.get('I18N_SUBSITES', {}).keys() }
- extra_siteurls[_main_site_lang] = _main_siteurl
+ # To be able to use url for main site root when SITEURL == '' (e.g. when developing)
+ extra_siteurls[_main_site_lang] = '/' if _main_siteurl == '' else _main_siteurl
current_def_lang = generator.settings['DEFAULT_LANG']
extra_siteurls.pop(current_def_lang)
generator.context['extra_siteurls'] = extra_siteurls
@@ -158,7 +160,7 @@ def install_templates_translations(generator):
domain = generator.settings.get('I18N_GETTEXT_DOMAIN', 'messages')
localedir = generator.settings.get('I18N_GETTEXT_LOCALEDIR')
if localedir is None:
- localedir = os.path.join(generator.theme, 'translations/')
+ localedir = os.path.join(generator.theme, 'translations')
if current_def_lang == generator.settings.get('I18N_TEMPLATES_LANG', _main_site_lang):
translations = gettext.NullTranslations()
else:
|
i<I>n_subsites: improve develop server support
1. main site url root fix
2. support autoreload mode
Also removed trailing slash on dir name.
|
getpelican_pelican-plugins
|
train
|
6730f7d79c0b1a54ca49f45b226e1226d73210d7
|
diff --git a/modules/component/component.js b/modules/component/component.js
index <HASH>..<HASH> 100644
--- a/modules/component/component.js
+++ b/modules/component/component.js
@@ -33,7 +33,7 @@ export default class Component extends Container {
* @return {Path2D}
*/
makePath (ctx) {
- const path = new Path2D();
+ const path = new window.Path2D();
this.trace(path);
if (this.options.fill) {
@@ -74,7 +74,7 @@ export default class Component extends Container {
const relative = Position.from(positionDefinition).clone().subtract(this.position);
const rotated = relative.clone().rotate(-this.options.rotation, this.options.rotationAnchor);
- const path = new Path2D();
+ const path = new window.Path2D();
this.trace(path);
let result = (this.options.fill && ctx.isPointInPath(path, rotated.x, rotated.y)) ||
(this.options.stroke && this.options.strokeWidth && ctx.isPointInStroke(path, rotated.x, rotated.y));
diff --git a/modules/container/container.js b/modules/container/container.js
index <HASH>..<HASH> 100644
--- a/modules/container/container.js
+++ b/modules/container/container.js
@@ -228,7 +228,7 @@ export default class Container extends EventEmitter {
ctx.translate(this.position.x, this.position.y);
if (this.options.clip) {
- const clipping = new Path2D();
+ const clipping = new window.Path2D();
const clipper = this.options.clip === Container.ITSELF ? this : this.options.clip;
const { x, y } = clipper.position;
ctx.translate(x, y);
diff --git a/modules/path/path.js b/modules/path/path.js
index <HASH>..<HASH> 100644
--- a/modules/path/path.js
+++ b/modules/path/path.js
@@ -105,7 +105,7 @@ export default class Path extends Component {
instructions.forEach(instruction => lastPosition = instruction.execute(path, lastPosition));
}
else if (typeof instructions === "string") {
- const svg = new Path2D(`M0 0 ${instructions}${this.isClosed ? " Z" : ""}`);
+ const svg = new window.Path2D(`M0 0 ${instructions}${this.isClosed ? " Z" : ""}`);
path.addPath(svg);
}
diff --git a/modules/text/text.js b/modules/text/text.js
index <HASH>..<HASH> 100644
--- a/modules/text/text.js
+++ b/modules/text/text.js
@@ -245,7 +245,7 @@ export default class Text extends Component {
}
const name = url.replace(/\W/g, "-");
- const fontFace = new FontFace(name, `url(${url})`);
+ const fontFace = new window.FontFace(name, `url(${url})`);
window.document.fonts.add(fontFace);
return fontFace.load().then(() => name);
}
diff --git a/test/helpers/browser-env-setup.js b/test/helpers/browser-env-setup.js
index <HASH>..<HASH> 100644
--- a/test/helpers/browser-env-setup.js
+++ b/test/helpers/browser-env-setup.js
@@ -4,13 +4,13 @@ browserEnv(["window"], {
pretendToBeVisual: true,
});
-global.Path2D = class Path2D {
+window.Path2D = class Path2D {
rect () {}
};
window.document.fonts = new Set();
-global.FontFace = class FontFace {
+window.FontFace = class FontFace {
load () {
return new Promise((resolve) => {
setTimeout(resolve, 50);
|
:recycle: Refactoring code.
Prepend globals with "window"
|
pencil-js_pencil.js
|
train
|
b8be48be6f27dbac3571825b67e9779fe6765855
|
diff --git a/samcli/commands/local/lib/events.py b/samcli/commands/local/lib/events.py
index <HASH>..<HASH> 100644
--- a/samcli/commands/local/lib/events.py
+++ b/samcli/commands/local/lib/events.py
@@ -100,6 +100,7 @@ def generate_schedule_event(region):
:return dict: Dictionary representing the Schedule Event
"""
return {
+ "version": "0",
"account": "123456789012",
"region": region,
"detail": {},
diff --git a/tests/unit/commands/local/lib/test_events.py b/tests/unit/commands/local/lib/test_events.py
index <HASH>..<HASH> 100644
--- a/tests/unit/commands/local/lib/test_events.py
+++ b/tests/unit/commands/local/lib/test_events.py
@@ -242,10 +242,11 @@ class TestGeneratedEvent(TestCase):
self.assertEquals(actual_event, expected_event)
- def test_scheudle_event(self):
+ def test_schedule_event(self):
actual_event = generate_schedule_event("us-east-1")
expected_event = {
+ "version": "0",
"account": "123456789012",
"region": "us-east-1",
"detail": {},
|
add version field to schedule event generator; update test (#<I>)
undo bad format
|
awslabs_aws-sam-cli
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.