hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
d6d85d0666c50fb334936d8df60b9249945eb8e8 | diff --git a/spyder/app/tests/test_mainwindow.py b/spyder/app/tests/test_mainwindow.py
index <HASH>..<HASH> 100644
--- a/spyder/app/tests/test_mainwindow.py
+++ b/spyder/app/tests/test_mainwindow.py
@@ -2132,7 +2132,7 @@ def test_debug_unsaved_file(main_window, qtbot):
# There is a breakpoint, so it should continue
qtbot.waitUntil(
- lambda: shell._control.toPlainText().split()[-1] == 'continue')
+ lambda: 'ipdb> continue' in shell._control.toPlainText())
qtbot.waitUntil(
lambda: shell._control.toPlainText().split()[-1] == 'ipdb>') | Avoid test failing because of race condition
The next line could be shown earlier | spyder-ide_spyder | train |
7adcf42958f9f42e3e0243f8514aefa85bdf69a7 | diff --git a/lib/googleauth.rb b/lib/googleauth.rb
index <HASH>..<HASH> 100644
--- a/lib/googleauth.rb
+++ b/lib/googleauth.rb
@@ -34,7 +34,7 @@ module Google
# Module Auth provides classes that provide Google-specific authorization
# used to access Google APIs.
module Auth
- NOT_FOUND = <<END
+ NOT_FOUND_ERROR = <<END
Could not load the default credentials. Browse to
https://developers.google.com/accounts/docs/application-default-credentials
for more information
@@ -53,7 +53,7 @@ END
return creds unless creds.nil?
creds = ServiceAccountCredentials.from_well_known_path(scope)
return creds unless creds.nil?
- fail NOT_FOUND unless GCECredentials.on_gce?(options)
+ fail NOT_FOUND_ERROR unless GCECredentials.on_gce?(options)
GCECredentials.new
end
diff --git a/lib/googleauth/service_account.rb b/lib/googleauth/service_account.rb
index <HASH>..<HASH> 100644
--- a/lib/googleauth/service_account.rb
+++ b/lib/googleauth/service_account.rb
@@ -54,11 +54,11 @@ module Google
# cf [Application Default Credentials](http://goo.gl/mkAHpZ)
class ServiceAccountCredentials < Signet::OAuth2::Client
ENV_VAR = 'GOOGLE_APPLICATION_CREDENTIALS'
- NOT_FOUND_PREFIX =
+ NOT_FOUND_ERROR =
"Unable to read the credential file specified by #{ENV_VAR}"
TOKEN_CRED_URI = 'https://www.googleapis.com/oauth2/v3/token'
WELL_KNOWN_PATH = 'gcloud/application_default_credentials.json'
- WELL_KNOWN_PREFIX = 'Unable to read the default credential file'
+ WELL_KNOWN_ERROR = 'Unable to read the default credential file'
class << self
extend Memoist
@@ -79,7 +79,7 @@ module Google
fail 'file #{path} does not exist' unless File.exist?(path)
return new(scope, File.open(path))
rescue StandardError => e
- raise "#{NOT_FOUND_PREFIX}: #{e}"
+ raise "#{NOT_FOUND_ERROR}: #{e}"
end
# Creates an instance from a well known path.
@@ -94,7 +94,7 @@ module Google
return nil unless File.exist?(path)
return new(scope, File.open(path))
rescue StandardError => e
- raise "#{WELL_KNOWN_PREFIX}: #{e}"
+ raise "#{WELL_KNOWN_ERROR}: #{e}"
end
end | Renamed the error vars | googleapis_google-auth-library-ruby | train |
76dc4d57f6afe7e8e23cbcdab97fdc334c4395ae | diff --git a/mcubes/exporter.py b/mcubes/exporter.py
index <HASH>..<HASH> 100644
--- a/mcubes/exporter.py
+++ b/mcubes/exporter.py
@@ -15,20 +15,22 @@ def export_obj(vertices, triangles, filename):
for f in triangles:
fh.write("f {} {} {}\n".format(*(f + 1)))
+
def export_off(vertices, triangles, filename):
"""
Exports a mesh in the (.off) format.
"""
with open(filename, 'w') as fh:
- fh.write('OFF\n')
- fh.write('{} {} 0\n'.format(len(vertices), len(faces))
-
+ fh.write('OFF\n')
+ fh.write('{} {} 0\n'.format(len(vertices), len(triangles)))
+
for v in vertices:
fh.write("{} {} {}\n".format(*v))
for f in triangles:
- fh.write("3 {} {} {}\n".format(*(f)))
+ fh.write("3 {} {} {}\n".format(*f))
+
def export_mesh(vertices, triangles, filename, mesh_name="mcubes_mesh"):
""" | Fixed some error with the OFF exporter. | pmneila_PyMCubes | train |
43fde1145235981e59af8795ab8451d5346dcd44 | diff --git a/polyaxon/hpsearch/iteration_managers/hyperband.py b/polyaxon/hpsearch/iteration_managers/hyperband.py
index <HASH>..<HASH> 100644
--- a/polyaxon/hpsearch/iteration_managers/hyperband.py
+++ b/polyaxon/hpsearch/iteration_managers/hyperband.py
@@ -65,7 +65,7 @@ class HyperbandIterationManager(BaseIterationManager):
# Get the last group's experiments metrics
experiments_metrics = self.experiment_group.iteration_config.experiments_metrics
- if not experiments_metrics:
+ if experiments_metrics is None:
raise ExperimentGroupException()
# Order the experiments | Update hyperband handling of non experiment_metrics | polyaxon_polyaxon | train |
64a614f2a9853b648e4e6063860863593f75f317 | diff --git a/txaws/ec2/client.py b/txaws/ec2/client.py
index <HASH>..<HASH> 100644
--- a/txaws/ec2/client.py
+++ b/txaws/ec2/client.py
@@ -212,7 +212,7 @@ class EC2Client(object):
@param name: Name of the new security group.
@param description: Description of the new security group.
- @return: A C{Deferred} that will fire with a turth value for the
+ @return: A C{Deferred} that will fire with a truth value for the
success of the operaion.
"""
group_names = None
@@ -229,7 +229,7 @@ class EC2Client(object):
def delete_security_group(self, name):
"""
@param name: Name of the new security group.
- @return: A C{Deferred} that will fire with a turth value for the
+ @return: A C{Deferred} that will fire with a truth value for the
success of the operaion.
"""
parameter = {"GroupName": name}
@@ -269,7 +269,7 @@ class EC2Client(object):
@param cidr_ip: CIDR IP range to authorize access to when operating on
a CIDR IP.
- @return: A C{Deferred} that will fire with a turth value for the
+ @return: A C{Deferred} that will fire with a truth value for the
success of the operaion.
"""
if source_group_name and source_group_owner_id:
@@ -353,7 +353,7 @@ class EC2Client(object):
@param cidr_ip: CIDR IP range to revoke access from when operating on
a CIDR IP.
- @return: A C{Deferred} that will fire with a turth value for the
+ @return: A C{Deferred} that will fire with a truth value for the
success of the operaion.
"""
if source_group_name and source_group_owner_id: | Fixed typos (therve 2). | twisted_txaws | train |
5ebc164f37ee42e253d676bc6d1914eb694d531f | diff --git a/lxd/daemon.go b/lxd/daemon.go
index <HASH>..<HASH> 100644
--- a/lxd/daemon.go
+++ b/lxd/daemon.go
@@ -355,7 +355,7 @@ func (d *Daemon) createCmd(version string, c Command) {
})
}
-func (d *Daemon) SetupStorageDriver() error {
+func (d *Daemon) SetupStorageDriver(forceCheck bool) error {
pools, err := dbStoragePools(d.db)
if err != nil {
if err == NoSuchObjectError {
@@ -372,7 +372,7 @@ func (d *Daemon) SetupStorageDriver() error {
// looking at the patches db: If we already have a storage pool defined
// but the upgrade somehow got messed up then there will be no
// "storage_api" entry in the db.
- if len(pools) > 0 {
+ if len(pools) > 0 && !forceCheck {
appliedPatches, err := dbPatches(d.db)
if err != nil {
return err
@@ -870,7 +870,7 @@ func (d *Daemon) Init() error {
if !d.MockMode {
/* Read the storage pools */
- err = d.SetupStorageDriver()
+ err = d.SetupStorageDriver(false)
if err != nil {
return err
}
diff --git a/lxd/patches.go b/lxd/patches.go
index <HASH>..<HASH> 100644
--- a/lxd/patches.go
+++ b/lxd/patches.go
@@ -268,7 +268,7 @@ func patchStorageApi(name string, d *Daemon) error {
daemonConfig["storage.zfs_remove_snapshots"].Set(d, "")
daemonConfig["storage.zfs_use_refquota"].Set(d, "")
- return d.SetupStorageDriver()
+ return d.SetupStorageDriver(true)
}
func upgradeFromStorageTypeBtrfs(name string, d *Daemon, defaultPoolName string, defaultStorageTypeName string, cRegular []string, cSnapshots []string, imgPublic []string, imgPrivate []string) error { | {daemon,patches}: adapt SetupStorageDriver()
We need a way to force a check right at the end of the storage api upgrade. | lxc_lxd | train |
2d497004605291f300511768082e9bae34a70655 | diff --git a/registration/__init__.py b/registration/__init__.py
index <HASH>..<HASH> 100644
--- a/registration/__init__.py
+++ b/registration/__init__.py
@@ -8,5 +8,7 @@ def get_version():
version = '%s pre-alpha' % version
else:
if VERSION[3] != 'final':
- version = '%s %s %s' % (version, VERSION[3], VERSION[4])
+ version = "%s %s" % (version, VERSION[3])
+ if VERSION[4] != 0:
+ version = '%s %s' % (version, VERSION[4])
return version
diff --git a/registration/tests/__init__.py b/registration/tests/__init__.py
index <HASH>..<HASH> 100644
--- a/registration/tests/__init__.py
+++ b/registration/tests/__init__.py
@@ -1,4 +1,45 @@
+from django.test import TestCase
+
+import registration
+
from registration.tests.backends import *
from registration.tests.forms import *
from registration.tests.models import *
from registration.tests.views import *
+
+
+class RegistrationInfrastructureTests(TestCase):
+ """
+ Test django-registration's internal infrastructure, including
+ version information and backend retrieval.
+
+ """
+ def setUp(self):
+ self.version = registration.VERSION
+
+ def tearDown(self):
+ registration.VERSION = self.version
+
+ def test_get_version(self):
+ """
+ Test the version-info reporting.
+
+ """
+ versions = [
+ {'version': (1, 0, 0, 'alpha', 0),
+ 'expected': "1.0 pre-alpha"},
+ {'version': (1, 0, 1, 'alpha', 1),
+ 'expected': "1.0.1 alpha 1"},
+ {'version': (1, 1, 0, 'beta', 2),
+ 'expected': "1.1 beta 2"},
+ {'version': (1, 2, 1, 'rc', 3),
+ 'expected': "1.2.1 rc 3"},
+ {'version': (1, 3, 0, 'final', 0),
+ 'expected': "1.3"},
+ {'version': (1, 4, 1, 'beta', 0),
+ 'expected': "1.4.1 beta"},
+ ]
+
+ for version_dict in versions:
+ registration.VERSION = version_dict['version']
+ self.assertEqual(registration.get_version(), version_dict['expected']) | Unit tests for version-retrieval, plus a bugfix they uncovered. | ubernostrum_django-registration | train |
2e27e87fee768ea36aeb9186b2647f2808bf5c6f | diff --git a/modules/modules.go b/modules/modules.go
index <HASH>..<HASH> 100644
--- a/modules/modules.go
+++ b/modules/modules.go
@@ -58,7 +58,7 @@ type Chain struct {
}
var (
- config = "/tmp/beehive.conf"
+ config = "./beehive.conf"
EventsIn = make(chan Event)
@@ -146,13 +146,11 @@ func GetModule(identifier string) *ModuleInterface {
// Loads chains from config
func LoadChains() {
j, err := ioutil.ReadFile(config)
- if err != nil {
- log.Println("Couldn't read config from:", config)
- }
-
- err = json.Unmarshal(j, &chains)
- if err != nil {
- panic(err)
+ if err == nil {
+ err = json.Unmarshal(j, &chains)
+ if err != nil {
+ panic(err)
+ }
}
}
@@ -163,7 +161,7 @@ func SaveChains() {
panic(err)
}
- err = ioutil.WriteFile("/tmp/beehive.conf", j, 0644)
+ err = ioutil.WriteFile(config, j, 0644)
}
func FakeChain() { | * Don't bail when config doesn't exist. | muesli_beehive | train |
109d7bf837191c51159bac2dcf49fd607f7884b0 | diff --git a/tests/test_MicroTokenizer.py b/tests/test_MicroTokenizer.py
index <HASH>..<HASH> 100644
--- a/tests/test_MicroTokenizer.py
+++ b/tests/test_MicroTokenizer.py
@@ -7,7 +7,6 @@ import pytest
from click.testing import CliRunner
-from MicroTokenizer import MicroTokenizer
from MicroTokenizer import cli | Bugfix: remove useless and wrong import statement | howl-anderson_MicroTokenizer | train |
ae341d725c169ed6ec08218f754c41cc511f29ce | diff --git a/lib/dm-core/associations.rb b/lib/dm-core/associations.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-core/associations.rb
+++ b/lib/dm-core/associations.rb
@@ -167,7 +167,7 @@ module DataMapper
end
end # module Associations
- Resource.append_extensions DataMapper::Associations
+ Resource::ClassMethods.append_extensions DataMapper::Associations
# module Resource
# module ClassMethods
diff --git a/lib/dm-core/hook.rb b/lib/dm-core/hook.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-core/hook.rb
+++ b/lib/dm-core/hook.rb
@@ -238,5 +238,5 @@ module DataMapper
end # module Hook
- DataMapper::Resource.append_extensions Hook
+ DataMapper::Resource::ClassMethods.append_extensions Hook
end # module DataMapper | Changed Associations and Hook to add themselves using Resource::ClassMethods.append_extensions | datamapper_dm-core | train |
05612d76b6b0fd7fdfd825fa554932e5822d8170 | diff --git a/test/e2e/framework/ingress/ingress_utils.go b/test/e2e/framework/ingress/ingress_utils.go
index <HASH>..<HASH> 100644
--- a/test/e2e/framework/ingress/ingress_utils.go
+++ b/test/e2e/framework/ingress/ingress_utils.go
@@ -38,7 +38,7 @@ import (
"k8s.io/klog"
apps "k8s.io/api/apps/v1"
- "k8s.io/api/core/v1"
+ v1 "k8s.io/api/core/v1"
extensions "k8s.io/api/extensions/v1beta1"
apierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -301,7 +301,7 @@ func GenerateRSACerts(host string, isCA bool) ([]byte, []byte, error) {
return nil, nil, fmt.Errorf("Failed creating cert: %v", err)
}
if err := pem.Encode(&keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil {
- return nil, nil, fmt.Errorf("Failed creating keay: %v", err)
+ return nil, nil, fmt.Errorf("Failed creating key: %v", err)
}
return certOut.Bytes(), keyOut.Bytes(), nil
}
@@ -871,7 +871,7 @@ func generateBacksideHTTPSIngressSpec(ns string) *extensions.Ingress {
Namespace: ns,
},
Spec: extensions.IngressSpec{
- // Note kubemci requres a default backend.
+ // Note kubemci requires a default backend.
Backend: &extensions.IngressBackend{
ServiceName: "echoheaders-https",
ServicePort: intstr.IntOrString{ | small cleanup of e2e/framework/ingress | kubernetes_kubernetes | train |
167f67e8ba9b77b94d91a7990988888a9d560ad4 | diff --git a/lib/deployml/configuration.rb b/lib/deployml/configuration.rb
index <HASH>..<HASH> 100644
--- a/lib/deployml/configuration.rb
+++ b/lib/deployml/configuration.rb
@@ -36,6 +36,9 @@ module DeploYML
# The ORM used by the project
attr_reader :orm
+ # The environment to run the project in
+ attr_reader :environment
+
# Specifies whether to enable debugging.
attr_accessor :debug
@@ -63,6 +66,9 @@ module DeploYML
# @option config [Symbol] :orm
# The ORM used by the project.
#
+ # @option config [Symbol] :environment
+ # The environment to run the project in.
+ #
# @option config [Boolean] :debug (false)
# Specifies whether to enable debugging.
#
@@ -70,13 +76,36 @@ module DeploYML
# The `server` option Hash did not contain a `name` option.
#
def initialize(config={})
- config = normalize_hash(config)
+ @scm = DEFAULT_SCM
- @scm = (config[:scm] || DEFAULT_SCM).to_sym
+ @source = nil
+ @dest = nil
+ @exclude = Set[]
@server_name = nil
@server_options = {}
+ @framework = nil
+ @orm = nil
+
+ @environment = nil
+ @debug = false
+
+ config = normalize_hash(config)
+
+ if config[:framework]
+ @framework = config[:framework].to_sym
+
+ case @framework
+ when :rails2, :rails3
+ @environment = :production
+ end
+ end
+
+ if config[:orm]
+ @orm = config[:orm].to_sym
+ end
+
case config[:server]
when Symbol, String
@server_name = config[:server].to_sym
@@ -94,27 +123,24 @@ module DeploYML
end
end
+ if config[:scm]
+ @scm = config[:scm].to_sym
+ end
+
@source = config[:source]
@dest = config[:dest]
- @exclude = Set[]
-
if config[:exclude]
@exclude += [*config[:exclude]]
end
- @framework = nil
- @orm = nil
-
- if config[:framework]
- @framework = config[:framework].to_sym
+ if config[:environment]
+ @environment = config[:environment].to_sym
end
- if config[:orm]
- @orm = config[:orm].to_sym
+ if config[:debug]
+ @debug = config[:debug]
end
-
- @debug = (config[:debug] || false)
end
protected | Added Configuration#environment.
* Default it to :production when using the rails2 or rails3 frameworks. | postmodern_deployml | train |
905090d86da427194123e088c2ab3c64157be2c1 | diff --git a/lib/heroku/commands/ps.rb b/lib/heroku/commands/ps.rb
index <HASH>..<HASH> 100644
--- a/lib/heroku/commands/ps.rb
+++ b/lib/heroku/commands/ps.rb
@@ -8,23 +8,21 @@ module Heroku::Command
output << "------- ------------ -------------------------- ---------- ---------"
ps.each do |p|
- since = time_ago(p['transitioned_at'])
output << "%-7s %-12s %-26s %-10s %-9s" %
- [p['upid'], p['slug'], truncate(p['command'], 22), p['state'], since]
+ [p['upid'], p['slug'], truncate(p['command'], 22), p['state'], time_ago(p['elapsed'])]
end
display output.join("\n")
end
private
- def time_ago(time)
- duration = Time.now - Time.parse(time)
- if duration < 60
- "#{duration.floor}s ago"
- elsif duration < (60 * 60)
- "#{(duration / 60).floor}m ago"
+ def time_ago(elapsed)
+ if elapsed < 60
+ "#{elapsed.floor}s ago"
+ elsif elapsed < (60 * 60)
+ "#{(elapsed / 60).floor}m ago"
else
- "#{(duration / 60 / 60).floor}h ago"
+ "#{(elapsed / 60 / 60).floor}h ago"
end
end
diff --git a/spec/commands/ps_spec.rb b/spec/commands/ps_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/commands/ps_spec.rb
+++ b/spec/commands/ps_spec.rb
@@ -8,7 +8,7 @@ module Heroku::Command
it "lists processes" do
@cli.heroku.should_receive(:ps).and_return([
- { 'command' => 'rake', 'transitioned_at' => Time.now.to_s }
+ { 'command' => 'rake', 'elapsed' => 3 }
])
@cli.index
end | use server-provided elapsed time | heroku_legacy-cli | train |
2c882cfdd487a9e2f57b839e3abf795638d46269 | diff --git a/views/js/uiForm.js b/views/js/uiForm.js
index <HASH>..<HASH> 100644
--- a/views/js/uiForm.js
+++ b/views/js/uiForm.js
@@ -89,7 +89,8 @@ define([
$translator = $container.find('.form-translator'),
$authoringBtn = $('.authoringOpener'),
$authoringBtnParent,
- $testAuthoringBtn = $('.test-authoring');
+ $testAuthoringBtn = $('.test-authoring'),
+ $rdfImportForm = $('.rdfImport #import');
// move authoring button to toolbar
if($authoringBtn.length) {
@@ -110,6 +111,19 @@ define([
$testAuthoringBtn.prependTo($toolBar);
}
+ // import Ontology styling changes
+ if($rdfImportForm.length) {
+ $('span.form_desc:empty',$rdfImportForm).hide();
+ $('span.form-elt-info',$rdfImportForm).css({
+ display: 'block',
+ width: '100%'
+ });
+ $('.form-elt-container.file-uploader',$rdfImportForm).css({
+ width: '65%',
+ float: 'right'
+ });
+
+ }
// modify properties
postRenderProps.init(); | Some quick fix to the import form. Need to be refactored. | oat-sa_tao-core | train |
051c56ceeea2af796332608e3b4c05473bca43ac | diff --git a/lib/memoist.rb b/lib/memoist.rb
index <HASH>..<HASH> 100644
--- a/lib/memoist.rb
+++ b/lib/memoist.rb
@@ -31,7 +31,7 @@ module Memoist
end
def self.extract_reload!(method, args)
- if args.length == method.arity + 1 && (args.last == true || args.last == :reload)
+ if args.length == method.arity.abs + 1 && (args.last == true || args.last == :reload)
reload = args.pop
end
reload
diff --git a/test/memoist_test.rb b/test/memoist_test.rb
index <HASH>..<HASH> 100644
--- a/test/memoist_test.rb
+++ b/test/memoist_test.rb
@@ -70,6 +70,26 @@ class MemoistTest < Minitest::Unit::TestCase
memoize :name, :age
+ def sleep(hours = 8)
+ @counter.call(:sleep)
+ hours
+ end
+ memoize :sleep
+
+ def sleep_calls
+ @counter.count(:sleep)
+ end
+
+ def update_attributes(options = {})
+ @counter.call(:update_attributes)
+ true
+ end
+ memoize :update_attributes
+
+ def update_attributes_calls
+ @counter.count(:update_attributes)
+ end
+
protected
def memoize_protected_test
@@ -167,6 +187,28 @@ class MemoistTest < Minitest::Unit::TestCase
assert_equal 1, @person.name_calls
end
+ def test_memoize_with_optional_arguments
+ assert_equal 4, @person.sleep(4)
+ assert_equal 1, @person.sleep_calls
+
+ 3.times { assert_equal 4, @person.sleep(4) }
+ assert_equal 1, @person.sleep_calls
+
+ 3.times { assert_equal 4, @person.sleep(4, :reload) }
+ assert_equal 4, @person.sleep_calls
+ end
+
+ def test_memoize_with_options_hash
+ assert_equal true, @person.update_attributes(:age => 21, :name => 'James')
+ assert_equal 1, @person.update_attributes_calls
+
+ 3.times { assert_equal true, @person.update_attributes(:age => 21, :name => 'James') }
+ assert_equal 1, @person.update_attributes_calls
+
+ 3.times { assert_equal true, @person.update_attributes({:age => 21, :name => 'James'}, :reload) }
+ assert_equal 4, @person.update_attributes_calls
+ end
+
def test_memoization_with_punctuation
assert_equal true, @person.name? | Call abs on arity when extracting reload
* Optional arguments in the method signature cause arity to be a
negative number. Call abs on the method arity to fix option values not
working and throwing something like:
ArgumentError: wrong number of arguments (3 for 2) | matthewrudy_memoist | train |
0009a0345480b96886ac9aec19d36ae23d14f5b6 | diff --git a/issue.py b/issue.py
index <HASH>..<HASH> 100755
--- a/issue.py
+++ b/issue.py
@@ -65,7 +65,9 @@ def list_issues(flags, tag):
print(str(issue["number"]).ljust(lens["number"] + padding), end='')
print(issue["tag"].ljust(lens["tag"] + padding), end='')
print(issue["date"].ljust(lens["date"] + padding), end='')
- print(issue["description"].ljust(lens["description"] + padding), end='')
+ desc = issue["description"].ljust(lens["description"])
+ desc = desc.splitlines()[0]
+ print(desc, end='')
print()
def edit_issue(number, message="", tag="", close=False, reopen=False): | Only print first line of each issue on issue listing | boarpig_issue | train |
1bd2a13de853da2015d2038ac7df9961a39b2bed | diff --git a/src/MultipartStream.php b/src/MultipartStream.php
index <HASH>..<HASH> 100644
--- a/src/MultipartStream.php
+++ b/src/MultipartStream.php
@@ -113,7 +113,7 @@ class MultipartStream implements StreamInterface
// Set a default content-disposition header if one was no provided
$disposition = $this->getHeader($headers, 'content-disposition');
if (!$disposition) {
- $headers['Content-Disposition'] = $filename
+ $headers['Content-Disposition'] = ($filename === '0' || $filename)
? sprintf('form-data; name="%s"; filename="%s"',
$name,
basename($filename))
@@ -130,7 +130,7 @@ class MultipartStream implements StreamInterface
// Set a default Content-Type if one was not supplied
$type = $this->getHeader($headers, 'content-type');
- if (!$type && $filename) {
+ if (!$type && ($filename === '0' || $filename)) {
if ($type = mimetype_from_filename($filename)) {
$headers['Content-Type'] = $type;
} | Accept "0" as a valid filename for multipart form file uploads | guzzle_psr7 | train |
ba77abe07cb77bbe44614c89b3fdbe13e7503c93 | diff --git a/internal/pipe/snapcraft/snapcraft.go b/internal/pipe/snapcraft/snapcraft.go
index <HASH>..<HASH> 100644
--- a/internal/pipe/snapcraft/snapcraft.go
+++ b/internal/pipe/snapcraft/snapcraft.go
@@ -175,6 +175,7 @@ func create(ctx *context.Context, arch string, binaries []artifact.Artifact) err
}
var snap = filepath.Join(ctx.Config.Dist, folder+".snap")
+ log.WithField("snap", snap).Info("creating")
/* #nosec */
var cmd = exec.CommandContext(ctx, "snapcraft", "pack", primeDir, "--output", snap)
if out, err = cmd.CombinedOutput(); err != nil { | chore: make output less verbose | goreleaser_goreleaser | train |
9bc9a8167a4d8b7529143d1a26c32c66cdace666 | diff --git a/luigi/contrib/bigquery.py b/luigi/contrib/bigquery.py
index <HASH>..<HASH> 100644
--- a/luigi/contrib/bigquery.py
+++ b/luigi/contrib/bigquery.py
@@ -466,6 +466,12 @@ class BigqueryRunQueryTask(MixinBigqueryBulkComplete, luigi.Task):
return CreateDisposition.CREATE_IF_NEEDED
@property
+ def flatten_results(self):
+ """Flattens all nested and repeated fields in the query results.
+ allowLargeResults must be true if this is set to False."""
+ return True
+
+ @property
def query(self):
"""The query, in text form."""
raise NotImplementedError()
@@ -502,6 +508,7 @@ class BigqueryRunQueryTask(MixinBigqueryBulkComplete, luigi.Task):
'allowLargeResults': True,
'createDisposition': self.create_disposition,
'writeDisposition': self.write_disposition,
+ 'flattenResults': self.flatten_results
}
}
} | allow for use of BigQuery's flatten results flag | spotify_luigi | train |
56e046a971353b2ed2a73fe7b45b4630609ad3ed | diff --git a/test/test_config.py b/test/test_config.py
index <HASH>..<HASH> 100644
--- a/test/test_config.py
+++ b/test/test_config.py
@@ -10,12 +10,22 @@ from khard import config
class LoadingConfigFile(unittest.TestCase):
+ _patch1 = None
+ _patch2 = None
+
@classmethod
def setUpClass(cls):
- # Clear the environment.
- for varname in ["EDITOR", "MERGE_EDITOR", "XDG_CONFIG_HOME"]:
- if varname in os.environ:
- del os.environ[varname]
+ # Mock the environment.
+ cls._patch1 = mock.patch('os.environ', {})
+ # Use a mock to "find" executables in the mocked environment.
+ cls._patch2 = mock.patch('khard.config.find_executable', lambda x: x)
+ cls._patch1.start()
+ cls._patch2.start()
+
+ @classmethod
+ def tearDownClass(cls):
+ cls._patch1.stop()
+ cls._patch2.stop()
def test_load_non_existing_file_fails(self):
filename = "I hope this file never exists" | Patch the environment in tests instead of modifying it | scheibler_khard | train |
660ced9578790e70a34aa07c85f9c852611e21ee | diff --git a/affinity/src/main/java/net/openhft/affinity/impl/OSXJNAAffinity.java b/affinity/src/main/java/net/openhft/affinity/impl/OSXJNAAffinity.java
index <HASH>..<HASH> 100644
--- a/affinity/src/main/java/net/openhft/affinity/impl/OSXJNAAffinity.java
+++ b/affinity/src/main/java/net/openhft/affinity/impl/OSXJNAAffinity.java
@@ -61,7 +61,7 @@ public enum OSXJNAAffinity implements IAffinity {
public int getThreadId() {
int tid = CLibrary.INSTANCE.pthread_self();
//The tid must be an unsigned 16 bit
- int tid_24 = tid & 0xFFFFFF;
+ int tid_24 = tid & 0xFFFF;
return tid_24;
} | The thread id must be contained in a <I> bit unsigned int. | OpenHFT_Java-Thread-Affinity | train |
ec550bc49fac0087fecd417fcf171a35ce9eb354 | diff --git a/ember-cli-build.js b/ember-cli-build.js
index <HASH>..<HASH> 100644
--- a/ember-cli-build.js
+++ b/ember-cli-build.js
@@ -10,6 +10,11 @@ module.exports = function(defaults) {
minifyCSS: {
enabled: false // CSS minification w/ @import rules seems to be broken in Ember-CLI 3.3
+ },
+
+ sourcemaps: {
+ enabled: true,
+ extensions: ['js']
}
}); | Compile sourcemaps for demo site to hopefully catch future regressions | sir-dunxalot_ember-tooltips | train |
a56c70a3534382b358c5d756a60445466b9c5e1d | diff --git a/plugins/item_tasks/plugin_tests/tasksSpec.js b/plugins/item_tasks/plugin_tests/tasksSpec.js
index <HASH>..<HASH> 100644
--- a/plugins/item_tasks/plugin_tests/tasksSpec.js
+++ b/plugins/item_tasks/plugin_tests/tasksSpec.js
@@ -286,7 +286,7 @@ describe('Navigate to the new JSON task', function () {
describe('Run task on item from item view', function () {
it('navigate to collections', function () {
runs(function () {
- $('ul.g-global-nav .g-nav-link[g-target="collections"]').click();
+ $('.g-global-nav .g-nav-link[g-target="collections"]').click();
});
waitsFor(function () {
diff --git a/plugins/item_tasks/web_client/main.js b/plugins/item_tasks/web_client/main.js
index <HASH>..<HASH> 100644
--- a/plugins/item_tasks/web_client/main.js
+++ b/plugins/item_tasks/web_client/main.js
@@ -65,7 +65,7 @@ ItemView.prototype.events['click .g-configure-item-task'] = function () {
// "Select Task" button in Actions drop down menu
import SelectSingleFileTaskWidget from './views/SelectSingleFileTaskWidget';
-ItemView.prototype.events['click a.g-select-item-task'] = function (e) {
+ItemView.prototype.events['click .g-select-item-task'] = function (e) {
new SelectSingleFileTaskWidget({
el: $('#g-dialog-container'),
parentView: this,
diff --git a/plugins/item_tasks/web_client/stylesheets/selectTaskWidget.styl b/plugins/item_tasks/web_client/stylesheets/selectTaskWidget.styl
index <HASH>..<HASH> 100644
--- a/plugins/item_tasks/web_client/stylesheets/selectTaskWidget.styl
+++ b/plugins/item_tasks/web_client/stylesheets/selectTaskWidget.styl
@@ -1,16 +1,4 @@
-.g-task-custom-target-container
- margin-bottom 8px
-
- .g-target-result
- padding 5px 10px
- background-color #eee
- border-radius 3px
- margin-bottom 6px
-
.g-selected-task
color #555
- position relative
- display block
padding 10px 15px
- background-color #fff
border 1px solid #ddd | Clean up stylus and selectors | girder_girder | train |
1392a12816c0ab3f9e97ccb08eccd682be0acfe4 | diff --git a/src/Rezzza/AliceExtension/Symfony/ContainerProxy.php b/src/Rezzza/AliceExtension/Symfony/ContainerProxy.php
index <HASH>..<HASH> 100644
--- a/src/Rezzza/AliceExtension/Symfony/ContainerProxy.php
+++ b/src/Rezzza/AliceExtension/Symfony/ContainerProxy.php
@@ -2,9 +2,10 @@
namespace Rezzza\AliceExtension\Symfony;
+use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\KernelInterface;
-class ContainerProxy
+class ContainerProxy implements ContainerInterface
{
private $container;
@@ -13,7 +14,7 @@ class ContainerProxy
$this->container = $kernel->getContainer();
}
- public function get($id)
+ public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE);
{
return $this->container->get($id);
}
@@ -27,4 +28,44 @@ class ContainerProxy
{
return $this->container->has($id);
}
+
+ public function set($id, $service, $scope = self::SCOPE_CONTAINER)
+ {
+ throw new \Exception('Unsupported method');
+ }
+
+ public function hasParameter($name)
+ {
+ throw new \Exception('Unsupported method');
+ }
+
+ public function setParameter($name, $value)
+ {
+ throw new \Exception('Unsupported method');
+ }
+
+ public function enterScope($name)
+ {
+ throw new \Exception('Unsupported method');
+ }
+
+ public function leaveScope($name)
+ {
+ throw new \Exception('Unsupported method');
+ }
+
+ public function addScope(ScopeInterface $scope)
+ {
+ throw new \Exception('Unsupported method');
+ }
+
+ public function hasScope($name)
+ {
+ throw new \Exception('Unsupported method');
+ }
+
+ public function isScopeActive($name)
+ {
+ throw new \Exception('Unsupported method');
+ }
} | ContainerProxy should implements ContainerInterface | rezzza_alice-extension | train |
be885d9f6522c2f9401532de6e1885bf678c702e | diff --git a/storage/inchi/src/main/java/org/openscience/cdk/inchi/InChIGenerator.java b/storage/inchi/src/main/java/org/openscience/cdk/inchi/InChIGenerator.java
index <HASH>..<HASH> 100644
--- a/storage/inchi/src/main/java/org/openscience/cdk/inchi/InChIGenerator.java
+++ b/storage/inchi/src/main/java/org/openscience/cdk/inchi/InChIGenerator.java
@@ -204,14 +204,6 @@ public class InChIGenerator {
}
}
- // Process atoms
- IsotopeFactory ifact = null;
- try {
- ifact = Isotopes.getInstance();
- } catch (Exception e) {
- // Do nothing
- }
-
Map<IAtom, JniInchiAtom> atomMap = new HashMap<IAtom, JniInchiAtom>();
atoms = atomContainer.atoms().iterator();
while (atoms.hasNext()) {
@@ -251,14 +243,7 @@ public class InChIGenerator {
// Check whether isotopic
Integer isotopeNumber = atom.getMassNumber();
- if (isotopeNumber != CDKConstants.UNSET && ifact != null) {
- IAtom isotope = atomContainer.getBuilder().newInstance(IAtom.class, el);
- ifact.configure(isotope);
- if (isotope.getMassNumber().intValue() == isotopeNumber.intValue()) {
- isotopeNumber = 0;
- }
- }
- if (isotopeNumber != CDKConstants.UNSET) {
+ if (isotopeNumber != null) {
iatom.setIsotopicMass(isotopeNumber);
}
diff --git a/storage/inchi/src/test/java/org/openscience/cdk/inchi/InChIGeneratorFactoryTest.java b/storage/inchi/src/test/java/org/openscience/cdk/inchi/InChIGeneratorFactoryTest.java
index <HASH>..<HASH> 100644
--- a/storage/inchi/src/test/java/org/openscience/cdk/inchi/InChIGeneratorFactoryTest.java
+++ b/storage/inchi/src/test/java/org/openscience/cdk/inchi/InChIGeneratorFactoryTest.java
@@ -20,7 +20,11 @@
*/
package org.openscience.cdk.inchi;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
@@ -28,11 +32,13 @@ import java.util.List;
import org.openscience.cdk.Atom;
import org.openscience.cdk.AtomContainer;
+import org.openscience.cdk.CDK;
import org.openscience.cdk.DefaultChemObjectBuilder;
import org.openscience.cdk.aromaticity.Aromaticity;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.interfaces.IAtom;
import org.openscience.cdk.interfaces.IAtomContainer;
+import org.openscience.cdk.silent.SilentChemObjectBuilder;
import org.openscience.cdk.smiles.SmilesParser;
import org.openscience.cdk.templates.TestMoleculeFactory;
import org.openscience.cdk.tools.manipulator.AtomContainerManipulator;
@@ -168,6 +174,16 @@ public class InChIGeneratorFactoryTest {
}
+ @Test
+ public void dontIgnoreMajorIsotopes() throws CDKException {
+ SmilesParser smipar = new SmilesParser(SilentChemObjectBuilder.getInstance());
+ InChIGeneratorFactory inchifact = InChIGeneratorFactory.getInstance();
+ assertThat(inchifact.getInChIGenerator(smipar.parseSmiles("[12CH4]")).getInchi(),
+ containsString("/i"));
+ assertThat(inchifact.getInChIGenerator(smipar.parseSmiles("C")).getInchi(),
+ not(containsString("/i")));
+ }
+
/**
* Tests the aromatic bonds option in the InChI factory class.
*/ | Don't ignore major isotopes in InChI generation. If a user want's to remove or add major isotopes by default they can still do this. | cdk_cdk | train |
21ce5a6425c98db0cd125ac0e040ea8eff756048 | diff --git a/src/bundles/Session/CCSession.php b/src/bundles/Session/CCSession.php
index <HASH>..<HASH> 100644
--- a/src/bundles/Session/CCSession.php
+++ b/src/bundles/Session/CCSession.php
@@ -36,6 +36,19 @@ class CCSession
}
/**
+ * Get a value from the session and remove it afterwards
+ *
+ * @param string $key
+ * @param string $default
+ * @param string $manager
+ * @return Session\Manager
+ */
+ public static function once( $key, $default, $manager = null )
+ {
+ return Manager::create( $manager )->once( $key, $default );
+ }
+
+ /**
* Set a value on the session
*
* @param string $key
@@ -49,6 +62,20 @@ class CCSession
}
/**
+ * Similar to add but forces the element to be an array
+ * and appends an item.
+ *
+ * @param string $key
+ * @param string $value
+ * @param string $manager
+ * @return Session\Manager
+ */
+ public static function add( $key, $value, $manager = null )
+ {
+ return Manager::create( $manager )->add( $key, $value );
+ }
+
+ /**
* Has a value on the session
*
* @param string $key
diff --git a/src/bundles/Session/Manager.php b/src/bundles/Session/Manager.php
index <HASH>..<HASH> 100644
--- a/src/bundles/Session/Manager.php
+++ b/src/bundles/Session/Manager.php
@@ -224,6 +224,20 @@ class Manager extends \CCDataObject
}
/**
+ * Get a value from data and remove it afterwards
+ *
+ * @param string $key
+ * @param mixed $default
+ * @return mixed
+ */
+ public function once( $key, $default = null )
+ {
+ $value = \CCArr::get( $key, $this->_data, $default );
+ \CCArr::delete( $key, $this->_data );
+ return $value;
+ }
+
+ /**
* Read data from the session driver. This overwrite's
* any changes made on runtime.
*
diff --git a/src/classes/CCArr.php b/src/classes/CCArr.php
index <HASH>..<HASH> 100755
--- a/src/classes/CCArr.php
+++ b/src/classes/CCArr.php
@@ -64,6 +64,35 @@ class CCArr
}
/**
+ * Adds an item to an element in the array
+ *
+ * Example:
+ * CCArr::add( 'foo.bar', 'test' );
+ *
+ * Results:
+ * array( 'foo' => array( 'bar' => array( 'test' ) ) )
+ *
+ * @param string $key
+ * @param mixed $item The item you would like to add to the array
+ * @param array $array
+ * @return array
+ */
+ public static function add( $key, $item, &$arr )
+ {
+ if( !is_array( $arr ) )
+ {
+ throw new \InvalidArgumentException('CCArr::add - second argument has to be an array.');
+ }
+
+ if ( !is_array( static::get( $key, $arr ) ) )
+ {
+ return static::set( $key, array( $item ), $arr );
+ }
+
+ return static::set( $key, static::push( $item, static::get( $key, $arr ) ), $arr );
+ }
+
+ /**
* get a special item from every array
*
* @param mixed $key
@@ -339,7 +368,7 @@ class CCArr
* @param string $key
* @param mixed $value
* @param array $arr
- * @return void
+ * @return array
*/
public static function set( $key, $value, &$arr )
{
@@ -375,6 +404,7 @@ class CCArr
break;
}
}
+ return $arr;
}
/**
diff --git a/src/classes/CCDataObject.php b/src/classes/CCDataObject.php
index <HASH>..<HASH> 100755
--- a/src/classes/CCDataObject.php
+++ b/src/classes/CCDataObject.php
@@ -46,6 +46,19 @@ class CCDataObject
}
/**
+ * Add data to the object
+ *
+ * @param string $key
+ * @param mixed $value
+ *
+ * @return void
+ */
+ public function add( $key, $value )
+ {
+ CCArr::add( $key, $value, $this->_data );
+ }
+
+ /**
* gets data, use a default if not set.
*
* @param string $key
diff --git a/tests/Core/CCArr.php b/tests/Core/CCArr.php
index <HASH>..<HASH> 100755
--- a/tests/Core/CCArr.php
+++ b/tests/Core/CCArr.php
@@ -76,6 +76,23 @@ class Test_CCArr extends \PHPUnit_Framework_TestCase
$this->assertEquals( 5, count( $array ) );
}
+
+ /**
+ * test array add
+ */
+ public function testArrayAdd()
+ {
+ $array = array( 'foo' => array( 'bar' => array( 'test' => 'woo' ) ) );
+
+ $array = CCArr::add( 'foo.bar.test', 'jep', $array );
+
+ $this->assertEquals( array( 'jep' ), CCArr::get( 'foo.bar.test', $array ) );
+
+ $array = CCArr::add( 'foo.bar.test', 'jepp', $array );
+
+ $this->assertEquals( array( 'jep', 'jepp' ), CCArr::get( 'foo.bar.test', $array ) );
+ }
+
/**
* test array push
* | Added once and add functionality
CCArr now support add
CCSession support now once and add | ClanCats_Core | train |
1bf25dc1b2f1f7aca81aedb422f524ad077f8808 | diff --git a/notifier/notifier_test.go b/notifier/notifier_test.go
index <HASH>..<HASH> 100644
--- a/notifier/notifier_test.go
+++ b/notifier/notifier_test.go
@@ -442,7 +442,7 @@ func TestLabelSetNotReused(t *testing.T) {
func makeInputTargetGroup() *config.TargetGroup {
return &config.TargetGroup{
Targets: []model.LabelSet{
- model.LabelSet{
+ {
model.AddressLabel: model.LabelValue("1.1.1.1:9090"),
model.LabelName("notcommon1"): model.LabelValue("label"),
},
diff --git a/util/testutil/roundtrip.go b/util/testutil/roundtrip.go
index <HASH>..<HASH> 100644
--- a/util/testutil/roundtrip.go
+++ b/util/testutil/roundtrip.go
@@ -37,7 +37,7 @@ func (rt *roundTripCheckRequest) RoundTrip(r *http.Request) (*http.Response, err
}
// NewRoundTripCheckRequest creates a new instance of a type that implements http.RoundTripper,
-// wich before returning theResponse and theError, executes checkRequest against a http.Request.
+// which before returning theResponse and theError, executes checkRequest against a http.Request.
func NewRoundTripCheckRequest(checkRequest func(*http.Request), theResponse *http.Response, theError error) http.RoundTripper {
return &roundTripCheckRequest{
checkRequest: checkRequest, | fix issues reported by gofmt and spelling typo (#<I>) | prometheus_prometheus | train |
ff618b94b852ec15ed7510c7dead50c360c299da | diff --git a/lib/nuggets/util/pluggable.rb b/lib/nuggets/util/pluggable.rb
index <HASH>..<HASH> 100644
--- a/lib/nuggets/util/pluggable.rb
+++ b/lib/nuggets/util/pluggable.rb
@@ -25,57 +25,68 @@
###############################################################################
#++
+require 'set'
+
module Util
module Pluggable
- class << self
-
- def load_plugins_for(*klasses)
- klasses.map { |klass| klass.extend(self).load_plugins }
- end
+ def self.load_plugins_for(*klasses)
+ klasses.map { |klass| klass.extend(self).load_plugins }
+ end
- def extended(base)
- base.plugin_filename ||= "#{base.name.
- gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
- gsub(/([a-z\d])([A-Z])/, '\1_\2').
- gsub(/::/, '/').tr('-', '_').downcase}_plugin.rb"
- end
+ def load_plugins(name = plugin_filename)
+ load_path_plugins(name)
+ load_gem_plugins(name)
+ load_env_plugins(name)
+ loaded_plugins.to_a
end
- attr_accessor :plugin_filename
+ def loaded_plugins
+ @loaded_plugins ||= Set.new
+ end
- def load_plugins
- plugins, name = [], plugin_filename
- plugins.concat(load_env_plugins(name))
- plugins.concat(load_gem_plugins(name)) if defined?(::Gem)
- plugins
+ def plugin_filename
+ @plugin_filename ||= "#{name.
+ gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').
+ gsub(/([a-z\d])([A-Z])/, '\1_\2').
+ gsub(/::/, '/').tr('-', '_').downcase}_plugin.rb"
end
+ attr_writer :plugin_filename
+
private
- def load_env_plugins(name)
- load_plugin_files($LOAD_PATH.map { |path|
+ def load_path_plugins(name)
+ $LOAD_PATH.dup.each { |path|
plugin = ::File.expand_path(name, path)
- plugin if ::File.file?(plugin)
- }.compact)
+ load_plugin_file(plugin) if ::File.file?(plugin)
+ }
end
def load_gem_plugins(name)
- load_plugin_files(::Gem::Specification.map { |spec|
- spec.matches_for_glob(name)
- }.flatten)
+ ::Gem::Specification.latest_specs.each { |spec|
+ load_plugin_files(spec.matches_for_glob(name))
+ } if ::Object.const_defined?(:Gem)
+ end
+
+ def load_env_plugins(name)
+ path = ::ENV["#{name.chomp(ext = ::File.extname(name)).upcase}_PATH"]
+ path.split(::File::PATH_SEPARATOR).each { |dir|
+ load_plugin_files(::Dir["#{dir}/*#{ext}"])
+ } if path
+ end
+
+ def load_plugin_file(plugin)
+ load plugin if loaded_plugins.add?(plugin)
+ rescue ::Exception => err
+ raise unless loaded_plugins.delete?(plugin)
+ warn "Error loading #{name} plugin: #{plugin}: #{err} (#{err.class})"
end
def load_plugin_files(plugins)
- plugins.each { |plugin|
- begin
- load plugin
- rescue ::Exception => err
- warn "Error loading #{name} plugin: #{plugin}: #{err} (#{err.class})"
- end
- }
+ plugins.each { |plugin| load_plugin_file(::File.expand_path(plugin)) }
end
end | lib/nuggets/util/pluggable.rb: Improved plugin loading.
* Only load each plugin once (if successful).
* Only load latest plugin versions from RubyGems.
* Allow to load plugins from user-defined locations. | blackwinter_nuggets | train |
e8c87f7cb36a339163d1e5af1336e4719d7c10df | diff --git a/cli/command/orchestrator.go b/cli/command/orchestrator.go
index <HASH>..<HASH> 100644
--- a/cli/command/orchestrator.go
+++ b/cli/command/orchestrator.go
@@ -2,6 +2,7 @@ package command
import (
"fmt"
+ "io"
"os"
)
@@ -19,6 +20,7 @@ const (
defaultOrchestrator = OrchestratorSwarm
envVarDockerStackOrchestrator = "DOCKER_STACK_ORCHESTRATOR"
+ envVarDockerOrchestrator = "DOCKER_ORCHESTRATOR"
)
// HasKubernetes returns true if defined orchestrator has Kubernetes capabilities.
@@ -53,13 +55,16 @@ func normalize(value string) (Orchestrator, error) {
// GetStackOrchestrator checks DOCKER_STACK_ORCHESTRATOR environment variable and configuration file
// orchestrator value and returns user defined Orchestrator.
-func GetStackOrchestrator(flagValue, value string) (Orchestrator, error) {
+func GetStackOrchestrator(flagValue, value string, stderr io.Writer) (Orchestrator, error) {
// Check flag
if o, err := normalize(flagValue); o != orchestratorUnset {
return o, err
}
// Check environment variable
env := os.Getenv(envVarDockerStackOrchestrator)
+ if env == "" && os.Getenv(envVarDockerOrchestrator) != "" {
+ fmt.Fprintf(stderr, "WARNING: experimental environment variable %s is set. Please use %s instead\n", envVarDockerOrchestrator, envVarDockerStackOrchestrator)
+ }
if o, err := normalize(env); o != orchestratorUnset {
return o, err
}
diff --git a/cli/command/orchestrator_test.go b/cli/command/orchestrator_test.go
index <HASH>..<HASH> 100644
--- a/cli/command/orchestrator_test.go
+++ b/cli/command/orchestrator_test.go
@@ -1,6 +1,7 @@
package command
import (
+ "io/ioutil"
"os"
"testing"
@@ -107,7 +108,7 @@ func TestOrchestratorSwitch(t *testing.T) {
err := cli.Initialize(options)
assert.NilError(t, err)
- orchestrator, err := GetStackOrchestrator(testcase.flagOrchestrator, cli.ConfigFile().StackOrchestrator)
+ orchestrator, err := GetStackOrchestrator(testcase.flagOrchestrator, cli.ConfigFile().StackOrchestrator, ioutil.Discard)
assert.NilError(t, err)
assert.Check(t, is.Equal(testcase.expectedKubernetes, orchestrator.HasKubernetes()))
assert.Check(t, is.Equal(testcase.expectedSwarm, orchestrator.HasSwarm()))
diff --git a/cli/command/stack/cmd.go b/cli/command/stack/cmd.go
index <HASH>..<HASH> 100644
--- a/cli/command/stack/cmd.go
+++ b/cli/command/stack/cmd.go
@@ -3,6 +3,7 @@ package stack
import (
"errors"
"fmt"
+ "io"
"strings"
"github.com/docker/cli/cli"
@@ -26,7 +27,7 @@ func NewStackCommand(dockerCli command.Cli) *cobra.Command {
Short: "Manage Docker stacks",
Args: cli.NoArgs,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
- orchestrator, err := getOrchestrator(dockerCli.ConfigFile(), cmd)
+ orchestrator, err := getOrchestrator(dockerCli.ConfigFile(), cmd, dockerCli.Err())
if err != nil {
return err
}
@@ -71,12 +72,12 @@ func NewTopLevelDeployCommand(dockerCli command.Cli) *cobra.Command {
return cmd
}
-func getOrchestrator(config *configfile.ConfigFile, cmd *cobra.Command) (command.Orchestrator, error) {
+func getOrchestrator(config *configfile.ConfigFile, cmd *cobra.Command, stderr io.Writer) (command.Orchestrator, error) {
var orchestratorFlag string
if o, err := cmd.Flags().GetString("orchestrator"); err == nil {
orchestratorFlag = o
}
- return command.GetStackOrchestrator(orchestratorFlag, config.StackOrchestrator)
+ return command.GetStackOrchestrator(orchestratorFlag, config.StackOrchestrator, stderr)
}
func hideOrchestrationFlags(cmd *cobra.Command, orchestrator command.Orchestrator) {
diff --git a/cli/command/system/version.go b/cli/command/system/version.go
index <HASH>..<HASH> 100644
--- a/cli/command/system/version.go
+++ b/cli/command/system/version.go
@@ -126,7 +126,7 @@ func runVersion(dockerCli command.Cli, opts *versionOptions) error {
return cli.StatusError{StatusCode: 64, Status: err.Error()}
}
- orchestrator, err := command.GetStackOrchestrator("", dockerCli.ConfigFile().StackOrchestrator)
+ orchestrator, err := command.GetStackOrchestrator("", dockerCli.ConfigFile().StackOrchestrator, dockerCli.Err())
if err != nil {
return cli.StatusError{StatusCode: 64, Status: err.Error()}
} | Warn if DOCKER_ORCHESTRATOR is still used but not DOCKER_STACK_ORCHESTRATOR | docker_cli | train |
79c36546916fa7ccec4e6da1d610b381ad14afb0 | diff --git a/lib/chai/utils/inspect.js b/lib/chai/utils/inspect.js
index <HASH>..<HASH> 100644
--- a/lib/chai/utils/inspect.js
+++ b/lib/chai/utils/inspect.js
@@ -79,8 +79,9 @@ function formatValue(ctx, value, recurseTimes) {
// Make functions say that they are functions
if (typeof value === 'function') {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
+ var name = getName(value);
+ var nameSuffix = name ? ': ' + name : '';
+ base = ' [Function' + nameSuffix + ']';
}
// Make RegExps say that they are RegExps | Use `utils.getName` for all function inspections.
This makes the `respondTo` tests pass in IE, where functions don't themselves have a `name` property. | chaijs_chai | train |
ca20a5f3bb18c78138dc17ee7b6b05c1a3094c20 | diff --git a/flake8_aaa/helpers.py b/flake8_aaa/helpers.py
index <HASH>..<HASH> 100644
--- a/flake8_aaa/helpers.py
+++ b/flake8_aaa/helpers.py
@@ -2,6 +2,9 @@ import ast
import py
+from flake8_aaa.exceptions import NotAMarker
+from flake8_aaa.marker import Marker
+
def is_test_file(filename):
"""
@@ -48,9 +51,16 @@ def load_markers(file_tokens):
file_tokens (list (tokenize.TokenInfo))
Returns:
- dict
+ dict: Key the dictionary using the starting line of the comment.
"""
- return {}
+ out = {}
+ for token in file_tokens:
+ try:
+ marker = Marker.build(token)
+ except NotAMarker:
+ continue
+ out[marker.token.start[0]] = marker
+ return out
def check_function(function_def):
diff --git a/tests/helpers/test_load_markers.py b/tests/helpers/test_load_markers.py
index <HASH>..<HASH> 100644
--- a/tests/helpers/test_load_markers.py
+++ b/tests/helpers/test_load_markers.py
@@ -32,5 +32,5 @@ def test():
def test_some(file_tokens):
result = load_markers(file_tokens)
- assert list(result) == [2]
- assert result[2].string == '# aaa act'
+ assert list(result) == [3]
+ assert result[3].token.string == '# aaa act' | Extend load_markers to load aaa comments | jamescooke_flake8-aaa | train |
4dbb2d23b5e2764826f33e4107d73d6fe81d6220 | diff --git a/lib/multi_git/tree/builder.rb b/lib/multi_git/tree/builder.rb
index <HASH>..<HASH> 100644
--- a/lib/multi_git/tree/builder.rb
+++ b/lib/multi_git/tree/builder.rb
@@ -10,6 +10,7 @@ module MultiGit
def initialize(from = nil, &block)
@entries = {}
+ instance_eval(&block) if block
end
def []=(key, options = {}, value)
@@ -19,9 +20,9 @@ module MultiGit
def >>(repository)
ent = []
- @entries.each do |name, (mode, content)|
- object = repository.put(content, Utils.type_from_mode(mode))
- ent << [name, mode, object.oid]
+ @entries.each do |name, entry|
+ object = repository.put(entry)
+ ent << [name, object.mode, object.oid]
end
return repository.make_tree(ent)
end
diff --git a/spec/shared.rb b/spec/shared.rb
index <HASH>..<HASH> 100644
--- a/spec/shared.rb
+++ b/spec/shared.rb
@@ -97,11 +97,18 @@ shared_examples "an empty repository" do
end
it "can add a Tree::Builder" do
- fb = MultiGit::File::Builder.new(nil, "a", "Blobs")
- result = repository.put(fb)
- result.should be_a(MultiGit::Object)
- result.name.should == 'a'
- result.oid.should == 'b4abd6f716fef3c1a4e69f37bd591d9e4c197a4a'
+ tb = MultiGit::Tree::Builder.new do
+ file "a", "b"
+ directory "c" do
+ file "d", "e"
+ end
+ end
+ result = repository.put(tb)
+ result.should be_a(MultiGit::Tree)
+ result['a'].should be_a(MultiGit::File)
+ result['c'].should be_a(MultiGit::Directory)
+ result['c/d'].should be_a(MultiGit::File)
+ result.oid.should == 'b490aa5179132fe8ea44df539cf8ede23d9cc5e2'
end
it "can read a previously added blob" do | inserting a MultiGit::Tree::Builder now works | hannesg_multi_git | train |
14cc18a91226e375d2aa776971e5a92e87ac83fb | diff --git a/src/toil/provisioners/abstractProvisioner.py b/src/toil/provisioners/abstractProvisioner.py
index <HASH>..<HASH> 100644
--- a/src/toil/provisioners/abstractProvisioner.py
+++ b/src/toil/provisioners/abstractProvisioner.py
@@ -330,7 +330,7 @@ coreos:
LEADER_DOCKER_ARGS = '--registry=in_memory --cluster={name}'
# --no-systemd_enable_support is necessary in Ubuntu 16.04 (otherwise,
# Mesos attempts to contact systemd but can't find its run file)
- WORKER_DOCKER_ARGS = '--work_dir=/var/lib/mesos --master={ip}:5050 --attributes=preemptable:{preemptable} --no-systemd_enable_support'
+ WORKER_DOCKER_ARGS = '--work_dir=/var/lib/mesos --master={ip}:5050 --attributes=preemptable:{preemptable} --no-hostname_lookup --no-systemd_enable_support'
def _getCloudConfigUserData(self, role, masterPublicKey=None, keyPath=None, preemptable=False):
if role == 'leader':
entryPoint = 'mesos-master' | Make ignoredNodes functionality actually work
The ignoredNodes functionality used to work on the basis of private
IPs, but the Mesos batch system checks against the ignoredNodes set on
the basis of hostnames. Except in very rare cases (when the
reverse-lookup that Mesos performs by default fails), those were
completely different values.
This patch forces Mesos workers to use the private IP when reporting
their "hostname". | DataBiosphere_toil | train |
2159c86940eba3a16341ae3953e41dcedbe0674f | diff --git a/src/com/google/javascript/jscomp/serialization/ScriptNodeDeserializer.java b/src/com/google/javascript/jscomp/serialization/ScriptNodeDeserializer.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/serialization/ScriptNodeDeserializer.java
+++ b/src/com/google/javascript/jscomp/serialization/ScriptNodeDeserializer.java
@@ -228,13 +228,14 @@ public final class ScriptNodeDeserializer {
case ASSIGN_COALESCE:
this.addScriptFeature(Feature.LOGICAL_ASSIGNMENT);
return;
- case FOR:
- if (node.isForOf()) {
- this.addScriptFeature(Feature.FOR_OF);
- } else if (node.isForAwaitOf()) {
- this.addScriptFeature(Feature.FOR_AWAIT_OF);
- }
+
+ case FOR_OF:
+ this.addScriptFeature(Feature.FOR_OF);
return;
+ case FOR_AWAIT_OF:
+ this.addScriptFeature(Feature.FOR_AWAIT_OF);
+ return;
+
case IMPORT:
case EXPORT:
this.addScriptFeature(Feature.MODULES);
diff --git a/test/com/google/javascript/jscomp/serialization/SerializeAndDeserializeAstTest.java b/test/com/google/javascript/jscomp/serialization/SerializeAndDeserializeAstTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/serialization/SerializeAndDeserializeAstTest.java
+++ b/test/com/google/javascript/jscomp/serialization/SerializeAndDeserializeAstTest.java
@@ -161,6 +161,16 @@ public final class SerializeAndDeserializeAstTest extends CompilerTestCase {
}
@Test
+ public void testForOfLoop() {
+ testSame("for (let elem of []);");
+ }
+
+ @Test
+ public void testForAwaitOfLoop() {
+ testSame("async function f() { for await (let elem of []); }");
+ }
+
+ @Test
public void testConstructorJsdoc() {
testSame("/** @constructor */ function Foo() {}");
} | Correctly add enhanced-for usages to the FeatureSet in TypedAST serialization
Fixes an issue where transpilation passes in stage 2 sometimes failed to transpile for-await-of loops, causing a compiler crash.
PiperOrigin-RevId: <I> | google_closure-compiler | train |
0496107a71f8d7cb518aca0e74f89ea8f2e26224 | diff --git a/core/ViewDataTable.php b/core/ViewDataTable.php
index <HASH>..<HASH> 100644
--- a/core/ViewDataTable.php
+++ b/core/ViewDataTable.php
@@ -534,7 +534,9 @@ class ViewDataTable
// default sort order to visits/visitors data
if (empty($this->viewProperties['filter_sort_column'])) {
- if ($haveNbUniqVisitors) {
+ if ($haveNbUniqVisitors
+ && in_array('nb_uniq_visitors', $this->viewProperties['columns_to_display'])
+ ) {
$this->viewProperties['filter_sort_column'] = 'nb_uniq_visitors';
} else {
$this->viewProperties['filter_sort_column'] = 'nb_visits'; | Fix regression in default sort column for some actions reports. | matomo-org_matomo | train |
9e4e8682dbe7dade0f34f254f7ddac3e3d5a27ce | diff --git a/openstack_dashboard/dashboards/settings/user/forms.py b/openstack_dashboard/dashboards/settings/user/forms.py
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/dashboards/settings/user/forms.py
+++ b/openstack_dashboard/dashboards/settings/user/forms.py
@@ -26,6 +26,12 @@ from horizon import forms
from horizon import messages
+def _one_year():
+ now = datetime.utcnow()
+ return datetime(now.year + 1, now.month, now.day, now.hour,
+ now.minute, now.second, now.microsecond, now.tzinfo)
+
+
class UserSettingsForm(forms.SelfHandlingForm):
language = forms.ChoiceField(label=_("Language"))
timezone = forms.ChoiceField(label=_("Timezone"))
@@ -71,14 +77,18 @@ class UserSettingsForm(forms.SelfHandlingForm):
if lang_code and translation.check_for_language(lang_code):
if hasattr(request, 'session'):
request.session['django_language'] = lang_code
- else:
- response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
+ response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
+ expires=_one_year())
# Timezone
request.session['django_timezone'] = pytz.timezone(
data['timezone']).zone
+ response.set_cookie('django_timezone', data['timezone'],
+ expires=_one_year())
request.session['horizon_pagesize'] = data['pagesize']
+ response.set_cookie('horizon_pagesize', data['pagesize'],
+ expires=_one_year())
messages.success(request, _("Settings saved."))
diff --git a/openstack_dashboard/dashboards/settings/user/views.py b/openstack_dashboard/dashboards/settings/user/views.py
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/dashboards/settings/user/views.py
+++ b/openstack_dashboard/dashboards/settings/user/views.py
@@ -25,11 +25,19 @@ class UserSettingsView(forms.ModalFormView):
template_name = 'settings/user/settings.html'
def get_initial(self):
- return {'language': self.request.LANGUAGE_CODE,
- 'timezone': self.request.session.get('django_timezone', 'UTC'),
+ return {'language': self.request.session.get(
+ settings.LANGUAGE_COOKIE_NAME,
+ self.request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME,
+ self.request.LANGUAGE_CODE)),
+ 'timezone': self.request.session.get(
+ 'django_timezone',
+ self.request.COOKIES.get('django_timezone', 'UTC')),
'pagesize': self.request.session.get(
'horizon_pagesize',
- getattr(settings, 'API_RESULT_PAGE_SIZE', 20))}
+ self.request.COOKIES.get(
+ 'horizon_pagesize',
+ getattr(settings,
+ 'API_RESULT_PAGE_SIZE', 20)))}
def form_valid(self, form):
return form.handle(self.request, form.cleaned_data)
diff --git a/openstack_dashboard/settings.py b/openstack_dashboard/settings.py
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/settings.py
+++ b/openstack_dashboard/settings.py
@@ -198,6 +198,7 @@ LANGUAGES = (
('zh-tw', gettext_noop('Traditional Chinese')),
)
LANGUAGE_CODE = 'en'
+LANGUAGE_COOKIE_NAME = 'horizon_language'
USE_I18N = True
USE_L10N = True
USE_TZ = True | Store user settings in persistent cookies as well as the session
This should keep international users from having to reset their
language preferences every time they login.
Fixes Bug: <I>
Change-Id: I<I>e7a<I>bf<I>b<I>ec4a<I>f<I>b<I>db4db | openstack_horizon | train |
82ba02ca33042030a899e795e516a1ec6b99aedd | diff --git a/spec/lib/files_spec.rb b/spec/lib/files_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/files_spec.rb
+++ b/spec/lib/files_spec.rb
@@ -275,15 +275,15 @@ describe '[Files]' do
describe '#remove_file_sharing_rights' do
it_should_behave_like 'an api request' do
- let(:command) { :remove_file_sharing_rights }
- let(:args) { [random_id(:new_file), [random_id(:user)]] }
+ let(:command) { :removes_sharing_rights }
+ let(:args) { [fileIds: [random_id(:new_file)]] }
end
end
describe '#remove_folder_sharing_rights' do
it_should_behave_like 'an api request' do
- let(:command) { :remove_folder_sharing_rights }
- let(:args) { [random_id(:new_folder), [random_id(:user)]] }
+ let(:command) { :removes_sharing_rights }
+ let(:args) { [folderIds: [random_id(:new_folder)]] }
end
end | Fix tests for removing sharing rights (#<I>) | ONLYOFFICE_onlyoffice_api_gem | train |
762d48f31b67beff9decea313cbd467c0cf4a699 | diff --git a/seleniumbase/fixtures/base_case.py b/seleniumbase/fixtures/base_case.py
index <HASH>..<HASH> 100755
--- a/seleniumbase/fixtures/base_case.py
+++ b/seleniumbase/fixtures/base_case.py
@@ -1811,6 +1811,7 @@ class BaseCase(unittest.TestCase):
* See https://github.com/SeleniumHQ/selenium/issues/1161
Based on the following Stack Overflow solution:
* https://stackoverflow.com/a/41150512/7058266 """
+ time.sleep(0.1) # May take a moment for errors to appear after loads.
try:
browser_logs = self.driver.get_log('browser')
except (ValueError, WebDriverException): | When checking for JS errors, give enough time for them to appear | seleniumbase_SeleniumBase | train |
4ff7bb6232d68953eb0a392a4bfd4f6d5f973d0e | diff --git a/src/Client/CurlFactory.php b/src/Client/CurlFactory.php
index <HASH>..<HASH> 100644
--- a/src/Client/CurlFactory.php
+++ b/src/Client/CurlFactory.php
@@ -76,24 +76,46 @@ class CurlFactory
$response['effective_url'] = $response['transfer_stats']['url'];
}
- if (isset($headers[0])) {
- $startLine = explode(' ', array_shift($headers), 3);
- // Trim out 100-Continue start-lines
- if ($startLine[1] == '100') {
- $startLine = explode(' ', array_shift($headers), 3);
- }
- $response['headers'] = Core::headersFromLines($headers);
+ if (!empty($headers)) {
+ list($startLine, $headerList) = self::parseHeaderOutput($headers);
+ $response['headers'] = $headerList;
$response['status'] = isset($startLine[1]) ? (int) $startLine[1] : null;
$response['reason'] = isset($startLine[2]) ? $startLine[2] : null;
$response['body'] = $body;
Core::rewindBody($response);
}
- return !empty($response['curl']['errno']) || !isset($startLine[1])
+ return !empty($response['curl']['errno']) || !isset($response['status'])
? self::createErrorResponse($handler, $request, $response)
: $response;
}
+ private static function parseHeaderOutput(array $lines)
+ {
+ // Curl returns one or more repeated lines in this format:
+ // 1. Start-Line
+ // 2. 1 or more Header lines
+ // 3. empty line
+ // So, we pop the last empty line (it might be the last or first).
+ array_pop($lines);
+ $startLine = '';
+ $headers = [];
+
+ // Pop lines off until the next empty line or the last line is popped.
+ while ($line = array_pop($lines)) {
+ if (substr($line, 0, 5) === 'HTTP/') {
+ $startLine = $line;
+ } else {
+ $parts = explode(':', $line, 2);
+ $headers[trim($parts[0])][] = isset($parts[1])
+ ? trim($parts[1])
+ : null;
+ }
+ }
+
+ return [explode(' ', $startLine, 3), array_reverse($headers)];
+ }
+
private static function createErrorResponse(
callable $handler,
array $request,
@@ -168,11 +190,8 @@ class CurlFactory
CURLOPT_HEADER => false,
CURLOPT_CONNECTTIMEOUT => 150,
CURLOPT_HEADERFUNCTION => function ($ch, $h) use (&$headers) {
- $length = strlen($h);
- if ($value = trim($h)) {
- $headers[] = trim($h);
- }
- return $length;
+ $headers[] = trim($h);
+ return strlen($h);
},
];
diff --git a/tests/Client/CurlFactoryTest.php b/tests/Client/CurlFactoryTest.php
index <HASH>..<HASH> 100644
--- a/tests/Client/CurlFactoryTest.php
+++ b/tests/Client/CurlFactoryTest.php
@@ -709,6 +709,45 @@ class CurlFactoryTest extends \PHPUnit_Framework_TestCase
);
$this->assertInstanceOf('GuzzleHttp\Ring\Exception\ConnectException', $response['error']);
}
+
+ public function testParsesLastResponseOnly()
+ {
+ $response1 = [
+ 'status' => 301,
+ 'headers' => [
+ 'Content-Length' => ['0'],
+ 'Location' => ['/foo']
+ ]
+ ];
+
+ $response2 = [
+ 'status' => 200,
+ 'headers' => [
+ 'Content-Length' => ['0'],
+ 'Foo' => ['bar']
+ ]
+ ];
+
+ Server::flush();
+ Server::enqueue([$response1, $response2]);
+
+ $a = new CurlMultiHandler();
+ $response = $a([
+ 'http_method' => 'GET',
+ 'headers' => ['Host' => [Server::$host]],
+ 'client' => [
+ 'curl' => [
+ CURLOPT_FOLLOWLOCATION => true
+ ]
+ ]
+ ])->wait();
+
+ $this->assertEquals(1, $response['transfer_stats']['redirect_count']);
+ $this->assertEquals('http://127.0.0.1:8125/foo', $response['effective_url']);
+ $this->assertEquals(['bar'], $response['headers']['Foo']);
+ $this->assertEquals(200, $response['status']);
+ $this->assertFalse(Core::hasHeader($response, 'Location'));
+ }
}
} | Handling multi-response header parsing.
This commit closes issue #<I> and addresses #<I>. This commit ensures
that curl responses that required curl to send multiple requests are
parsed correctly and that headers are not merged together in the
resulting Guzzle response object. | guzzle_RingPHP | train |
fc3a4c3843f4be7640ee2ac1a7d354b294ed0bd7 | diff --git a/opal/corelib/string/encoding.rb b/opal/corelib/string/encoding.rb
index <HASH>..<HASH> 100644
--- a/opal/corelib/string/encoding.rb
+++ b/opal/corelib/string/encoding.rb
@@ -1,30 +1,26 @@
require 'corelib/string'
class Encoding
+ self.JS['$$register'] = `{}`
+
def self.register(name, options = {}, &block)
names = [name] + (options[:aliases] || [])
encoding = Class.new(self, &block).
new(name, names, options[:ascii] || false, options[:dummy] || false)
- names.each {|name|
+ register = self.JS['$$register']
+ names.each do |name|
const_set name.sub('-', '_'), encoding
- }
+ register.JS["$$#{name}"] = encoding
+ end
end
def self.find(name)
- upcase = name.upcase
-
- constants.each {|const|
- encoding = const_get(const)
-
- next unless Encoding === encoding
-
- if encoding.name == upcase || encoding.names.include?(upcase)
- return encoding
- end
- }
-
- raise ArgumentError, "unknown encoding name - #{name}"
+ return default_external if name == :default_external
+ register = self.JS['$$register']
+ encoding = register.JS["$$#{name}"] || register.JS["$$#{name.upcase}"]
+ raise ArgumentError, "unknown encoding name - #{name}" unless encoding
+ encoding
end
class << self
@@ -194,21 +190,15 @@ class String
def force_encoding(encoding)
%x{
- if (encoding === self.encoding) {
- return self;
- }
- }
- encoding = Opal.coerce_to!(encoding, String, :to_s)
- encoding = Encoding.find(encoding)
+ if (encoding === self.encoding) { return self; }
- return self if encoding == @encoding
- raise ArgumentError, "unknown encoding name - #{encoding}" if encoding.nil?
+ encoding = #{Opal.coerce_to!(encoding, String, :to_s)};
+ encoding = #{Encoding.find(encoding)};
- %x{
- var result = new String(self);
- result.encoding = encoding;
+ if (encoding === self.encoding) { return self; }
- return result;
+ self.encoding = encoding;
+ return self;
}
end
diff --git a/spec/opal/core/string_spec.rb b/spec/opal/core/string_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/opal/core/string_spec.rb
+++ b/spec/opal/core/string_spec.rb
@@ -47,4 +47,17 @@ describe 'Encoding' do
"è".force_encoding('BINARY').should == "\xC3\xA8"
"è".force_encoding('binary').should == "\xC3\xA8"
end
+
+ describe '.find' do
+ it 'finds the encoding regardless of the case' do
+ Encoding.find('ASCII').should == Encoding::ASCII
+ Encoding.find('ascii').should == Encoding::ASCII
+ Encoding.find('US-ASCII').should == Encoding::ASCII
+ Encoding.find('us-ascii').should == Encoding::ASCII
+ Encoding.find('ASCII-8BIT').should == Encoding::ASCII
+ Encoding.find('ascii-8bit').should == Encoding::ASCII
+ Encoding.find('BINARY').should == Encoding::ASCII
+ Encoding.find('binary').should == Encoding::ASCII
+ end
+ end
end | Keep an internal registry of encodings
Previously it was relying just on constants. | opal_opal | train |
0ffc61239f61dbc2df1d4729128fa051b779c391 | diff --git a/Form/Type/FilterDbRowMultipleSingleChoiceType.php b/Form/Type/FilterDbRowMultipleSingleChoiceType.php
index <HASH>..<HASH> 100644
--- a/Form/Type/FilterDbRowMultipleSingleChoiceType.php
+++ b/Form/Type/FilterDbRowMultipleSingleChoiceType.php
@@ -25,8 +25,11 @@ class FilterDbRowMultipleSingleChoiceType extends FilterDbRowType {
'multiple'=>false,
'class'=>$options['class'],
'property'=>isset($options['property']) ? $options['property'] : null,
- 'query_builder' => isset($options['where']) || isset($options['order']) ? function(ObjectRepository $er) use($options, $nyrodevDb) {
- $ret = $nyrodevDb->getQueryBuilder($er);
+ 'query_builder' => isset($options['query_builder']) || isset($options['where']) || isset($options['order']) ? function(ObjectRepository $or) use($options, $nyrodevDb) {
+ if (isset($options['query_builder']))
+ return $options['query_builder']($or);
+
+ $ret = $nyrodevDb->getQueryBuilder($or);
/* @var $ret \NyroDev\UtilityBundle\QueryBuilder\AbstractQueryBuilder */
if (isset($options['where']) && is_array($options['where'])) {
@@ -73,6 +76,7 @@ class FilterDbRowMultipleSingleChoiceType extends FilterDbRowType {
$resolver->setDefaults(array(
'class'=>null,
'property'=>null,
+ 'query_builder'=>null,
'where'=>null,
'order'=>null,
));
diff --git a/Form/Type/FilterDbRowMultipleType.php b/Form/Type/FilterDbRowMultipleType.php
index <HASH>..<HASH> 100644
--- a/Form/Type/FilterDbRowMultipleType.php
+++ b/Form/Type/FilterDbRowMultipleType.php
@@ -28,8 +28,11 @@ class FilterDbRowMultipleType extends FilterDbRowType {
),
'class'=>$options['class'],
'property'=>isset($options['property']) ? $options['property'] : null,
- 'query_builder' => isset($options['where']) || isset($options['order']) ? function(ObjectRepository $er) use($options, $nyrodevDb) {
- $ret = $nyrodevDb->getQueryBuilder($er);
+ 'query_builder' => isset($options['query_builder']) || isset($options['where']) || isset($options['order']) ? function(ObjectRepository $or) use($options, $nyrodevDb) {
+ if (isset($options['query_builder']))
+ return $options['query_builder']($or);
+
+ $ret = $nyrodevDb->getQueryBuilder($or);
/* @var $ret \NyroDev\UtilityBundle\QueryBuilder\AbstractQueryBuilder */
if (isset($options['where']) && is_array($options['where'])) {
@@ -83,6 +86,7 @@ class FilterDbRowMultipleType extends FilterDbRowType {
$resolver->setDefaults(array(
'class'=>null,
'property'=>null,
+ 'query_builder'=>null,
'where'=>null,
'order'=>null,
));
diff --git a/Form/Type/FilterDbRowType.php b/Form/Type/FilterDbRowType.php
index <HASH>..<HASH> 100644
--- a/Form/Type/FilterDbRowType.php
+++ b/Form/Type/FilterDbRowType.php
@@ -24,8 +24,11 @@ class FilterDbRowType extends FilterType {
'required'=>false,
'class'=>$options['class'],
'property'=>isset($options['property']) ? $options['property'] : null,
- 'query_builder' => isset($options['where']) || isset($options['order']) ? function(ObjectRepository $er) use($options, $nyrodevDb) {
- $ret = $nyrodevDb->getQueryBuilder($er);
+ 'query_builder' => isset($options['query_builder']) || isset($options['where']) || isset($options['order']) ? function(ObjectRepository $or) use($options, $nyrodevDb) {
+ if (isset($options['query_builder']))
+ return $options['query_builder']($or);
+
+ $ret = $nyrodevDb->getQueryBuilder($or);
/* @var $ret \NyroDev\UtilityBundle\QueryBuilder\AbstractQueryBuilder */
if (isset($options['where']) && is_array($options['where'])) {
@@ -62,6 +65,7 @@ class FilterDbRowType extends FilterType {
$resolver->setDefaults(array(
'class'=>null,
'property'=>null,
+ 'query_builder'=>null,
'where'=>null,
'order'=>null,
)); | Add query_builder option for dbRow filter types | nyroDev_UtilityBundle | train |
0de4dda0b68935b7816fc488dbe532a654f3a349 | diff --git a/tests/test_authentication.py b/tests/test_authentication.py
index <HASH>..<HASH> 100644
--- a/tests/test_authentication.py
+++ b/tests/test_authentication.py
@@ -12,9 +12,11 @@ from starlette.authentication import (
requires,
)
from starlette.endpoints import HTTPEndpoint
+from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
+from starlette.routing import Route, WebSocketRoute
from starlette.websockets import WebSocketDisconnect
@@ -34,11 +36,6 @@ class BasicAuth(AuthenticationBackend):
return AuthCredentials(["authenticated"]), SimpleUser(username)
-app = Starlette()
-app.add_middleware(AuthenticationMiddleware, backend=BasicAuth())
-
-
[email protected]("/")
def homepage(request):
return JSONResponse(
{
@@ -48,7 +45,6 @@ def homepage(request):
)
[email protected]("/dashboard")
@requires("authenticated")
async def dashboard(request):
return JSONResponse(
@@ -59,7 +55,6 @@ async def dashboard(request):
)
[email protected]("/admin")
@requires("authenticated", redirect="homepage")
async def admin(request):
return JSONResponse(
@@ -70,7 +65,6 @@ async def admin(request):
)
[email protected]("/dashboard/sync")
@requires("authenticated")
def dashboard_sync(request):
return JSONResponse(
@@ -81,7 +75,6 @@ def dashboard_sync(request):
)
[email protected]("/dashboard/class")
class Dashboard(HTTPEndpoint):
@requires("authenticated")
def get(self, request):
@@ -93,7 +86,6 @@ class Dashboard(HTTPEndpoint):
)
[email protected]("/admin/sync")
@requires("authenticated", redirect="homepage")
def admin_sync(request):
return JSONResponse(
@@ -104,7 +96,6 @@ def admin_sync(request):
)
[email protected]_route("/ws")
@requires("authenticated")
async def websocket_endpoint(websocket):
await websocket.accept()
@@ -126,7 +117,6 @@ def async_inject_decorator(**kwargs):
return wrapper
[email protected]("/dashboard/decorated")
@async_inject_decorator(additional="payload")
@requires("authenticated")
async def decorated_async(request, additional):
@@ -149,7 +139,6 @@ def sync_inject_decorator(**kwargs):
return wrapper
[email protected]("/dashboard/decorated/sync")
@sync_inject_decorator(additional="payload")
@requires("authenticated")
def decorated_sync(request, additional):
@@ -172,7 +161,6 @@ def ws_inject_decorator(**kwargs):
return wrapper
[email protected]_route("/ws/decorated")
@ws_inject_decorator(additional="payload")
@requires("authenticated")
async def websocket_endpoint_decorated(websocket, additional):
@@ -186,6 +174,23 @@ async def websocket_endpoint_decorated(websocket, additional):
)
+app = Starlette(
+ middleware=[Middleware(AuthenticationMiddleware, backend=BasicAuth())],
+ routes=[
+ Route("/", endpoint=homepage),
+ Route("/dashboard", endpoint=dashboard),
+ Route("/admin", endpoint=admin),
+ Route("/dashboard/sync", endpoint=dashboard_sync),
+ Route("/dashboard/class", endpoint=Dashboard),
+ Route("/admin/sync", endpoint=admin_sync),
+ Route("/dashboard/decorated", endpoint=decorated_async),
+ Route("/dashboard/decorated/sync", endpoint=decorated_sync),
+ WebSocketRoute("/ws", endpoint=websocket_endpoint),
+ WebSocketRoute("/ws/decorated", endpoint=websocket_endpoint_decorated),
+ ],
+)
+
+
def test_invalid_decorator_usage():
with pytest.raises(Exception): | Remove routing decorators in test_authentication.py (#<I>) | encode_starlette | train |
f9f6936e9d6603d03e4301e41063264271fd8a22 | diff --git a/server/sonar-server/src/main/java/org/sonar/server/component/index/ComponentIndexSearchFeature.java b/server/sonar-server/src/main/java/org/sonar/server/component/index/ComponentIndexSearchFeature.java
index <HASH>..<HASH> 100644
--- a/server/sonar-server/src/main/java/org/sonar/server/component/index/ComponentIndexSearchFeature.java
+++ b/server/sonar-server/src/main/java/org/sonar/server/component/index/ComponentIndexSearchFeature.java
@@ -39,6 +39,13 @@ import static org.sonar.server.es.DefaultIndexSettingsElement.SORTABLE_ANALYZER;
public enum ComponentIndexSearchFeature {
+ EXACT_IGNORE_CASE {
+ @Override
+ public QueryBuilder getQuery(String queryText) {
+ return matchQuery(SORTABLE_ANALYZER.subField(FIELD_NAME), queryText)
+ .boost(2.5f);
+ }
+ },
PREFIX {
@Override
public QueryBuilder getQuery(String queryText) {
@@ -69,7 +76,7 @@ public enum ComponentIndexSearchFeature {
@Override
public QueryBuilder getQuery(String queryText) {
return matchQuery(SORTABLE_ANALYZER.subField(FIELD_KEY), queryText)
- .boost(5f);
+ .boost(50f);
}
};
diff --git a/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexScoreTest.java b/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexScoreTest.java
index <HASH>..<HASH> 100644
--- a/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexScoreTest.java
+++ b/server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexScoreTest.java
@@ -83,6 +83,13 @@ public class ComponentIndexScoreTest extends ComponentIndexTest {
}
@Test
+ public void scoring_perfect_match_dispite_case_changes() {
+ assertResultOrder("sonarqube",
+ "SonarQube",
+ "SonarQube SCM Git");
+ }
+
+ @Test
public void do_not_match_wrong_file_extension() {
ComponentDto file1 = indexFile("MyClass.java");
ComponentDto file2 = indexFile("ClassExample.java"); | SONAR-<I> make perfect name matches score higher in global search | SonarSource_sonarqube | train |
3f37bbecadf909dfe4645f9ada3c2b76f79ed62a | diff --git a/bloop/models.py b/bloop/models.py
index <HASH>..<HASH> 100644
--- a/bloop/models.py
+++ b/bloop/models.py
@@ -390,7 +390,11 @@ class GlobalSecondaryIndex(Index):
.. _GlobalSecondaryIndex: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html
"""
- def __init__(self, *, projection, hash_key, range_key=None, read_units=None, write_units=None, name=None, **kwargs):
+ def __init__(
+ self, *, projection,
+ hash_key, range_key=None,
+ read_units=None, write_units=None,
+ name=None, **kwargs):
super().__init__(hash_key=hash_key, range_key=range_key, name=name, projection=projection, **kwargs)
self.write_units = write_units
self.read_units = read_units
diff --git a/tests/unit/test_models.py b/tests/unit/test_models.py
index <HASH>..<HASH> 100644
--- a/tests/unit/test_models.py
+++ b/tests/unit/test_models.py
@@ -112,12 +112,12 @@ def test_load_dump_none(engine):
def test_meta_read_write_units():
- """If `read_units` or `write_units` is missing from a model's Meta, it defaults to 1"""
+ """If `read_units` or `write_units` is missing from a model's Meta, it defaults to None until bound"""
class Model(BaseModel):
id = Column(UUID, hash_key=True)
- assert Model.Meta.write_units == 1
- assert Model.Meta.read_units == 1
+ assert Model.Meta.write_units is None
+ assert Model.Meta.read_units is None
class Other(BaseModel):
class Meta: | fix flake issue, test model read/write units default to None | numberoverzero_bloop | train |
7074e544ddfceddfc1450e368d9cb454dae47a37 | diff --git a/lib/Drupal/AppConsole/Command/Helper/RegisterCommands.php b/lib/Drupal/AppConsole/Command/Helper/RegisterCommands.php
index <HASH>..<HASH> 100644
--- a/lib/Drupal/AppConsole/Command/Helper/RegisterCommands.php
+++ b/lib/Drupal/AppConsole/Command/Helper/RegisterCommands.php
@@ -24,34 +24,8 @@ class RegisterCommands extends Helper {
}
}
- protected function getContainer() {
- $this->getKernel();
- if(!isset($this->container)){
- $this->container = $this->kernel->getContainer();
- }
- }
-
- protected function getModuleList() {
- // Get Container
- $this->getContainer();
- // Get Module handler
- if (!isset($this->modules)){
- $module_handler = $this->container->get('module_handler');
- $this->modules = $module_handler->getModuleDirectories();
- }
- }
-
- protected function getNamespaces() {
- $this->getContainer();
- // Get Transversal, namespaces
- if (!isset($this->namespaces)){
- $namespaces = $this->container->get('container.namespaces');
- $this->namespaces = $namespaces->getArrayCopy();
- }
- }
-
public function register() {
-
+
$this->getModuleList();
$this->getNamespaces();
@@ -65,7 +39,7 @@ class RegisterCommands extends Helper {
if (!is_dir($dir)) {
continue;
}
-
+
$finder->files()
->name('*Command.php')
->in($dir)
@@ -74,18 +48,18 @@ class RegisterCommands extends Helper {
foreach ($finder as $file) {
$ns = $prefix;
-
+
if ($relativePath = $file->getRelativePath()) {
$ns .= '\\'.strtr($relativePath, '/', '\\');
}
-
+
$class = $ns.'\\'.$file->getBasename('.php');
if (class_exists($class)){
$r = new \ReflectionClass($class);
// if is a valid command
- if ($r->isSubclassOf('Symfony\\Component\\Console\\Command\\Command')
- && !$r->isAbstract()
+ if ($r->isSubclassOf('Symfony\\Component\\Console\\Command\\Command')
+ && !$r->isAbstract()
&& !$r->getConstructor()->getNumberOfRequiredParameters()) {
// Register command
@@ -100,7 +74,33 @@ class RegisterCommands extends Helper {
* @see \Symfony\Component\Console\Helper\HelperInterface::getName()
*/
public function getName() {
- return 'register_commands';
+ return 'register_commands';
+ }
+
+ protected function getContainer() {
+ $this->getKernel();
+ if(!isset($this->container)){
+ $this->container = $this->kernel->getContainer();
+ }
+ }
+
+ protected function getModuleList() {
+ // Get Container
+ $this->getContainer();
+ // Get Module handler
+ if (!isset($this->modules)){
+ $module_handler = $this->container->get('module_handler');
+ $this->modules = $module_handler->getModuleDirectories();
+ }
+ }
+
+ protected function getNamespaces() {
+ $this->getContainer();
+ // Get Transversal, namespaces
+ if (!isset($this->namespaces)){
+ $namespaces = $this->container->get('container.namespaces');
+ $this->namespaces = $namespaces->getArrayCopy();
+ }
}
}
\ No newline at end of file | revert order of protected to be at the bottom | hechoendrupal_drupal-console | train |
1372163c8608deea49c39560d14d16116d803742 | diff --git a/clients/python/girder_client/__init__.py b/clients/python/girder_client/__init__.py
index <HASH>..<HASH> 100644
--- a/clients/python/girder_client/__init__.py
+++ b/clients/python/girder_client/__init__.py
@@ -714,18 +714,6 @@ class GirderClient(object):
for chunk in req.iter_content(chunk_size=65536):
path.write(chunk)
- def downloadFileInline(self, fileId):
- """
- Download a file inline. The binary response content is returned
-
- :param fileId: The ID of the girder file to download.
- """
-
- req = requests.get('%sfile/%s/download' % (self.urlBase, fileId),
- headers={'Girder-Token': self.token})
- if req:
- return req.content
-
def downloadItem(self, itemId, dest, name=None):
"""
Download an item from Girder into a local folder. Each file in the | removed useless downloadFileInline function | girder_girder | train |
76bb61a65dc60f5ae293951bb0dd873993915308 | diff --git a/tests/frontend/org/voltdb/TestRejoinFuzz.java b/tests/frontend/org/voltdb/TestRejoinFuzz.java
index <HASH>..<HASH> 100644
--- a/tests/frontend/org/voltdb/TestRejoinFuzz.java
+++ b/tests/frontend/org/voltdb/TestRejoinFuzz.java
@@ -58,6 +58,7 @@ public class TestRejoinFuzz extends RejoinTestBase {
LocalCluster.FailureState.ALL_RUNNING,
true);
cluster.setMaxHeap(256);
+ cluster.overrideAnyRequestForValgrind();
final int numTuples = cluster.isValgrind() ? 1000 : 60000;
boolean success = cluster.compile(builder);
diff --git a/tests/frontend/org/voltdb/dtxn/TestNonDetermisticSeppuku.java b/tests/frontend/org/voltdb/dtxn/TestNonDetermisticSeppuku.java
index <HASH>..<HASH> 100644
--- a/tests/frontend/org/voltdb/dtxn/TestNonDetermisticSeppuku.java
+++ b/tests/frontend/org/voltdb/dtxn/TestNonDetermisticSeppuku.java
@@ -55,6 +55,7 @@ public class TestNonDetermisticSeppuku extends TestCase {
builder.addProcedures(NonDeterministicSPProc.class);
cluster = new LocalCluster("det1.jar", 1, 2, 1, BackendTarget.NATIVE_EE_JNI);
+ cluster.overrideAnyRequestForValgrind();
cluster.compile(builder);
cluster.setHasLocalServer(false);
diff --git a/tests/frontend/org/voltdb/regressionsuites/LocalCluster.java b/tests/frontend/org/voltdb/regressionsuites/LocalCluster.java
index <HASH>..<HASH> 100644
--- a/tests/frontend/org/voltdb/regressionsuites/LocalCluster.java
+++ b/tests/frontend/org/voltdb/regressionsuites/LocalCluster.java
@@ -171,8 +171,8 @@ public class LocalCluster implements VoltServerConfig {
m_pipes = new ArrayList<PipeToFile>();
m_cmdLines = new ArrayList<CommandLine>();
- // if the user wants valgrind, give it to 'em
- if (isValgrind() && (target == BackendTarget.NATIVE_EE_JNI)) {
+ // if the user wants valgrind and it makes sense, give it to 'em
+ if (isMemcheckDefined() && (target == BackendTarget.NATIVE_EE_JNI)) {
m_target = BackendTarget.NATIVE_EE_VALGRIND_IPC;
}
else {
@@ -226,6 +226,16 @@ public class LocalCluster implements VoltServerConfig {
this.templateCmdLine.m_noLoadLibVOLTDB = m_target == BackendTarget.HSQLDB_BACKEND;
}
+ /**
+ * Override the Valgrind backend with a JNI backend.
+ * Called after a constructor but before startup.
+ */
+ public void overrideAnyRequestForValgrind() {
+ if (templateCmdLine.m_backend == BackendTarget.NATIVE_EE_VALGRIND_IPC) {
+ templateCmdLine.m_backend = BackendTarget.NATIVE_EE_JNI;
+ }
+ }
+
@Override
public void setCallingMethodName(String name) {
m_callingMethodName = name;
@@ -309,12 +319,6 @@ public class LocalCluster implements VoltServerConfig {
cmdln.ipcPort(proc.port());
}
- // rtb: why is this? this flag short-circuits an Inits worker
- // but can only be set on the local in-process server (there is no
- // command line version of it.) Consequently, in-process and out-of-
- // process VoltDBs initialize differently when this flag is set.
- // cmdln.rejoinTest(true);
-
// for debug, dump the command line to a unique file.
// cmdln.dumpToFile("/Users/rbetts/cmd_" + Integer.toString(portGenerator.next()));
@@ -1046,8 +1050,7 @@ public class LocalCluster implements VoltServerConfig {
cl.m_leaderPort = config.m_leaderPort;
}
- @Override
- public boolean isValgrind() {
+ protected boolean isMemcheckDefined() {
final String buildType = System.getenv().get("BUILD");
if (buildType == null) {
return false;
@@ -1055,6 +1058,10 @@ public class LocalCluster implements VoltServerConfig {
return buildType.startsWith("memcheck");
}
+ @Override
+ public boolean isValgrind() {
+ return templateCmdLine.m_backend == BackendTarget.NATIVE_EE_VALGRIND_IPC;
+ }
@Override
public void createDirectory(File path) throws IOException {
diff --git a/tests/frontend/org/voltdb/regressionsuites/TestPartitionDetection.java b/tests/frontend/org/voltdb/regressionsuites/TestPartitionDetection.java
index <HASH>..<HASH> 100644
--- a/tests/frontend/org/voltdb/regressionsuites/TestPartitionDetection.java
+++ b/tests/frontend/org/voltdb/regressionsuites/TestPartitionDetection.java
@@ -30,6 +30,7 @@ import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicBoolean;
+
import junit.framework.TestCase;
import org.voltdb.BackendTarget;
@@ -170,6 +171,7 @@ public class TestPartitionDetection extends TestCase
// choose a partitionable cluster: 2 sites / 2 hosts / k-factor 1.
// use a separate process for each host.
LocalCluster cluster = new LocalCluster("partition-detection1.jar", 2, 2, 1, BackendTarget.NATIVE_EE_JNI);
+ cluster.overrideAnyRequestForValgrind(); // valgrind and failure don't mix well atm
cluster.setHasLocalServer(false);
builder.setPartitionDetectionSettings(TMPDIR, TESTNONCE);
boolean success = cluster.compile(builder); | ENG-<I>: Some test changes to make Valgrind pass (hopefully).
I think there's a larger problem where Valgrind tests don't look much different from regular tests, from an output to junit reporting point of view. How many tests run in Valgrind? It's really hard to say at the moment without inspecting all the logs. The reported number is likely wrong. | VoltDB_voltdb | train |
ea43ff15dd6a6e755ef54ba75f650ab87a86539e | diff --git a/app/Czech.php b/app/Czech.php
index <HASH>..<HASH> 100644
--- a/app/Czech.php
+++ b/app/Czech.php
@@ -109,7 +109,7 @@ class Czech implements ValidatorInterface
if (!$this->validateBankCode($bankCode)) {
return false;
}
-
+
if (null !== $firstPart && !$this->validateCheckSum($firstPart)) {
return false;
}
@@ -201,13 +201,16 @@ PATTERN;
$firstPart = $secondPart = $bankCode = null;
preg_match($pattern, $bankAccountNumber, $match);
- if (isset($match[6])) {
+ if (!empty($match[6])) {
$bankCode = $match[6];
}
- if (isset($match[2]) && isset($match[3])) {
+ if (isset($match[2])
+ && '' !== $match[2]
+ && isset($match[3])
+ && '' !== $match[3]) {
$firstPart = $match[2];
$secondPart = $match[3];
- } elseif (isset($match[5])) {
+ } elseif (!empty($match[5])) {
$secondPart = $match[5];
}
diff --git a/readme.md b/readme.md
index <HASH>..<HASH> 100644
--- a/readme.md
+++ b/readme.md
@@ -17,7 +17,7 @@ composer require heureka/bankAccountValidator
require_once __DIR__ . '/vendor/autoload.php';
-$validator = new BankAccountValidator/Czech();
+$validator = new BankAccountValidator\Czech();
$isValid = $validator->validate('333-123/0123');
```
diff --git a/tests/CzechTest.php b/tests/CzechTest.php
index <HASH>..<HASH> 100644
--- a/tests/CzechTest.php
+++ b/tests/CzechTest.php
@@ -47,7 +47,7 @@ class CzechTest extends \PHPUnit_Framework_TestCase
return [
[
[null, null, null],
- "ASD"
+ 'ASD'
],
[
[null, null, null],
@@ -55,32 +55,36 @@ class CzechTest extends \PHPUnit_Framework_TestCase
],
[
['0', '12', '1234'],
- "0-12/1234"
+ '0-12/1234'
],
[
- [null, null, null],
- "0-2/1234"
+ ['0', '12', '1234'],
+ '0-12/1234'
+ ],
+ [
+ [null, '196437539', '0100'],
+ '196437539/0100'
],
[
//if one part is incorrect no matches returns
[null, null, null],
- "21231221/123"
+ '21231221/123'
],
[
[null, null, null],
- "21231221/12312"
+ '21231221/12312'
],
[
['123456', '0000000123', '0000'],
- "123456-0000000123/0000"
+ '123456-0000000123/0000'
],
[
[null, null, null],
- "123456-00000000123/0000"
+ '123456-00000000123/0000'
],
[
[null, null, null],
- "1234567-000000123/0000"
+ '1234567-000000123/0000'
]
];
}
@@ -88,6 +92,7 @@ class CzechTest extends \PHPUnit_Framework_TestCase
public function validateProvider()
{
return [
+
[
false,
'196437539/0100'
@@ -114,6 +119,10 @@ class CzechTest extends \PHPUnit_Framework_TestCase
],
[
true,
+ '0086-3055103/2030'
+ ],
+ [
+ false,
'0086-3055103/30'
],
]; | Fix class for passing tests
Fix readme.md - wrong slash in example | heureka_bank-account-validator | train |
1492a15d50f2af7be9b716cf28833bdf47343f4c | diff --git a/spec/tweetstream/client_spec.rb b/spec/tweetstream/client_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/tweetstream/client_spec.rb
+++ b/spec/tweetstream/client_spec.rb
@@ -198,7 +198,7 @@ describe TweetStream::Client do
end
it '#filter should make a call to "statuses/filter" with the query params provided longitude/latitude pairs, separated by commas ' do
@client.should_receive(:start).once.with('statuses/filter', :locations => '-122.75,36.8,-121.75,37.8,-74,40,-73,41', :method => :post)
- @client.filter(:locations => -122.75,36.8,-121.75,37.8,-74,40,-73,41)
+ @client.filter(:locations => '-122.75,36.8,-121.75,37.8,-74,40,-73,41')
end
end | location test args need to be in quotes | tweetstream_tweetstream | train |
b9d4980265a4467ee1f12e91016bc234ed8b9813 | diff --git a/src/ContainerParser/Parser/ScopeParser.php b/src/ContainerParser/Parser/ScopeParser.php
index <HASH>..<HASH> 100644
--- a/src/ContainerParser/Parser/ScopeParser.php
+++ b/src/ContainerParser/Parser/ScopeParser.php
@@ -74,6 +74,12 @@ class ScopeParser extends ContainerParser
$this->scope->addNode($this->parseChild(ParameterDefinitionParser::class));
}
+ // is service definition
+ elseif ($token->isType(T::TOKEN_DEPENDENCY))
+ {
+ $this->scope->addNode($this->parseChild(ServiceDefinitionParser::class));
+ }
+
// import another scope
elseif ($token->isType(T::TOKEN_IMPORT))
{
diff --git a/tests/ContainerParser/Parser/ScopeParserTest.php b/tests/ContainerParser/Parser/ScopeParserTest.php
index <HASH>..<HASH> 100644
--- a/tests/ContainerParser/Parser/ScopeParserTest.php
+++ b/tests/ContainerParser/Parser/ScopeParserTest.php
@@ -8,7 +8,8 @@ use ClanCats\Container\ContainerParser\{
Nodes\ScopeNode,
Token as T,
- Nodes\ParameterDefinitionNode
+ Nodes\ParameterDefinitionNode,
+ Nodes\ServiceDefinitionNode
};
class ScopeParserTest extends ParserTestCase
@@ -70,4 +71,16 @@ class ScopeParserTest extends ParserTestCase
{
$this->scopeNodeFromCode(":test: 42\n42"); // actually i want this in the feature
}
+
+ public function testParseServiceDefinition()
+ {
+ $scopeNode = $this->scopeNodeFromCode('@artist.eddi: Person(:artist.eddi)');
+
+ $nodes = $scopeNode->getNodes();
+ $this->assertCount(1, $nodes);
+ $this->assertInstanceOf(ServiceDefinitionNode::class, $nodes[0]);
+
+ $this->assertEquals('artist.eddi', $nodes[0]->getName());
+ $this->assertEquals('Person', $nodes[0]->getClassName());
+ }
}
\ No newline at end of file | Added scope parser service definitions | ClanCats_Container | train |
9e47373d824f7c23a047c522e5e9ad6f6428e846 | diff --git a/engines/bastion/app/assets/javascripts/bastion/widgets/nutupane.factory.js b/engines/bastion/app/assets/javascripts/bastion/widgets/nutupane.factory.js
index <HASH>..<HASH> 100644
--- a/engines/bastion/app/assets/javascripts/bastion/widgets/nutupane.factory.js
+++ b/engines/bastion/app/assets/javascripts/bastion/widgets/nutupane.factory.js
@@ -53,7 +53,8 @@ angular.module('Bastion.widgets').factory('Nutupane',
params: params,
resource: resource,
rows: [],
- searchTerm: $location.search()[self.searchKey]
+ searchTerm: $location.search()[self.searchKey],
+ initialLoad: true
};
// Set default resource values | Fixes #<I> - only disable initial load if it's actually disabled. | Katello_katello | train |
68b216c03d295bad04365ead01eb479a84241e93 | diff --git a/core/index/lucene42_test.go b/core/index/lucene42_test.go
index <HASH>..<HASH> 100644
--- a/core/index/lucene42_test.go
+++ b/core/index/lucene42_test.go
@@ -20,7 +20,7 @@ func TestReadFieldInfos(t *testing.T) {
if err != nil {
t.Error(err)
}
- if !fis.hasNorms || fis.hasDocValues {
+ if !fis.HasNorms || fis.HasDocValues {
t.Errorf("hasNorms must be true and hasDocValues must be false, but found %v", fis)
}
}
diff --git a/core/index/segmentInfos.go b/core/index/segmentInfos.go
index <HASH>..<HASH> 100644
--- a/core/index/segmentInfos.go
+++ b/core/index/segmentInfos.go
@@ -445,7 +445,9 @@ func (sis *SegmentInfos) Read(directory store.Directory, segmentFileName string)
return err
}
if checksumNow != checksumThen {
- return errors.New(fmt.Sprintf("checksum mismatch in segments file (resource: %v)", input))
+ return errors.New(fmt.Sprintf(
+ "checksum mismatch in segments file: %v vs %v (resource: %v)",
+ checksumNow, checksumThen, input))
}
success = true
diff --git a/core/store/input.go b/core/store/input.go
index <HASH>..<HASH> 100644
--- a/core/store/input.go
+++ b/core/store/input.go
@@ -5,7 +5,7 @@ import (
"fmt"
"github.com/balzaczyy/golucene/core/util"
"hash"
- "hash/crc64"
+ "hash/crc32"
"io"
)
@@ -66,11 +66,11 @@ func bufferSize(context IOContext) int {
type ChecksumIndexInput struct {
*IndexInputImpl
main IndexInput
- digest hash.Hash64
+ digest hash.Hash32
}
func NewChecksumIndexInput(main IndexInput) *ChecksumIndexInput {
- ans := &ChecksumIndexInput{main: main, digest: crc64.New(crc64.MakeTable(crc64.ISO))}
+ ans := &ChecksumIndexInput{main: main, digest: crc32.NewIEEE()}
ans.IndexInputImpl = newIndexInputImpl(fmt.Sprintf("ChecksumIndexInput(%v)", main), ans)
return ans
}
@@ -91,7 +91,7 @@ func (in *ChecksumIndexInput) ReadBytes(buf []byte) error {
}
func (in *ChecksumIndexInput) Checksum() int64 {
- return int64(in.digest.Sum64())
+ return int64(in.digest.Sum32())
}
func (in *ChecksumIndexInput) Close() error { | fix search by reverting CRC<I> change | balzaczyy_golucene | train |
4cd79fb0856da414b73ccf6b459384be1e49086b | diff --git a/chain.py b/chain.py
index <HASH>..<HASH> 100644
--- a/chain.py
+++ b/chain.py
@@ -19,7 +19,7 @@ from evm.rlp.transactions import BaseTransaction # noqa: F401
from p2p import protocol
from p2p import eth
from p2p.cancel_token import CancelToken, wait_with_token
-from p2p.exceptions import OperationCancelled
+from p2p.exceptions import NoConnectedPeers, OperationCancelled
from p2p.peer import BasePeer, ETHPeer, PeerPool, PeerPoolSubscriber
from p2p.service import BaseService
@@ -150,6 +150,10 @@ class FastChainSyncer(BaseService, PeerPoolSubscriber):
# find the common ancestor between our chain and the peer's.
start_at = max(0, head.block_number - eth.MAX_HEADERS_FETCH)
while not self._sync_complete.is_set():
+ if peer.is_finished:
+ self.logger.info("%s disconnected, aborting sync", peer)
+ break
+
self.logger.info("Fetching chain segment starting at #%d", start_at)
peer.sub_proto.send_get_block_headers(start_at, eth.MAX_HEADERS_FETCH, reverse=False)
try:
@@ -169,7 +173,11 @@ class FastChainSyncer(BaseService, PeerPoolSubscriber):
self.logger.info("Got headers segment starting at #%d", start_at)
# TODO: Process headers for consistency.
- head_number = await self._process_headers(peer, headers)
+ try:
+ head_number = await self._process_headers(peer, headers)
+ except NoConnectedPeers:
+ self.logger.info("No connected peers, aborting sync")
+ break
start_at = head_number + 1
async def _process_headers(self, peer: ETHPeer, headers: List[BlockHeader]) -> int:
@@ -222,6 +230,13 @@ class FastChainSyncer(BaseService, PeerPoolSubscriber):
download_queue: 'asyncio.Queue[List[DownloadedBlockPart]]',
key_func: Callable[[BlockHeader], Union[bytes, Tuple[bytes, bytes]]],
part_name: str) -> 'List[DownloadedBlockPart]':
+ """Download block parts for the given headers, using the given request_func.
+
+ Retry timed out parts until we have the parts for all headers.
+
+ Raises NoConnectedPeers if at any moment we have no connected peers to request the missing
+ parts to.
+ """
missing = headers.copy()
# The ETH protocol doesn't guarantee that we'll get all body parts requested, so we need
# to keep track of the number of pending replies and missing items to decide when to retry
@@ -257,6 +272,8 @@ class FastChainSyncer(BaseService, PeerPoolSubscriber):
self,
headers: List[BlockHeader],
request_func: Callable[[ETHPeer, List[BlockHeader]], None]) -> int:
+ if not self.peer_pool.peers:
+ raise NoConnectedPeers()
length = math.ceil(len(headers) / len(self.peer_pool.peers))
batches = list(partition_all(length, headers))
for peer, batch in zip(self.peer_pool.peers, batches):
diff --git a/exceptions.py b/exceptions.py
index <HASH>..<HASH> 100644
--- a/exceptions.py
+++ b/exceptions.py
@@ -87,3 +87,10 @@ class RemoteDisconnected(BaseP2PError):
Raised when a remote disconnected.
"""
pass
+
+
+class NoConnectedPeers(BaseP2PError):
+ """
+ Raised when an operation requires a peer connection but we have none.
+ """
+ pass | p2p: Cleanly abort sync if there are no connected peers
Closes #<I> | ethereum_asyncio-cancel-token | train |
82d76ef81b90ed213f9ce3f46d3c97e1322025be | diff --git a/tests/unit/test_main.py b/tests/unit/test_main.py
index <HASH>..<HASH> 100644
--- a/tests/unit/test_main.py
+++ b/tests/unit/test_main.py
@@ -724,14 +724,15 @@ import sys
def test_unsupported_encodings(tmpdir, capsys):
tmp_file = tmpdir.join("file.py")
# fmt: off
- tmp_file.write(
- u'''
+ tmp_file.write_text(
+ '''
# [syntax-error]\
# -*- coding: IBO-8859-1 -*-
""" check correct unknown encoding declaration
"""
__revision__ = 'יייי'
-'''
+''',
+ encoding="utf8"
)
# fmt: on | Fix how unsupported encoding file is created | timothycrosley_isort | train |
1de868a9921db65d979cb271b82014f976b5fb79 | diff --git a/src/main/java/com/sdl/selenium/web/utils/FileUtils.java b/src/main/java/com/sdl/selenium/web/utils/FileUtils.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/sdl/selenium/web/utils/FileUtils.java
+++ b/src/main/java/com/sdl/selenium/web/utils/FileUtils.java
@@ -26,7 +26,7 @@ public class FileUtils {
do {
logger.debug("Content file is empty in: " + time);
time++;
- Utils.sleep(50);
+ Utils.sleep(100);
empty = file.length() > 0;
} while (!empty && time < 100);
return empty;
diff --git a/src/test/functional/java/com/sdl/weblocator/pageObject/PageObjectTest.java b/src/test/functional/java/com/sdl/weblocator/pageObject/PageObjectTest.java
index <HASH>..<HASH> 100644
--- a/src/test/functional/java/com/sdl/weblocator/pageObject/PageObjectTest.java
+++ b/src/test/functional/java/com/sdl/weblocator/pageObject/PageObjectTest.java
@@ -19,7 +19,7 @@ public class PageObjectTest {
for (int i = 0; i < 20; i++) {
pageObject(page);
-// pageSimple(page2);
+ pageSimple(page2);
logger.debug("------------------------------------------");
}
stop();
diff --git a/src/test/functional/java/com/sdl/weblocator/pageObject/SimplePage.java b/src/test/functional/java/com/sdl/weblocator/pageObject/SimplePage.java
index <HASH>..<HASH> 100644
--- a/src/test/functional/java/com/sdl/weblocator/pageObject/SimplePage.java
+++ b/src/test/functional/java/com/sdl/weblocator/pageObject/SimplePage.java
@@ -26,6 +26,6 @@ public class SimplePage {
public void save() {
driver.findElement(By.id("saveButton")).click();
driver.findElement(By.id("close")).click();
-// Utils.sleep(100);
+ Utils.sleep(100);
}
}
diff --git a/src/test/functional/java/com/sdl/weblocator/pageObject/WritePage.java b/src/test/functional/java/com/sdl/weblocator/pageObject/WritePage.java
index <HASH>..<HASH> 100644
--- a/src/test/functional/java/com/sdl/weblocator/pageObject/WritePage.java
+++ b/src/test/functional/java/com/sdl/weblocator/pageObject/WritePage.java
@@ -38,6 +38,6 @@ public class WritePage {
public void save() {
saveButton.click();
close.click();
-// Utils.sleep(100);
+ Utils.sleep(100);
}
} | more time for waitFileIfIsEmpty | sdl_Testy | train |
d3d827c4f8751b99a7e042bd69e5528e0c41bcb6 | diff --git a/packages/@vue/cli-service/lib/webpack/ModernModePlugin.js b/packages/@vue/cli-service/lib/webpack/ModernModePlugin.js
index <HASH>..<HASH> 100644
--- a/packages/@vue/cli-service/lib/webpack/ModernModePlugin.js
+++ b/packages/@vue/cli-service/lib/webpack/ModernModePlugin.js
@@ -25,7 +25,10 @@ class ModernModePlugin {
// get stats, write to disk
await fs.ensureDir(this.targetDir)
const htmlName = path.basename(data.plugin.options.filename)
- const tempFilename = path.join(this.targetDir, `legacy-assets-${htmlName}.json`)
+ // Watch out for output files in sub directories
+ const htmlPath = path.dirname(data.plugin.options.filename)
+ const tempFilename = path.join(this.targetDir, htmlPath, `legacy-assets-${htmlName}.json`)
+ await fs.mkdirp(path.dirname(tempFilename))
await fs.writeFile(tempFilename, JSON.stringify(data.body))
cb()
})
@@ -52,7 +55,9 @@ class ModernModePlugin {
// inject links for legacy assets as <script nomodule>
const htmlName = path.basename(data.plugin.options.filename)
- const tempFilename = path.join(this.targetDir, `legacy-assets-${htmlName}.json`)
+ // Watch out for output files in sub directories
+ const htmlPath = path.dirname(data.plugin.options.filename)
+ const tempFilename = path.join(this.targetDir, htmlPath, `legacy-assets-${htmlName}.json`)
const legacyAssets = JSON.parse(await fs.readFile(tempFilename, 'utf-8'))
.filter(a => a.tagName === 'script' && a.attributes)
legacyAssets.forEach(a => { a.attributes.nomodule = '' }) | fix(build): modern plugin when building multi page applications with output in sub directories (#<I>) | vuejs_vue-cli | train |
7cb8f06e46cccfb67e5d3a73dbc106f385d5dbea | diff --git a/tests/junit/org/jgroups/tests/SharedTransportTest.java b/tests/junit/org/jgroups/tests/SharedTransportTest.java
index <HASH>..<HASH> 100644
--- a/tests/junit/org/jgroups/tests/SharedTransportTest.java
+++ b/tests/junit/org/jgroups/tests/SharedTransportTest.java
@@ -14,7 +14,7 @@ import java.util.List;
/**
* Tests which test the shared transport
* @author Bela Ban
- * @version $Id: SharedTransportTest.java,v 1.6 2008/01/24 07:51:56 belaban Exp $
+ * @version $Id: SharedTransportTest.java,v 1.7 2008/01/25 00:21:45 bstansberry Exp $
*/
public class SharedTransportTest extends ChannelTestBase {
private JChannel a, b, c;
@@ -137,6 +137,44 @@ public class SharedTransportTest extends ChannelTestBase {
Util.sleep(500);
assertEquals(1, r1.size());
}
+
+ /**
+ * Tests that a second channel with the same group name can be
+ * created and connected once the first channel is disconnected.
+ *
+ * @throws Exception
+ */
+ public void testSimpleReCreation() throws Exception {
+ a=createSharedChannel(SINGLETON_1);
+ a.connect("A");
+ a.disconnect();
+ b=createSharedChannel(SINGLETON_1);
+ b.connect("A");
+ }
+
+ /**
+ * Tests that a second channel with the same group name can be
+ * created and connected once the first channel is disconnected even
+ * if 3rd channel with a different group name is still using the shared
+ * transport.
+ *
+ * @throws Exception
+ */
+ public void testReCreationWithSurvivingChannel() throws Exception {
+
+ // Create 2 channels sharing a transport
+ a=createSharedChannel(SINGLETON_1);
+ a.connect("A");
+ b=createSharedChannel(SINGLETON_1);
+ b.connect("B");
+
+ a.disconnect();
+
+ // a is disconnected so we should be able to create a new
+ // channel with group "A"
+ c=createSharedChannel(SINGLETON_1);
+ c.connect("A");
+ } | [JGRP-<I>] Add tests of disconnecting channels and the creating new ones for the same group | belaban_JGroups | train |
3b33c8cf8ebb7bb9f1b734eee3b4ad5e09ded875 | diff --git a/aeron-core/src/main/java/uk/co/real_logic/aeron/conductor/ClientConductor.java b/aeron-core/src/main/java/uk/co/real_logic/aeron/conductor/ClientConductor.java
index <HASH>..<HASH> 100644
--- a/aeron-core/src/main/java/uk/co/real_logic/aeron/conductor/ClientConductor.java
+++ b/aeron-core/src/main/java/uk/co/real_logic/aeron/conductor/ClientConductor.java
@@ -21,13 +21,14 @@ import uk.co.real_logic.aeron.RegistrationException;
import uk.co.real_logic.aeron.Subscription;
import uk.co.real_logic.aeron.util.Agent;
import uk.co.real_logic.aeron.util.BackoffIdleStrategy;
-import uk.co.real_logic.aeron.util.TermHelper;
import uk.co.real_logic.aeron.util.ErrorCode;
+import uk.co.real_logic.aeron.util.TermHelper;
import uk.co.real_logic.aeron.util.collections.ConnectionMap;
import uk.co.real_logic.aeron.util.command.LogBuffersMessageFlyweight;
import uk.co.real_logic.aeron.util.concurrent.AtomicBuffer;
import uk.co.real_logic.aeron.util.concurrent.logbuffer.LogAppender;
import uk.co.real_logic.aeron.util.concurrent.logbuffer.LogReader;
+import uk.co.real_logic.aeron.util.event.EventLogger;
import uk.co.real_logic.aeron.util.protocol.DataHeaderFlyweight;
import uk.co.real_logic.aeron.util.status.BufferPositionIndicator;
import uk.co.real_logic.aeron.util.status.LimitBarrier;
@@ -44,6 +45,8 @@ import static uk.co.real_logic.aeron.util.TermHelper.BUFFER_COUNT;
*/
public class ClientConductor extends Agent implements MediaDriverListener
{
+ private static final EventLogger LOGGER = new EventLogger(ClientConductor.class);
+
private static final int MAX_FRAME_LENGTH = 1024;
public static final long AGENT_IDLE_MAX_SPINS = 5000;
@@ -92,7 +95,15 @@ public class ClientConductor extends Agent implements MediaDriverListener
public int doWork()
{
- return mediaDriverBroadcastReceiver.receive(this, activeCorrelationId);
+ try
+ {
+ return mediaDriverBroadcastReceiver.receive(this, activeCorrelationId);
+ }
+ catch (Exception ex)
+ {
+ LOGGER.logException(ex);
+ return 0;
+ }
}
public void close()
diff --git a/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/MediaConductor.java b/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/MediaConductor.java
index <HASH>..<HASH> 100644
--- a/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/MediaConductor.java
+++ b/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/MediaConductor.java
@@ -129,21 +129,21 @@ public class MediaConductor extends Agent
try
{
workCount += nioSelector.processKeys();
+
+ workCount += publications.doAction(DriverPublication::cleanLogBuffer);
+ workCount += connectedSubscriptions.doAction(DriverConnectedSubscription::cleanLogBuffer);
+ workCount += connectedSubscriptions.doAction(DriverConnectedSubscription::scanForGaps);
+ workCount += connectedSubscriptions.doAction((subscription) -> subscription.sendAnyPendingSm(timerWheel.now()));
+
+ workCount += processFromClientCommandBuffer();
+ workCount += processFromReceiverCommandQueue();
+ workCount += processTimers();
}
catch (final Exception ex)
{
LOGGER.logException(ex);
}
- workCount += publications.doAction(DriverPublication::cleanLogBuffer);
- workCount += connectedSubscriptions.doAction(DriverConnectedSubscription::cleanLogBuffer);
- workCount += connectedSubscriptions.doAction(DriverConnectedSubscription::scanForGaps);
- workCount += connectedSubscriptions.doAction((subscription) -> subscription.sendAnyPendingSm(timerWheel.now()));
-
- workCount += processFromClientCommandBuffer();
- workCount += processFromReceiverCommandQueue();
- workCount += processTimers();
-
return workCount;
}
diff --git a/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/Sender.java b/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/Sender.java
index <HASH>..<HASH> 100644
--- a/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/Sender.java
+++ b/aeron-mediadriver/src/main/java/uk/co/real_logic/aeron/mediadriver/Sender.java
@@ -17,12 +17,16 @@ package uk.co.real_logic.aeron.mediadriver;
import uk.co.real_logic.aeron.util.Agent;
import uk.co.real_logic.aeron.util.concurrent.AtomicArray;
+import uk.co.real_logic.aeron.util.event.EventLogger;
/**
* Agent that iterates over publications for sending them to registered subscribers.
*/
public class Sender extends Agent
{
+
+ private static final EventLogger LOGGER = new EventLogger(Sender.class);
+
private final AtomicArray<DriverPublication> publications;
private int roundRobinIndex = 0;
@@ -35,12 +39,21 @@ public class Sender extends Agent
public int doWork()
{
- roundRobinIndex++;
- if (roundRobinIndex == publications.size())
+ try
{
- roundRobinIndex = 0;
- }
+ roundRobinIndex++;
+ if (roundRobinIndex == publications.size())
+ {
+ roundRobinIndex = 0;
+ }
- return publications.doAction(roundRobinIndex, DriverPublication::send);
+ return publications.doAction(roundRobinIndex, DriverPublication::send);
+ }
+ catch (final Exception ex)
+ {
+ LOGGER.logException(ex);
+ return 0;
+ }
}
+
} | ensure all agents catch and log exceptions at the top level | real-logic_aeron | train |
f640243ee3bf69927179f2f38e6f78d1087f85be | diff --git a/osmdroid-android/src/main/java/org/osmdroid/views/MapView.java b/osmdroid-android/src/main/java/org/osmdroid/views/MapView.java
index <HASH>..<HASH> 100644
--- a/osmdroid-android/src/main/java/org/osmdroid/views/MapView.java
+++ b/osmdroid-android/src/main/java/org/osmdroid/views/MapView.java
@@ -159,6 +159,7 @@ public class MapView extends ViewGroup implements IMapView, MapViewConstants,
: tileRequestCompleteHandler;
mTileProvider = tileProvider;
mTileProvider.setTileRequestCompleteHandler(mTileRequestCompleteHandler);
+ updateTileSizeForDensity(mTileProvider.getTileSource());
this.mMapOverlay = new TilesOverlay(mTileProvider, mResourceProxy);
mOverlayManager = new OverlayManager(mMapOverlay); | Issue #<I> Set the tile size from the constructor using the initial tile source. | osmdroid_osmdroid | train |
fe4c7b012ab329570e85260a13dc646b76592442 | diff --git a/modules/okhttp/src/main/java/dev/failsafe/okhttp/FailsafeCall.java b/modules/okhttp/src/main/java/dev/failsafe/okhttp/FailsafeCall.java
index <HASH>..<HASH> 100644
--- a/modules/okhttp/src/main/java/dev/failsafe/okhttp/FailsafeCall.java
+++ b/modules/okhttp/src/main/java/dev/failsafe/okhttp/FailsafeCall.java
@@ -164,7 +164,10 @@ public final class FailsafeCall {
}
// Propagate cancellation to the call
- ctx.onCancel(call::cancel);
+ ctx.onCancel(() -> {
+ cancelled.set(true);
+ call.cancel();
+ });
return call;
}
}
diff --git a/modules/okhttp/src/test/java/dev/failsafe/okhttp/FailsafeCallTest.java b/modules/okhttp/src/test/java/dev/failsafe/okhttp/FailsafeCallTest.java
index <HASH>..<HASH> 100644
--- a/modules/okhttp/src/test/java/dev/failsafe/okhttp/FailsafeCallTest.java
+++ b/modules/okhttp/src/test/java/dev/failsafe/okhttp/FailsafeCallTest.java
@@ -27,6 +27,7 @@ import org.testng.annotations.Test;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.CancellationException;
+import java.util.concurrent.Future;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.testng.Assert.assertEquals;
@@ -189,6 +190,23 @@ public class FailsafeCallTest extends OkHttpTesting {
assertCalled("/test", 2);
}
+ public void testCancelViaFuture() {
+ // Given
+ mockDelayedResponse(200, "foo", 1000);
+ FailsafeExecutor<Response> failsafe = Failsafe.none();
+ Call call = callFor("/test");
+
+ // When / Then Async
+ FailsafeCall failsafeCall = FailsafeCall.of(call, failsafe);
+ Future<Response> future = failsafeCall.executeAsync();
+ sleep(150);
+ future.cancel(false);
+ assertThrows(future::get, CancellationException.class);
+ assertTrue(call.isCanceled());
+ assertTrue(failsafeCall.isCancelled());
+ assertCalled("/test", 1);
+ }
+
private Call callFor(String path) {
return client.newCall(new Request.Builder().url(URL + path).build());
}
diff --git a/modules/retrofit/src/main/java/dev/failsafe/retrofit/FailsafeCall.java b/modules/retrofit/src/main/java/dev/failsafe/retrofit/FailsafeCall.java
index <HASH>..<HASH> 100644
--- a/modules/retrofit/src/main/java/dev/failsafe/retrofit/FailsafeCall.java
+++ b/modules/retrofit/src/main/java/dev/failsafe/retrofit/FailsafeCall.java
@@ -156,7 +156,10 @@ public final class FailsafeCall<T> {
retrofit2.Call<T> call = ctx.isFirstAttempt() ? initialCall : initialCall.clone();
// Propagate cancellation to the call
- ctx.onCancel(call::cancel);
+ ctx.onCancel(() -> {
+ cancelled.set(true);
+ call.cancel();
+ });
return call;
}
}
diff --git a/modules/retrofit/src/test/java/dev/retrofit/FailsafeCallTest.java b/modules/retrofit/src/test/java/dev/retrofit/FailsafeCallTest.java
index <HASH>..<HASH> 100644
--- a/modules/retrofit/src/test/java/dev/retrofit/FailsafeCallTest.java
+++ b/modules/retrofit/src/test/java/dev/retrofit/FailsafeCallTest.java
@@ -33,6 +33,7 @@ import retrofit2.converter.gson.GsonConverterFactory;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.CancellationException;
+import java.util.concurrent.Future;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.testng.Assert.assertEquals;
@@ -204,6 +205,23 @@ public class FailsafeCallTest extends RetrofitTesting {
assertCalled("/test", 2);
}
+ public void testCancelViaFuture() {
+ // Given
+ mockDelayedResponse(200, "foo", 1000);
+ FailsafeExecutor<Response<User>> failsafe = Failsafe.none();
+ Call<User> call = service.testUser();
+ FailsafeCall<User> failsafeCall = FailsafeCall.of(call, failsafe);
+
+ // When / Then Async
+ Future<Response<User>> future = failsafeCall.executeAsync();
+ sleep(150);
+ future.cancel(false);
+ assertThrows(future::get, CancellationException.class);
+ assertTrue(call.isCanceled());
+ assertTrue(failsafeCall.isCancelled());
+ assertCalled("/test", 1);
+ }
+
private void mockResponse(int responseCode, User body) {
stubFor(get(urlPathEqualTo("/test")).willReturn(
aResponse().withStatus(responseCode).withHeader("Content-Type", "application/json").withBody(gson.toJson(body)))); | Propagate async call future cancellation to FailsafeCall | jhalterman_failsafe | train |
cd48bd2478accbb2638bcfc7e32cb62d3d0ab2cc | diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb
index <HASH>..<HASH> 100644
--- a/activesupport/test/time_zone_test.rb
+++ b/activesupport/test/time_zone_test.rb
@@ -224,9 +224,9 @@ class TimeZoneTest < Test::Unit::TestCase
end
def test_formatted_offset_positive
- zone = ActiveSupport::TimeZone['Moscow']
- assert_equal "+03:00", zone.formatted_offset
- assert_equal "+0300", zone.formatted_offset(false)
+ zone = ActiveSupport::TimeZone['New Delhi']
+ assert_equal "+05:30", zone.formatted_offset
+ assert_equal "+0530", zone.formatted_offset(false)
end
def test_formatted_offset_negative
@@ -257,7 +257,7 @@ class TimeZoneTest < Test::Unit::TestCase
end
def test_to_s
- assert_equal "(GMT+03:00) Moscow", ActiveSupport::TimeZone['Moscow'].to_s
+ assert_equal "(GMT+05:30) New Delhi", ActiveSupport::TimeZone['New Delhi'].to_s
end
def test_all_sorted | Using not effected timezone in tests. | rails_rails | train |
b62f422394bae86b14092b0a404b2630a6c6df83 | diff --git a/p2p/host/peerstore/addr_manager.go b/p2p/host/peerstore/addr_manager.go
index <HASH>..<HASH> 100644
--- a/p2p/host/peerstore/addr_manager.go
+++ b/p2p/host/peerstore/addr_manager.go
@@ -12,7 +12,7 @@ import (
ma "github.com/multiformats/go-multiaddr"
)
-const (
+var (
// TempAddrTTL is the ttl used for a short lived address
TempAddrTTL = time.Second * 10
@@ -30,7 +30,8 @@ const (
OwnObservedAddrTTL = time.Minute * 10
)
-// Permanent TTLs (distinct so we can distinguish between them)
+// Permanent TTLs (distinct so we can distinguish between them, constant as they
+// are, in fact, permanent)
const (
// PermanentAddrTTL is the ttl for a "permanent address" (e.g. bootstrap nodes).
PermanentAddrTTL = math.MaxInt64 - iota | make it possible to modify non-permanent TTLs
useful for testing, at the very least. | libp2p_go-libp2p | train |
2c56424e2d1ad02290a44ab15ce980b1a5204ed2 | diff --git a/photini/configstore.py b/photini/configstore.py
index <HASH>..<HASH> 100644
--- a/photini/configstore.py
+++ b/photini/configstore.py
@@ -23,7 +23,7 @@ import appdirs
from PyQt4 import QtCore
class ConfigStore(object):
- def __init__(self):
+ def __init__(self, name):
self.config = SafeConfigParser()
if hasattr(appdirs, 'user_config_dir'):
data_dir = appdirs.user_config_dir('Photini')
@@ -31,12 +31,13 @@ class ConfigStore(object):
data_dir = appdirs.user_data_dir('Photini')
if not os.path.isdir(data_dir):
os.makedirs(data_dir, mode=0700)
- self.file_name = os.path.join(data_dir, 'photini.ini')
- old_file_name = os.path.expanduser('~/photini.ini')
- if os.path.exists(old_file_name):
- self.config.read(old_file_name)
- self.save()
- os.unlink(old_file_name)
+ self.file_name = os.path.join(data_dir, '%s.ini' % name)
+ for old_file_name in (os.path.expanduser('~/photini.ini'),
+ os.path.join(data_dir, 'photini.ini')):
+ if os.path.exists(old_file_name):
+ self.config.read(old_file_name)
+ self.save()
+ os.unlink(old_file_name)
self.config.read(self.file_name)
self.timer = QtCore.QTimer()
self.timer.setSingleShot(True)
diff --git a/photini/editor.py b/photini/editor.py
index <HASH>..<HASH> 100755
--- a/photini/editor.py
+++ b/photini/editor.py
@@ -66,7 +66,7 @@ class MainWindow(QtGui.QMainWindow):
self.loggerwindow = LoggerWindow(verbose)
self.logger = logging.getLogger(self.__class__.__name__)
# config store
- self.config_store = ConfigStore()
+ self.config_store = ConfigStore('editor')
# set network proxy
proxies = urllib2.getproxies()
if 'http' in proxies:
diff --git a/photini/version.py b/photini/version.py
index <HASH>..<HASH> 100644
--- a/photini/version.py
+++ b/photini/version.py
@@ -1,3 +1,3 @@
-version = '14.03.dev44'
-release = '44'
-commit = '074f3a7'
+version = '14.04.dev45'
+release = '45'
+commit = '008df50' | Changed name of config file. | jim-easterbrook_Photini | train |
61a12193952d2e4d43c8d61e22261565f016d5e8 | diff --git a/sonnet/src/adam.py b/sonnet/src/adam.py
index <HASH>..<HASH> 100644
--- a/sonnet/src/adam.py
+++ b/sonnet/src/adam.py
@@ -103,7 +103,6 @@ class Adam(base.Module):
self._initialize(parameters)
self.step.assign_add(1)
for update, parameter, m, v in zip(updates, parameters, self.m, self.v):
- # TODO(petebu): Consider caching learning_rate cast.
# TODO(petebu): Consider the case when all updates are None.
if update is not None:
optimizer_utils.check_same_dtype(update, parameter)
@@ -168,7 +167,6 @@ class FastAdam(base.Module):
self._initialize(parameters)
self.step.assign_add(1)
for update, parameter, m, v in zip(updates, parameters, self.m, self.v):
- # TODO(petebu): Consider caching learning_rate cast.
# TODO(petebu): Consider the case when all updates are None.
if update is not None:
optimizer_utils.check_same_dtype(update, parameter)
diff --git a/sonnet/src/momentum.py b/sonnet/src/momentum.py
index <HASH>..<HASH> 100644
--- a/sonnet/src/momentum.py
+++ b/sonnet/src/momentum.py
@@ -87,7 +87,6 @@ class Momentum(base.Module):
self._initialize(parameters)
for update, parameter, momentum in zip(
updates, parameters, self.accumulated_momentum):
- # TODO(petebu): Consider caching learning_rate cast.
# TODO(petebu): Consider the case when all updates are None.
if update is not None:
optimizer_utils.check_same_dtype(update, parameter)
@@ -137,7 +136,6 @@ class FastMomentum(base.Module):
self._initialize(parameters)
for update, parameter, accumulated_momentum in zip(
updates, parameters, self.accumulated_momentum):
- # TODO(petebu): Consider caching learning_rate cast.
# TODO(petebu): Consider the case when all updates are None.
if update is not None:
optimizer_utils.check_same_dtype(update, parameter)
diff --git a/sonnet/src/rmsprop.py b/sonnet/src/rmsprop.py
index <HASH>..<HASH> 100644
--- a/sonnet/src/rmsprop.py
+++ b/sonnet/src/rmsprop.py
@@ -114,7 +114,6 @@ class RMSProp(base.Module):
self._initialize(parameters)
for update, parameter, mom, ms, mg in six.moves.zip_longest(
updates, parameters, self.mom, self.ms, self.mg):
- # TODO(petebu): Consider caching learning_rate cast.
# TODO(petebu): Consider the case when all updates are None.
if update is not None:
optimizer_utils.check_same_dtype(update, parameter)
@@ -185,7 +184,6 @@ class FastRMSProp(base.Module):
self._initialize(parameters)
for update, parameter, mom, ms, mg in six.moves.zip_longest(
updates, parameters, self.mom, self.ms, self.mg):
- # TODO(petebu): Consider caching learning_rate cast.
# TODO(petebu): Consider the case when all updates are None.
if update is not None:
optimizer_utils.check_same_dtype(update, parameter)
diff --git a/sonnet/src/sgd.py b/sonnet/src/sgd.py
index <HASH>..<HASH> 100644
--- a/sonnet/src/sgd.py
+++ b/sonnet/src/sgd.py
@@ -56,7 +56,6 @@ class SGD(base.Module):
"""
optimizer_utils.check_updates_parameters(updates, parameters)
for update, parameter in zip(updates, parameters):
- # TODO(petebu): Consider caching learning_rate cast.
# TODO(petebu): Consider the case when all updates are None.
if update is not None:
optimizer_utils.check_same_dtype(update, parameter)
@@ -80,7 +79,6 @@ class FastSGD(base.Module):
"""Applies updates to parameters."""
optimizer_utils.check_updates_parameters(updates, parameters)
for update, parameter in zip(updates, parameters):
- # TODO(petebu): Consider caching learning_rate cast.
# TODO(petebu): Consider the case when all updates are None.
if update is not None:
optimizer_utils.check_same_dtype(update, parameter) | Remove TODO for caching casts. These are all scalars so the casts cost little.
PiperOrigin-RevId: <I>
Change-Id: I<I>d<I>d<I>ff<I>a<I>c<I>c<I>ebefd1 | deepmind_sonnet | train |
42f3aa3208a1e02bce77091ef651e26a06f1fadc | diff --git a/Tank/Plugins/Aggregator.py b/Tank/Plugins/Aggregator.py
index <HASH>..<HASH> 100644
--- a/Tank/Plugins/Aggregator.py
+++ b/Tank/Plugins/Aggregator.py
@@ -359,6 +359,7 @@ class AbstractReader:
def pop_second(self):
''' pop from out queue new aggregate data item '''
+ self.data_queue.sort()
next_time = self.data_queue.pop(0)
data = self.data_buffer[next_time]
del self.data_buffer[next_time] | sort seconds buffer in aggregator before popping | yandex_yandex-tank | train |
5968dccc4c3da027c806b394181222f551ea3bc3 | diff --git a/src/js/select2/i18n/fr.js b/src/js/select2/i18n/fr.js
index <HASH>..<HASH> 100644
--- a/src/js/select2/i18n/fr.js
+++ b/src/js/select2/i18n/fr.js
@@ -8,20 +8,20 @@ define(function () {
var overChars = args.input.length - args.maximum;
return 'Supprimez ' + overChars + ' caractère' +
- (overChars > 1) ? 's' : '';
+ ((overChars > 1) ? 's' : '');
},
inputTooShort: function (args) {
var remainingChars = args.minimum - args.input.length;
return 'Saisissez au moins ' + remainingChars + ' caractère' +
- (remainingChars > 1) ? 's' : '';
+ ((remainingChars > 1) ? 's' : '');
},
loadingMore: function () {
return 'Chargement de résultats supplémentaires…';
},
maximumSelected: function (args) {
return 'Vous pouvez seulement sélectionner ' + args.maximum +
- ' élément' + (args.maximum > 1) ? 's' : '';
+ ' élément' + ((args.maximum > 1) ? 's' : '');
},
noResults: function () {
return 'Aucun résultat trouvé'; | Fix pluralization (#<I>)
The test return always 's' in translations : inputTooLong, inputTooShort, maximumSelected | select2_select2 | train |
5565d315dad31df9861ada7f6a5bc8addd4fbc00 | diff --git a/contribs/gmf/src/authentication/module.js b/contribs/gmf/src/authentication/module.js
index <HASH>..<HASH> 100644
--- a/contribs/gmf/src/authentication/module.js
+++ b/contribs/gmf/src/authentication/module.js
@@ -3,7 +3,6 @@
*/
goog.provide('gmf.authentication.module');
-goog.require('gmf');
goog.require('gmf.authentication.component');
goog.require('gmf.authentication.service'); | Don't require gmf, like in search module | camptocamp_ngeo | train |
afc21eb29cbbfa6848d70d2dca2224a69162ca80 | diff --git a/src/Illuminate/Redis/Limiters/DurationLimiterBuilder.php b/src/Illuminate/Redis/Limiters/DurationLimiterBuilder.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Redis/Limiters/DurationLimiterBuilder.php
+++ b/src/Illuminate/Redis/Limiters/DurationLimiterBuilder.php
@@ -73,7 +73,7 @@ class DurationLimiterBuilder
/**
* Set the amount of time the lock window is maintained.
*
- * @param int $decay
+ * @param \DateTimeInterface|\DateInterval|int $decay
* @return $this
*/
public function every($decay) | fix PHPdoc for decay param (#<I>) | laravel_framework | train |
0c4045df36614966f094a59c1a70d044fd25e94c | diff --git a/leaflet_storage/templatetags/leaflet_storage_tags.py b/leaflet_storage/templatetags/leaflet_storage_tags.py
index <HASH>..<HASH> 100644
--- a/leaflet_storage/templatetags/leaflet_storage_tags.py
+++ b/leaflet_storage/templatetags/leaflet_storage_tags.py
@@ -24,7 +24,7 @@ def leaflet_storage_js(locale=None):
@register.inclusion_tag('leaflet_storage/map_fragment.html')
-def map_fragment(map_instance):
+def map_fragment(map_instance, **kwargs):
layers = DataLayer.objects.filter(map=map_instance)
datalayer_data = [c.metadata for c in layers]
tilelayers = TileLayer.get_list() # TODO: no need to all
@@ -51,6 +51,7 @@ def map_fragment(map_instance):
'displayCaptionOnLoad': False,
'default_iconUrl': "%sstorage/src/img/marker.png" % settings.STATIC_URL,
})
+ map_settings['properties'].update(kwargs)
return {
"map_settings": simplejson.dumps(map_settings),
"map": map_instance | Allow to override options in map_fragment | umap-project_django-leaflet-storage | train |
3671cc7f27130ecd468a04bc27c7554382d6f3fa | diff --git a/lfs/transfer_queue.go b/lfs/transfer_queue.go
index <HASH>..<HASH> 100644
--- a/lfs/transfer_queue.go
+++ b/lfs/transfer_queue.go
@@ -224,15 +224,14 @@ func (q *TransferQueue) batchApiRoutine() {
startProgress.Do(q.meter.Start)
for _, o := range objects {
- if _, ok := o.Rel(q.transferKind); ok {
- // This object has an error
- if o.Error != nil {
- q.errorc <- Error(o.Error)
- q.meter.Skip(o.Size)
- q.wait.Done()
- continue
- }
+ if o.Error != nil {
+ q.errorc <- Error(o.Error)
+ q.meter.Skip(o.Size)
+ q.wait.Done()
+ continue
+ }
+ if _, ok := o.Rel(q.transferKind); ok {
// This object needs to be transferred
if transfer, ok := q.transferables[o.Oid]; ok {
transfer.SetObject(o) | check for errors before checking for a link action | git-lfs_git-lfs | train |
31e145936b6648e309e232c4ed5a4936999cee75 | diff --git a/closure/goog/labs/testing/environment.js b/closure/goog/labs/testing/environment.js
index <HASH>..<HASH> 100644
--- a/closure/goog/labs/testing/environment.js
+++ b/closure/goog/labs/testing/environment.js
@@ -107,10 +107,10 @@ goog.labs.testing.Environment = goog.defineClass(null, {
this.mockControl.$verifyAll();
} finally {
this.mockControl.$resetAll();
- }
- if (this.shouldMakeMockControl_) {
- // If we created the mockControl, we'll also tear it down.
- this.mockControl.$tearDown();
+ if (this.shouldMakeMockControl_) {
+ // If we created the mockControl, we'll also tear it down.
+ this.mockControl.$tearDown();
+ }
}
}
// Verifying the mockControl may throw, so if cleanup needs to happen, | Move tearDown to be invoked in finally block, so that it executes even if there is an exception during verifying or replaying all.
-------------
Created by MOE: <URL> | google_closure-library | train |
97310190550f224bdc6a94023d4108288775f336 | diff --git a/presto-main/src/main/java/com/facebook/presto/sql/gen/CommonSubExpressionRewriter.java b/presto-main/src/main/java/com/facebook/presto/sql/gen/CommonSubExpressionRewriter.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/sql/gen/CommonSubExpressionRewriter.java
+++ b/presto-main/src/main/java/com/facebook/presto/sql/gen/CommonSubExpressionRewriter.java
@@ -35,6 +35,7 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
+import static com.facebook.presto.spi.relation.SpecialFormExpression.Form.BIND;
import static com.facebook.presto.spi.relation.SpecialFormExpression.Form.WHEN;
import static com.facebook.presto.sql.relational.Expressions.subExpressions;
import static com.google.common.collect.ImmutableList.toImmutableList;
@@ -382,7 +383,8 @@ public class CommonSubExpressionRewriter
public Integer visitSpecialForm(SpecialFormExpression specialForm, Void collect)
{
int level = specialForm.getArguments().stream().map(argument -> argument.accept(this, null)).reduce(Math::max).get() + 1;
- if (specialForm.getForm() != WHEN) {
+ if (specialForm.getForm() != WHEN && specialForm.getForm() != BIND) {
+ // BIND returns a function type rather than a value type
// WHEN is part of CASE expression. We do not have a separate code generator to generate code for WHEN expression separately so do not consider them as CSE
// TODO If we detect a whole WHEN statement as CSE we should probably only keep one
addAtLevel(level, specialForm); | Skip BIND in common sub-expression extraction
BIND returns a function type rather than a value type so it's not
suitable for common sub-expression optimization. | prestodb_presto | train |
e46a96a26c2c7a89bc4144d7ee5af61e508efa21 | diff --git a/telemetry/telemetry/unittest/tab_test_case.py b/telemetry/telemetry/unittest/tab_test_case.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/unittest/tab_test_case.py
+++ b/telemetry/telemetry/unittest/tab_test_case.py
@@ -29,6 +29,7 @@ class TabTestCase(unittest.TestCase):
self._browser.Start()
self._tab = self._browser.tabs[0]
self._tab.Navigate('about:blank')
+ self._tab.WaitForDocumentReadyStateToBeInteractiveOrBetter()
except:
self.tearDown() | [telemetry] Attempt to fix testActivateTab.
The test immediately checks for document visible. It might not be true because the page hasn't finished loading yet. So we should just wait for it.
BUG=<I>
TEST=tools/telemetry/run_tests testActivateTab # Though this isn't a <I>% test, since the flakiness was rare and Windows-only.
TBR=tonyg
Review URL: <URL> | catapult-project_catapult | train |
c81854c4439fc273700e2da670d631c380ff21e4 | diff --git a/lib/AssetGraph.js b/lib/AssetGraph.js
index <HASH>..<HASH> 100644
--- a/lib/AssetGraph.js
+++ b/lib/AssetGraph.js
@@ -129,17 +129,16 @@ class AssetGraph extends EventEmitter {
*
* Add an asset to the graph.
*
- * @param {Asset} asset The asset to add.
- * @return {AssetGraph} The AssetGraph instance (chaining-friendly).
- * @api public
+ * @param {Asset|String|Object} The asset (or spec) to add
+ * @return {Asset[]} The assets instances that were added
*/
add(asset) {
if (Array.isArray(asset)) {
- return asset.map(asset => this.addAsset(asset));
+ return _.flatten(asset.map(asset => this.addAsset(asset)));
} else if (typeof asset === 'string' && !/^[a-zA-Z-\+]+:/.test(asset) && asset.includes('*')) {
- return glob
+ return _.flatten(glob
.sync(pathModule.resolve(this.root ? urlTools.fileUrlToFsPath(this.root) : process.cwd(), asset))
- .map(path => this.addAsset(encodeURI(`file://${path}`)));
+ .map(path => this.addAsset(encodeURI(`file://${path}`))));
}
if (!asset.isAsset) {
asset = this.createAsset(asset);
@@ -152,7 +151,7 @@ class AssetGraph extends EventEmitter {
this.emit('addAsset', asset);
asset.populate();
}
- return asset;
+ return [ asset ];
}
addAsset(...args) {
diff --git a/lib/transforms/loadAssets.js b/lib/transforms/loadAssets.js
index <HASH>..<HASH> 100644
--- a/lib/transforms/loadAssets.js
+++ b/lib/transforms/loadAssets.js
@@ -6,14 +6,13 @@ module.exports = function () { // ...
var flattenedArguments = _.flatten(arguments);
return async function loadAssets(assetGraph) {
await Promise.map(_.flatten(flattenedArguments), async assetConfig => {
- if (typeof assetConfig === 'string') {
- assetConfig = { url: assetConfig };
- }
- if (typeof assetConfig.isInitial === 'undefined') {
- assetConfig.isInitial = true;
- }
try {
- await assetGraph.addAsset(assetConfig).load();
+ for (const asset of assetGraph.addAsset(assetConfig)) {
+ await asset.load();
+ if (typeof asset.isInitial === 'undefined') {
+ asset.isInitial = true;
+ }
+ }
} catch (err) {
assetGraph.warn(err);
}
diff --git a/test/add.js b/test/add.js
index <HASH>..<HASH> 100644
--- a/test/add.js
+++ b/test/add.js
@@ -67,7 +67,7 @@ describe('AssetGraph#add', function () {
describe('with an asset config that does not include the body', function () {
it('should add the targets of all external outgoing relations as unloaded Asset instances once the asset is loaded', async function () {
const assetGraph = new AssetGraph();
- const cssAsset = assetGraph.addAsset({
+ const [ cssAsset ] = assetGraph.addAsset({
type: 'Css',
url: 'https://example.com/styles.css'
});
@@ -95,7 +95,7 @@ describe('AssetGraph#add', function () {
describe('when the url already exists in the graph', function () {
it('should return the existing instance', function () {
const assetGraph = new AssetGraph();
- const cssAsset = assetGraph.addAsset({
+ const [ cssAsset ] = assetGraph.addAsset({
type: 'Css',
url: 'https://example.com/styles.css',
text: 'body { color: teal; }'
diff --git a/test/assets/Asset.js b/test/assets/Asset.js
index <HASH>..<HASH> 100644
--- a/test/assets/Asset.js
+++ b/test/assets/Asset.js
@@ -527,8 +527,6 @@ describe('assets/Asset', function () {
expect(assetGraph, 'to contain relation', 'HtmlAnchor');
- expect(assetGraph.findRelations({type: 'CssImage'}, true).length - assetGraph.findRelations({type: 'CssImage'}).length, 'to equal', 1);
-
const fooHtml = assetGraph.findAssets({url: /\/foo\.html$/})[0];
fooHtml.text = '<!DOCTYPE html>\n<html><head></head><body><a href="baz.html">Another link text</a></body></html>'; | WIP, simplify loadAssets further, always return an array from addAsset
<I> failing [ci skip] | assetgraph_assetgraph | train |
b75e569cdf09a45d5852f5484f63b394d3fd4d20 | diff --git a/test/ginkgo-ext/scopes.go b/test/ginkgo-ext/scopes.go
index <HASH>..<HASH> 100644
--- a/test/ginkgo-ext/scopes.go
+++ b/test/ginkgo-ext/scopes.go
@@ -62,6 +62,7 @@ var (
FIt = wrapItFunc(ginkgo.FIt, true)
PIt = ginkgo.PIt
XIt = ginkgo.XIt
+ Measure = ginkgo.Measure
By = ginkgo.By
JustBeforeEach = ginkgo.JustBeforeEach
BeforeSuite = ginkgo.BeforeSuite | Ginkgo: Add Measure in Ginkgo-ext | cilium_cilium | train |
7d7cbef7e6c618bde4e6f3595039a9d2cc858523 | diff --git a/lib/attachinary/orm/base_extension.rb b/lib/attachinary/orm/base_extension.rb
index <HASH>..<HASH> 100644
--- a/lib/attachinary/orm/base_extension.rb
+++ b/lib/attachinary/orm/base_extension.rb
@@ -39,6 +39,23 @@ module Attachinary
options
end
+ if options[:single]
+ # def photo_url=(url)
+ # ...
+ # end
+ define_method :"#{options[:scope]}_url=" do |url|
+ send(:"#{options[:scope]}=", Cloudinary::Uploader.upload(url))
+ end
+
+ else
+ # def image_urls=(urls)
+ # ...
+ # end
+ define_method :"#{options[:singular]}_urls=" do |urls|
+ send(:"#{options[:scope]}=", urls.map { |url| Cloudinary::Uploader.upload(url) })
+ end
+ end
+
end
end
diff --git a/spec/models/note_spec.rb b/spec/models/note_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/note_spec.rb
+++ b/spec/models/note_spec.rb
@@ -40,6 +40,21 @@ describe Note do
end
end
+ describe '#photo_url=(url)' do
+ let(:url) { "http://placehold.it/100x100" }
+ let(:file) { build(:file) }
+ let(:json) { file.attributes.to_json }
+
+ before do
+ Cloudinary::Uploader.should_receive(:upload).with(url).and_return(json)
+ end
+
+ it 'uploads photo via url' do
+ subject.photo_url = url
+ subject.photo.public_id.should == file.public_id
+ end
+ end
+
describe '#photo?' do
it 'checks whether photo is present' do
subject.photo?.should be_true
@@ -81,6 +96,22 @@ describe Note do
end
end
+ describe '#image_urls=(urls)' do
+ let(:urls) { %w[ 1 2 3 ] }
+ let(:files) { build_list(:file, urls.length) }
+
+ before do
+ files.each.with_index do |file, index|
+ Cloudinary::Uploader.should_receive(:upload).with(urls[index]).and_return(file.attributes)
+ end
+ end
+
+ it 'upload photos via urls' do
+ subject.image_urls = urls
+ subject.images.map(&:public_id).should =~ files.map(&:public_id)
+ end
+ end
+
describe '#images_metadata' do
it 'returns association metadata' do
subject.images_metadata[:single].should == false | allowing uploads by urls | assembler_attachinary | train |
460dafbc86c03a72008e93a29fbee02b61e86ba2 | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -142,7 +142,7 @@ Arguments:
* `path` (string, mandatory): the path for this repo
* `options` (object, optional): may contain the following values
- * `lock` (string *Deprecated* or [Lock](#lock)), string can be `"fs"` or `"memory"`: what type of lock to use. Lock has to be acquired when opening.
+ * `lock` ([Lock](#lock) or string *Deprecated*): what type of lock to use. Lock has to be acquired when opening. string can be `"fs"` or `"memory"`.
* `storageBackends` (object, optional): may contain the following values, which should each be a class implementing the [datastore interface](https://github.com/ipfs/interface-datastore#readme):
* `root` (defaults to [`datastore-fs`](https://github.com/ipfs/js-datastore-fs#readme) in Node.js and [`datastore-level`](https://github.com/ipfs/js-datastore-level#readme) in the browser). Defines the back-end type used for gets and puts of values at the root (`repo.set()`, `repo.get()`)
* `blocks` (defaults to [`datastore-fs`](https://github.com/ipfs/js-datastore-fs#readme) in Node.js and [`datastore-level`](https://github.com/ipfs/js-datastore-level#readme) in the browser). Defines the back-end type used for gets and puts of values at `repo.blocks`.
@@ -302,12 +302,14 @@ IPFS Repo comes with two built in locks: memory and fs. These can be imported vi
```js
const fsLock = require('ipfs-repo/src/lock') // Default in Node.js
-const memLock = require('ipfs-repo/src/lock-memory') // Default in browser
+const memoryLock = require('ipfs-repo/src/lock-memory') // Default in browser
```
-#### `lock.open (dir, callback)`
+You can also provide your own custom Lock. It must be an object with the following interface:
-Sets the lock if one does not already exist.
+#### `lock.lock (dir, callback)`
+
+Sets the lock if one does not already exist. If a lock already exists, `callback` should be called with an error.
`dir` is a string to the directory the lock should be created at. The repo typically creates the lock at its root.
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -159,7 +159,14 @@ class IpfsRepo {
* @returns {void}
*/
_openLock (path, callback) {
- this._locker.lock(path, callback)
+ this._locker.lock(path, (err, lockfile) => {
+ if (err) {
+ return callback(err, null)
+ }
+
+ assert.equal(typeof lockfile.close, 'function', 'Locks must have a close method')
+ callback(null, lockfile)
+ })
}
/**
diff --git a/test/options-test.js b/test/options-test.js
index <HASH>..<HASH> 100644
--- a/test/options-test.js
+++ b/test/options-test.js
@@ -29,7 +29,7 @@ describe('custom options tests', () => {
expect(repo.options).to.deep.equal(expectedRepoOptions())
})
- it('allows for a custom locker', () => {
+ it('allows for a custom lock', () => {
const lock = {
lock: (path, callback) => { },
locked: (path, callback) => { }
@@ -41,6 +41,23 @@ describe('custom options tests', () => {
expect(repo._getLocker()).to.deep.equal(lock)
})
+
+ it('ensures a custom lock has a .close method', (done) => {
+ const lock = {
+ lock: (path, callback) => {
+ callback(null, {})
+ }
+ }
+
+ const repo = new Repo(repoPath, {
+ lock
+ })
+
+ expect(
+ () => repo._openLock(repo.path)
+ ).to.throw('Locks must have a close method')
+ done()
+ })
})
function noop () {} | docs: update docs to be clearer
Ensure locks have a close method when creating the lock | ipfs_js-ipfs-repo | train |
f3dd60bf0d5e0b9421d107ea76ef5534e44d16a7 | diff --git a/lib/core/abstract_jdl_application.js b/lib/core/abstract_jdl_application.js
index <HASH>..<HASH> 100644
--- a/lib/core/abstract_jdl_application.js
+++ b/lib/core/abstract_jdl_application.js
@@ -19,9 +19,9 @@
const ApplicationOptions = require('./jhipster/application_options');
const mergeObjects = require('../utils/object_utils').merge;
-const CustomSet = require('../utils/objects/custom_set');
const { COUCHBASE, CASSANDRA, MONGODB } = require('./jhipster/database_types');
const ApplicationErrorCases = require('../exceptions/error_cases').ErrorCases.applications;
+const { join } = require('../utils/set_utils');
class AbstractJDLApplication {
constructor(args) {
@@ -52,7 +52,7 @@ class AbstractJDLApplication {
this.config.devDatabaseType = this.config.databaseType;
this.config.prodDatabaseType = this.config.databaseType;
}
- this.entityNames = new CustomSet(args.entities);
+ this.entityNames = new Set(args.entities);
}
static checkValidity(application) {
@@ -97,7 +97,7 @@ class AbstractJDLApplication {
toString() {
let stringifiedApplication = `application {\n${stringifyConfig(this.config)}\n`;
if (this.entityNames.size !== 0) {
- stringifiedApplication = `\n entities ${this.entityNames.join(', ')}\n`;
+ stringifiedApplication = `\n entities ${join(this.entityNames, ', ')}\n`;
}
stringifiedApplication += '}';
return stringifiedApplication;
@@ -109,7 +109,7 @@ function generateConfigObject(passedConfig) {
Object.keys(passedConfig).forEach(option => {
const value = passedConfig[option];
if (Array.isArray(value) && (option === 'languages' || option === 'testFrameworks')) {
- config[option] = new CustomSet(value);
+ config[option] = new Set(value);
} else {
config[option] = value;
}
@@ -130,7 +130,7 @@ function stringifyOptionValue(name, value) {
if (value.size === 0) {
return ' []';
}
- return ` [${value.join(', ')}]`;
+ return ` [${join(value, ', ')}]`;
}
if (value === null || value === undefined) {
return '';
diff --git a/test/spec/core/abstract_jdl_application_test.js b/test/spec/core/abstract_jdl_application_test.js
index <HASH>..<HASH> 100644
--- a/test/spec/core/abstract_jdl_application_test.js
+++ b/test/spec/core/abstract_jdl_application_test.js
@@ -131,7 +131,7 @@ describe('AbstractJDLApplication', () => {
});
it('returns the entity list', () => {
- expect(result.toString()).to.equal('[A,B]');
+ expect(result).to.deep.equal(new Set(['A', 'B']));
});
});
}); | Replaced use of the CustomSet in the JDL applications in favor of the SetUtils functions | jhipster_jhipster-core | train |
87c22187a988558ebe048f6caea56c1a03ee7513 | diff --git a/session.go b/session.go
index <HASH>..<HASH> 100644
--- a/session.go
+++ b/session.go
@@ -496,6 +496,7 @@ runLoop:
putPacketBuffer(&p.header.Raw)
case p := <-s.paramsChan:
s.processTransportParameters(&p)
+ continue
case _, ok := <-s.handshakeEvent:
// when the handshake is completed, the channel will be closed
s.handleHandshakeEvent(!ok) | don't send a packet after receiving the transport parameters | lucas-clemente_quic-go | train |
bf3f1c19cd3af2da536ec75e42a210c9f71abac4 | diff --git a/lib/plsql/oci_connection.rb b/lib/plsql/oci_connection.rb
index <HASH>..<HASH> 100644
--- a/lib/plsql/oci_connection.rb
+++ b/lib/plsql/oci_connection.rb
@@ -194,8 +194,7 @@ module PLSQL
end
when :"OCI8::CLOB", :"OCI8::BLOB"
# ruby-oci8 cannot create CLOB/BLOB from ''
- value = nil if value == ''
- type.new(raw_oci_connection, value)
+ value.to_s.length > 0 ? type.new(raw_oci_connection, value) : nil
when :"OCI8::Cursor"
value && value.raw_cursor
else
diff --git a/spec/plsql/procedure_spec.rb b/spec/plsql/procedure_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/plsql/procedure_spec.rb
+++ b/spec/plsql/procedure_spec.rb
@@ -466,10 +466,34 @@ describe "Parameter type mapping /" do
RETURN p_clob;
END test_clob;
SQL
+ plsql.execute "CREATE TABLE test_clob_table (clob_col CLOB)"
+ plsql.execute <<-SQL
+ CREATE OR REPLACE FUNCTION test_clob_insert
+ ( p_clob CLOB )
+ RETURN CLOB
+ IS
+ CURSOR clob_cur IS
+ SELECT clob_col
+ FROM test_clob_table;
+
+ v_dummy CLOB;
+ BEGIN
+ DELETE FROM test_clob_table;
+ INSERT INTO test_clob_table (clob_col) VALUES (p_clob);
+
+ OPEN clob_cur;
+ FETCH clob_cur INTO v_dummy;
+ CLOSE clob_cur;
+
+ RETURN v_dummy;
+ END test_clob_insert;
+ SQL
end
after(:all) do
plsql.execute "DROP FUNCTION test_clob"
+ plsql.execute "DROP FUNCTION test_clob_insert"
+ plsql.execute "DROP TABLE test_clob_table"
end
it "should find existing procedure" do
@@ -487,6 +511,11 @@ describe "Parameter type mapping /" do
text = ''
plsql.test_clob(text).should be_nil
end
+
+ it "should execute function which inserts the CLOB parameter into a table with empty string and return nil" do
+ text = ''
+ plsql.test_clob_insert(text).should be_nil
+ end
else
@@ -501,6 +530,10 @@ describe "Parameter type mapping /" do
plsql.test_clob(nil).should be_nil
end
+ it "should execute function which inserts the CLOB parameter into a table with nil and return nil" do
+ plsql.test_clob_insert(nil).should be_nil
+ end
+
end
describe "Procedrue with CLOB parameter and return value" do | correction to ruby_value_to_ora_value when type is OCI8::CLOB | rsim_ruby-plsql | train |
8d57ec980e59aead2a82ffa0f68809b87070c040 | diff --git a/src/Json/JsonFormatter.php b/src/Json/JsonFormatter.php
index <HASH>..<HASH> 100644
--- a/src/Json/JsonFormatter.php
+++ b/src/Json/JsonFormatter.php
@@ -3,7 +3,7 @@
/**
* This file is part of phpcq/author-validation.
*
- * (c) 2014 Christian Schiffler, Tristan Lins
+ * (c) 2014-2018 Christian Schiffler, Tristan Lins
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -15,7 +15,8 @@
* @author Jordi Boggiano <[email protected]>
* @author Christian Schiffler <[email protected]>
* @author Tristan Lins <[email protected]>
- * @copyright 2014-2016 Christian Schiffler <[email protected]>, Tristan Lins <[email protected]>
+ * @author Sven Baumann <[email protected]>
+ * @copyright 2014-2018 Christian Schiffler <[email protected]>, Tristan Lins <[email protected]>
* @license https://github.com/phpcq/author-validation/blob/master/LICENSE MIT
* @link https://github.com/phpcq/author-validation
* @filesource
@@ -53,107 +54,18 @@ class JsonFormatter
*/
public static function format($data)
{
- if (version_compare(PHP_VERSION, '5.4', '>=')) {
- // This is:
- // JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
- $json = json_encode($data, 448);
- // compact brackets to follow recent php versions
- if (PHP_VERSION_ID < 50428
- || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50512)
- || (defined('JSON_C_VERSION') && version_compare(phpversion('json'), '1.3.6', '<'))
- ) {
- $json = preg_replace('/\[\s+\]/', '[]', $json);
- $json = preg_replace('/\{\s+\}/', '{}', $json);
- }
- return $json;
+ // This is:
+ // JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
+ $json = \json_encode($data, 448);
+ // compact brackets to follow recent php versions
+ if (PHP_VERSION_ID < 50428
+ || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50512)
+ || (\defined('JSON_C_VERSION') && \version_compare(\phpversion('json'), '1.3.6', '<'))
+ ) {
+ $json = \preg_replace('/\[\s+\]/', '[]', $json);
+ $json = \preg_replace('/\{\s+\}/', '{}', $json);
}
- $json = json_encode($data);
-
- $result = '';
- $pos = 0;
- $strLen = strlen($json);
- $indentStr = ' ';
- $newLine = "\n";
- $outOfQuotes = true;
- $buffer = '';
- $noescape = true;
-
- for ($i = 0; $i < $strLen; $i++) {
- // Grab the next character in the string
- $char = substr($json, $i, 1);
-
- // Are we inside a quoted string?
- if ('"' === $char && $noescape) {
- $outOfQuotes = !$outOfQuotes;
- }
-
- if (!$outOfQuotes) {
- $buffer .= $char;
- $noescape = '\\' === $char ? !$noescape : true;
- continue;
- } elseif ('' !== $buffer) {
- $buffer = str_replace('\\/', '/', $buffer);
-
- if (function_exists('mb_convert_encoding')) {
- // See thread at http://stackoverflow.com/questions/2934563
- $buffer = preg_replace_callback('/(\\\\+)u([0-9a-f]{4})/i', function ($match) {
- $length = strlen($match[1]);
-
- if (($length % 2)) {
- return str_repeat('\\', ($length - 1)) . mb_convert_encoding(
- pack('H*', $match[2]),
- 'UTF-8',
- 'UCS-2BE'
- );
- }
-
- return $match[0];
- }, $buffer);
- }
-
- $result .= $buffer.$char;
- $buffer = '';
- continue;
- }
-
- if (':' === $char) {
- // Add a space after the : character
- $char .= ' ';
- } elseif (('}' === $char || ']' === $char)) {
- $pos--;
- $prevChar = substr($json, ($i - 1), 1);
-
- if ('{' !== $prevChar && '[' !== $prevChar) {
- // If this character is the end of an element,
- // output a new line and indent the next line
- $result .= $newLine;
- for ($j = 0; $j < $pos; $j++) {
- $result .= $indentStr;
- }
- } else {
- // Collapse all empty braces to have shorter output. This applies to {} and [].
- $result = rtrim($result);
- }
- }
-
- $result .= $char;
-
- // If the last character was the beginning of an element,
- // output a new line and indent the next line
- if (',' === $char || '{' === $char || '[' === $char) {
- $result .= $newLine;
-
- if ('{' === $char || '[' === $char) {
- $pos++;
- }
-
- for ($j = 0; $j < $pos; $j++) {
- $result .= $indentStr;
- }
- }
- }
-
- return $result;
+ return $json;
}
} | Remove the superfluous php version compare | phpcq_author-validation | train |
c1df54c67948bbb6ab86f7cbc7796642fafece0d | diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -151,6 +151,13 @@ function create(defaults) {
continue
}
+ // return early on HEAD requests
+ if (o.method.toUpperCase() === 'HEAD') {
+ res.req = req
+ res.resume()
+ return res
+ }
+
// unzip
var gunzip = typeof options.gunzip === 'boolean'
? options.gunzip
diff --git a/test/buffer.js b/test/buffer.js
index <HASH>..<HASH> 100644
--- a/test/buffer.js
+++ b/test/buffer.js
@@ -13,6 +13,15 @@ describe('buffer', function () {
res.buffer.should.be.a.Buffer
}))
+ it('should not buffer the response on HEAD requests', co(function* () {
+ var res = yield* request(uri, {
+ method: 'HEAD',
+ buffer: true
+ })
+ res.statusCode.should.equal(200)
+ res.should.not.have.property('buffer')
+ }))
+
it('should buffer the response as a string', co(function* () {
var res = yield* request(uri, {
string: true | don't buffer or gunzip the request on HEAD requests | cojs_cogent | train |
af82f49cdaf8a9a2bcbffaa1f69d0727873b1bb9 | diff --git a/src/Doctrine/OrientDB/Query/Formatter/Query/Updates.php b/src/Doctrine/OrientDB/Query/Formatter/Query/Updates.php
index <HASH>..<HASH> 100644
--- a/src/Doctrine/OrientDB/Query/Formatter/Query/Updates.php
+++ b/src/Doctrine/OrientDB/Query/Formatter/Query/Updates.php
@@ -20,7 +20,6 @@
namespace Doctrine\OrientDB\Query\Formatter\Query;
use Doctrine\OrientDB\Query\Formatter\Query;
-use Doctrine\OrientDB\Query\Formatter\String;
class Updates extends Query implements TokenInterface
{ | Remove unused class that caused the error | doctrine_orientdb-odm | train |
aa40f23952a61b75a44e373630a24f77066843b1 | diff --git a/prow/github/client.go b/prow/github/client.go
index <HASH>..<HASH> 100644
--- a/prow/github/client.go
+++ b/prow/github/client.go
@@ -1459,7 +1459,7 @@ func (c *client) AcceptUserOrgInvitation(org string) error {
path: fmt.Sprintf("/user/memberships/orgs/%s", org),
org: org,
requestBody: map[string]string{"state": "active"},
- exitCodes: []int{204},
+ exitCodes: []int{200},
}, nil)
return err | Fix accept org invitation method
The expected succeess code is <I> instead of <I> | kubernetes_test-infra | train |
26af54257ead399bf42fa8f76740e9c59ae67ba4 | diff --git a/neuropythy/__init__.py b/neuropythy/__init__.py
index <HASH>..<HASH> 100644
--- a/neuropythy/__init__.py
+++ b/neuropythy/__init__.py
@@ -11,7 +11,7 @@ from vision import (retinotopy_data, empirical_retinotopy_data, predicted_re
neighborhood_cortical_magnification)
# Version information...
-__version__ = '0.2.33'
+__version__ = '0.3.0'
description = 'Integrate Python environment with FreeSurfer and perform mesh registration'
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -27,7 +27,7 @@ setup(
url='https://github.com/noahbenson/neuropythy',
download_url='https://github.com/noahbenson/neuropythy',
license='GPLv3',
- classifiers=['Development Status :: 2 - Pre-Alpha',
+ classifiers=['Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', | upped version number for pypi alpha release | noahbenson_neuropythy | train |
a15fe14fe6c6d6c06b22cc22526153f935857dd8 | diff --git a/test/index.js b/test/index.js
index <HASH>..<HASH> 100644
--- a/test/index.js
+++ b/test/index.js
@@ -9,8 +9,6 @@
var path = require('path');
var fs = require('fs');
var assert = require('assert');
-var diff = require('diff');
-var chalk = require('chalk');
var mdast = require('mdast');
var File = require('mdast/lib/file');
var man = require('..');
@@ -26,12 +24,6 @@ var basename = path.basename;
var extname = path.extname;
var dirname = path.dirname;
-/*
- * Constants.
- */
-
-var stderr = global.process.stderr;
-
/**
* Create a `File` from a `filePath`.
*
@@ -104,25 +96,11 @@ function describeFixture(fixture) {
var config = join(filepath, 'config.json');
var file = toFile(fixture + '.md', input);
var result;
- var difference;
config = exists(config) ? JSON.parse(read(config, 'utf-8')) : {};
result = process(file, config);
- try {
- assert(result === output);
- } catch (exception) {
- difference = diff.diffLines(output, result);
-
- difference.forEach(function (change) {
- var colour = change.added ?
- 'green' : change.removed ? 'red' : 'dim';
-
- stderr.write(chalk[colour](change.value));
- });
-
- throw exception;
- }
+ assert.equal(result, output);
});
} | Add `assert.equal` instead of custom string-diff algorithm | remarkjs_remark-man | train |
1c002347ad21e3b92e35282579c6574ca866e449 | diff --git a/src/Test.php b/src/Test.php
index <HASH>..<HASH> 100644
--- a/src/Test.php
+++ b/src/Test.php
@@ -175,6 +175,16 @@ class Test
if (!isset($e)) {
$this->isOk($comment, strlen($out) ? 'darkGreen' : 'green');
} else {
+ if (!isset($err)) {
+ $err = sprintf(
+ '<gray>Caught exception <darkGray>%s <gray> with message <darkGray>%s <gray>in <darkGray>%s <gray>on line <darkGray>%s <gray>in test <darkGray>%s',
+ get_class($e),
+ $e->getMessage(),
+ $this->getBasename($e->getFile()),
+ $e->getLine(),
+ $this->file
+ );
+ }
$this->isError($comment);
$this->out(" <darkRed>[!] $err\n");
Log::log($err); | make sure this is at least always set | toast-php_unit | train |
f9863409739c8917b24c4844432f984d68877c63 | diff --git a/packages/@vue/cli-service/lib/config/base.js b/packages/@vue/cli-service/lib/config/base.js
index <HASH>..<HASH> 100644
--- a/packages/@vue/cli-service/lib/config/base.js
+++ b/packages/@vue/cli-service/lib/config/base.js
@@ -10,6 +10,9 @@ module.exports = (api, options) => {
const isLegacyBundle = process.env.VUE_CLI_MODERN_MODE && !process.env.VUE_CLI_MODERN_BUILD
const resolveLocal = require('../util/resolveLocal')
+ // https://github.com/webpack/webpack/issues/14532#issuecomment-947525539
+ webpackConfig.output.set('hashFunction', 'xxhash64')
+
// https://github.com/webpack/webpack/issues/11467#issuecomment-691873586
webpackConfig.module
.rule('esm') | fix: set hashFunction to `xxhash<I>` to fix Node <I> compatibility (#<I>) | vuejs_vue-cli | train |
cdf1712cb178a702270eeab8f6583a9cd6b3c1db | diff --git a/lib/mongomodel/railtie.rb b/lib/mongomodel/railtie.rb
index <HASH>..<HASH> 100644
--- a/lib/mongomodel/railtie.rb
+++ b/lib/mongomodel/railtie.rb
@@ -18,5 +18,13 @@ module MongoModel
MongoModel.configuration = mongomodel_configuration[Rails.env]
end
end
+
+ initializer "mongomodel.passenger_forking" do |app|
+ if defined?(PhusionPassenger)
+ PhusionPassenger.on_event(:starting_worker_process) do |forked|
+ MongoModel.database.connection.connect if forked
+ end
+ end
+ end
end
end | Add forked process reconnection code for passenger | spohlenz_mongomodel | train |
308d1431636af66408afe394bf5653efc4020846 | diff --git a/tests/GreenhouseServiceTest.php b/tests/GreenhouseServiceTest.php
index <HASH>..<HASH> 100644
--- a/tests/GreenhouseServiceTest.php
+++ b/tests/GreenhouseServiceTest.php
@@ -52,7 +52,7 @@ class GreenhouseServiceTest extends \PHPUnit_Framework_TestCase
);
$baseUrl = ApiService::jobBoardBaseUrl($this->boardToken);
- $authHeader = 'Basic ' . base64_encode($this->apiKey);
+ $authHeader = 'Basic ' . base64_encode($this->apiKey . ':');
$this->assertEquals($baseUrl, $service->getJobBoardBaseUrl());
$this->assertEquals($authHeader, $service->getAuthorizationHeader());
} | Add colon to test to match auth header. | grnhse_greenhouse-tools-php | train |
66fe255cda77384efd14ee13ba38b37578d6c99c | diff --git a/aegea/__init__.py b/aegea/__init__.py
index <HASH>..<HASH> 100644
--- a/aegea/__init__.py
+++ b/aegea/__init__.py
@@ -60,6 +60,7 @@ def initialize():
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument("--version", action="version", version="%(prog)s {version}".format(version=__version__))
+
def help(args):
parser.print_help()
register_parser(help)
diff --git a/aegea/ls.py b/aegea/ls.py
index <HASH>..<HASH> 100644
--- a/aegea/ls.py
+++ b/aegea/ls.py
@@ -70,6 +70,7 @@ def get_policies_for_principal(cell, row):
def users(args):
current_user = resources.iam.CurrentUser()
+
def mark_cur_user(cell, row):
return ">>>" if row.user_id == current_user.user_id else ""
users = list(resources.iam.users.all())
diff --git a/setup.cfg b/setup.cfg
index <HASH>..<HASH> 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -2,4 +2,4 @@
universal=1
[flake8]
max-line-length=120
-ignore: E301, E302, E401, E261, E265, E226, F401
+ignore: E301, E302, E305, E401, E261, E265, E226, F401
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -21,12 +21,12 @@ setup(
long_description=open("README.rst").read(),
install_requires=[
"setuptools",
- "boto3 >= 1.4.0, < 2",
+ "boto3 >= 1.4.1, < 2",
"argcomplete >= 1.4.1, < 2",
"paramiko >= 2.0.2, < 3",
"requests >= 2.11.0, < 3",
- "tweak >= 0.3.3, < 1",
- "keymaker >= 0.2.1, < 1",
+ "tweak >= 0.4.0, < 1",
+ "keymaker >= 0.3.3, < 1",
"pyyaml >= 3.11, < 4",
"python-dateutil >= 2.5.3, < 3",
"babel >= 2.3.4, < 3", | Bump deps; fix linter | kislyuk_aegea | train |
14f90d731048a1a2cd336d8194e3453e14fd0bd7 | diff --git a/autograd/numpy/linalg.py b/autograd/numpy/linalg.py
index <HASH>..<HASH> 100644
--- a/autograd/numpy/linalg.py
+++ b/autograd/numpy/linalg.py
@@ -89,10 +89,6 @@ def broadcasting_dsymv(alpha, A, x, lower=None):
A_sym[..., idxs, idxs] *= 0.5
return onp.einsum('...ij,...j->...i', A_sym, x)
-def broadcasting_diag(A):
- idxs = onp.arange(A.shape[-1])
- return A[...,idxs,idxs]
-
def make_grad_cholesky(L, A):
# based on choleskies_cython.pyx in SheffieldML/GPy and (Smith 1995)
# TODO for higher-order differentiation, replace dsymv, get rid of inplace
@@ -103,7 +99,7 @@ def make_grad_cholesky(L, A):
if A.ndim > 2:
dsymv = broadcasting_dsymv
dot = partial(onp.einsum, '...i,...i->...')
- diag = broadcasting_diag
+ diag = partial(onp.diagonal, axis1=-1, axis2=-2)
else:
dot = onp.dot
diag = onp.diag | Using np.diagonal in cholesky grad | HIPS_autograd | train |
e52db2bb7e6d23974d69a9cd412802ad82ac5165 | diff --git a/lib/kindle_manager/adapters/highlights_adapter.rb b/lib/kindle_manager/adapters/highlights_adapter.rb
index <HASH>..<HASH> 100644
--- a/lib/kindle_manager/adapters/highlights_adapter.rb
+++ b/lib/kindle_manager/adapters/highlights_adapter.rb
@@ -11,8 +11,10 @@ module KindleManager
end
def go_to_kindle_highlights_page
- log "Visiting kindle highlights page"
- session.visit KINDLE_HIGHLIGHT_URL
+ unless session.current_url == KINDLE_HIGHLIGHT_URL
+ log "Visiting kindle highlights page"
+ session.visit KINDLE_HIGHLIGHT_URL
+ end
wait_for_selector('#library')
check_library_scroll
snapshot_page
diff --git a/lib/kindle_manager/client.rb b/lib/kindle_manager/client.rb
index <HASH>..<HASH> 100644
--- a/lib/kindle_manager/client.rb
+++ b/lib/kindle_manager/client.rb
@@ -25,7 +25,8 @@ module KindleManager
end
def fetch_kindle_highlights
- sign_in
+ session.visit KindleManager::HighlightsAdapter::KINDLE_HIGHLIGHT_URL
+ @client.submit_signin_form
set_adapter(:highlights, @options.merge(session: session))
adapter.fetch
end | Fix sign in of kindle highlights page | kyamaguchi_kindle_manager | train |
6511c919ef205c10bc9ea08ad9dfe0f7c4e03518 | diff --git a/userapp/__init__.py b/userapp/__init__.py
index <HASH>..<HASH> 100644
--- a/userapp/__init__.py
+++ b/userapp/__init__.py
@@ -51,6 +51,9 @@ class IterableObject(object):
def to_json(self):
return json.dumps(self, cls=IterableObjectEncoder)
+ def to_dict(self):
+ return DictionaryUtility.to_dict(self)
+
class DictionaryUtility:
"""
Utility methods for dealing with dictionaries.
@@ -73,6 +76,29 @@ class DictionaryUtility:
return convert(item)
+ @staticmethod
+ def to_dict(item):
+ """
+ Convert an object to a dictionary (recursive).
+ """
+ def convert(item):
+ if isinstance(item, IterableObject):
+ if isinstance(item.source, dict):
+ return {k: convert(v.source) if hasattr(v, 'source') else convert(v) for k, v in item}
+ else:
+ return convert(item.source)
+ elif isinstance(item, dict):
+ return {k: convert(v) for k, v in item.iteritems()}
+ elif isinstance(item, list):
+ def yield_convert(item):
+ for index, value in enumerate(item):
+ yield convert(value)
+ return list(yield_convert(item))
+ else:
+ return item
+
+ return convert(item)
+
class UserAppException(Exception):
"""
Base class for all UserApp exceptions. | Added support for converting object to dictionary. | userapp-io_userapp-python | train |
1320a99323cb7dd1319366cc710362d8bebc0b05 | diff --git a/test/helpers/bootstrap_helper_test.rb b/test/helpers/bootstrap_helper_test.rb
index <HASH>..<HASH> 100644
--- a/test/helpers/bootstrap_helper_test.rb
+++ b/test/helpers/bootstrap_helper_test.rb
@@ -232,15 +232,13 @@ class BootstrapHelperTest < ActionView::TestCase
assert_select 'div.modal-footer' do
assert_select 'button',
attributes: { class: 'btn btn-default', "data-dismiss": 'modal' },
- html: "Don't save"
+ html: /Don(.*?)t save/ # assert_select behaviour changes
assert_select 'input', attributes: { type: 'submit', class: 'btn-primary btn' }
end
end
end
- @output_buffer = bootstrap_modal_box('New Pear') do
- 'Pear form'
- end
+ @output_buffer = bootstrap_modal_box('New Pear') { 'Pear form' }
assert_select 'div.modal-dialog' do
assert_select 'div.modal-content' do
assert_select 'div.modal-header h4', 'New Pear'
@@ -248,9 +246,8 @@ class BootstrapHelperTest < ActionView::TestCase
assert_select 'div.modal-footer' do
assert_select 'button',
attributes: { class: 'btn btn-default', "data-dismiss": 'modal' },
- html: "Don't save"
- assert_select 'input',
- attributes: { type: 'submit', class: 'btn-primary btn' }
+ html: /Don(.*?)t save/ # assert_select behaviour changes
+ assert_select 'input', attributes: { type: 'submit', class: 'btn-primary btn' }
end
end
end | # On Rails 4+, assert_select is nokogiri-powered | PublicHealthEngland_ndr_ui | train |
766d2daa06509839779cd2f33728535d2b428485 | diff --git a/testing/test_runner.py b/testing/test_runner.py
index <HASH>..<HASH> 100644
--- a/testing/test_runner.py
+++ b/testing/test_runner.py
@@ -570,13 +570,16 @@ def test_pytest_exit_msg(testdir):
result.stderr.fnmatch_lines(["Exit: oh noes"])
-def test_pytest_exit_returncode():
- try:
- pytest.exit("hello", returncode=2)
- except SystemExit as exc:
- excinfo = _pytest._code.ExceptionInfo()
- assert excinfo.errisinstance(SystemExit)
- assert excinfo.value.code == 2
+def test_pytest_exit_returncode(testdir):
+ testdir.makepyfile(
+ """
+ import pytest
+ def test_foo():
+ pytest.exit("some exit msg", 99)
+ """
+ )
+ result = testdir.runpytest()
+ assert result.ret == 99
def test_pytest_fail_notrace_runtest(testdir): | Update returncode exit test to check exitstatus returrned from test session | pytest-dev_pytest | train |
f337a5ba32d2e3cb1a65a0391b9bc9e2d89983d5 | diff --git a/lib/libnmap.js b/lib/libnmap.js
index <HASH>..<HASH> 100644
--- a/lib/libnmap.js
+++ b/lib/libnmap.js
@@ -350,14 +350,13 @@ var version = 'v0.4.0'
/* singular IPv4, IPv6 or RFC-1123 hostname */
case (validation.test(tests.hostname, host) ||
validation.test(tests.IPv4, host) ||
- validation.test(tests.IPv6, host) ||
- validation.test(tests.IPv6CIDR, host)):
+ validation.test(tests.IPv6, host)):
results.push(host);
break;
- /* CIDR notation; break up into chunks for parallel processing */
+ /* IPv4 CIDR notation; break up into chunks for parallel processing */
case (validation.test(tests.IPv4CIDR, host)):
results = network.range(opts, host);
@@ -370,6 +369,14 @@ var version = 'v0.4.0'
results.push(host);
break;
+
+ case (validation.test(tests.IPv6CIDR, host)):
+
+ /* Add IPv6 calculations to assist with parallel processing */
+ results.push(host);
+
+ break;
+
default:
/* Silently discard specified element as invalid */ | Added conditional for IPv6 CIDR range prcoessing | jas-_node-libnmap | train |
71613a2d1d4161a3064ec9ccf65f7c54f5c983f8 | diff --git a/will/decorators.py b/will/decorators.py
index <HASH>..<HASH> 100644
--- a/will/decorators.py
+++ b/will/decorators.py
@@ -92,7 +92,7 @@ def rendered_template(template_name, context=None, custom_filters=[]):
def wrap(f):
def wrapped_f(*args, **kwargs):
context = f(*args, **kwargs)
- if type(context) == type({}):
+ if isinstance(context, dict()):
template = env.get_template(template_name)
return template.render(**context)
else: | PEP8 warning fix replaced type comparsion for isinstance | skoczen_will | train |
302ba289710144feaa27721cdcfb2204028dc6a3 | diff --git a/lib/eye/controller/load.rb b/lib/eye/controller/load.rb
index <HASH>..<HASH> 100644
--- a/lib/eye/controller/load.rb
+++ b/lib/eye/controller/load.rb
@@ -85,6 +85,7 @@ private
cfg = Eye::Dsl.parse(nil, filename)
@current_config.merge(cfg).validate! # just validate summary config here
+ Eye.parsed_config = nil # remove link on config, for better gc
cfg
end | remove link on config, for better gc in load | kostya_eye | train |
fae7a09b83e3e2d4abbd7a9454a189c0a6da4cd7 | diff --git a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java
index <HASH>..<HASH> 100644
--- a/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java
+++ b/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java
@@ -105,7 +105,7 @@ public class SpringBootContextLoader extends AbstractContextLoader {
application.setMainApplicationClass(config.getTestClass());
application.addPrimarySources(Arrays.asList(configClasses));
application.getSources().addAll(Arrays.asList(configLocations));
- ConfigurableEnvironment environment = new StandardEnvironment();
+ ConfigurableEnvironment environment = getEnvironment();
if (!ObjectUtils.isEmpty(config.getActiveProfiles())) {
setActiveProfiles(environment, config.getActiveProfiles());
}
@@ -148,6 +148,15 @@ public class SpringBootContextLoader extends AbstractContextLoader {
return new SpringApplication();
}
+ /**
+ * Builds a new {@link ConfigurableEnvironment} instance. You can override this method
+ * to return something other than {@link StandardEnvironment} if necessary.
+ * @return a {@link ConfigurableEnvironment} instance
+ */
+ protected ConfigurableEnvironment getEnvironment() {
+ return new StandardEnvironment();
+ }
+
private void setActiveProfiles(ConfigurableEnvironment environment,
String[] profiles) {
TestPropertyValues | Support custom SpringBootContextLoader environment
Provide a `getEnvironment` method in `SpringBootContextLoader` to allow
specialized `ConfigurableEnvironment` implementations to be used.
Closes gh-<I> | spring-projects_spring-boot | train |
Subsets and Splits