hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
93f8dafbfdde90986504644d3b534e911abfc458
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -20,6 +20,7 @@ setup(
version=CURRENT_VERSION,
description='Python 3 portage of pysvg',
long_description=read('README.md'),
+ long_description_content_type="text/markdown",
author='Kerim Mansour',
author_email='',
url='https://github.com/alorence/pysvg-py3',
|
Add info about README format
This seems now mandatory to publish on Pypi
|
alorence_pysvg-py3
|
train
|
fc793c99aa4967f7ba3464211f0f920d43b378a5
|
diff --git a/lib/restaurant/actions.rb b/lib/restaurant/actions.rb
index <HASH>..<HASH> 100644
--- a/lib/restaurant/actions.rb
+++ b/lib/restaurant/actions.rb
@@ -5,10 +5,11 @@ module Restaurant
base.before_filter :add_created_at, :only => :create
base.before_filter :add_updated_at, :only => :update
base.after_filter :expire_resource_cache, :only => [:update, :destroy]
+ base.after_filter :update_resources_version_cache, :only => [:create, :update, :destroy]
end
def index
- respond_with collection.find(filter_params).sort(sort_params).skip(skip_params).limit(limit_params)
+ respond_with resources
end
def show
@@ -46,6 +47,21 @@ module Restaurant
@resource ||= collection.find(:_id => resource_id).first
end
+ def resources
+ collection.find(filter_params).sort(sort_params).skip(skip_params).limit(limit_params).to_a
+ end
+
+ def resources_with_cache
+ if cache_configured?
+ cache_store.fetch(resources_cache_key) do
+ resources_without_cache
+ end
+ else
+ resources_without_cache
+ end
+ end
+ alias_method_chain :resources, :cache
+
def resource_with_cache
if cache_configured?
cache_store.fetch(resource_cache_key) do
@@ -114,5 +130,23 @@ module Restaurant
def resource_cache_key
params.slice(:resource, :id)
end
+
+ def resources_version_cache_key
+ { :resource => params[:resource] }
+ end
+
+ def update_resources_version_cache
+ if cache_configured?
+ cache_store.write(resources_version_cache_key, Time.now.to_f)
+ end
+ end
+
+ def resources_version
+ cache_store.read(resources_version_cache_key)
+ end
+
+ def resources_cache_key
+ params.slice(:resource, :filter, :sort, :page).merge(:version => resources_version)
+ end
end
end
|
Cache resources until any resource is updated or deleted
If any resource is updated or deleted, the version is updated.
The version will be used as resources cache key.
I used Time.now.to_f as version with no thought but anything is OK.
|
r7kamura_restaurant
|
train
|
ef6188bacee6dbc817a6b8f28aa92ac501c954a5
|
diff --git a/features/sinatra_app_steps.rb b/features/sinatra_app_steps.rb
index <HASH>..<HASH> 100644
--- a/features/sinatra_app_steps.rb
+++ b/features/sinatra_app_steps.rb
@@ -2,6 +2,9 @@ Given /the example sinatra app$/ do
end
When /^I run "([^\"]*)" in the sinatra root$/ do |cmd|
+ # Need to run Rails generators first since the siatra app symlinks to the step defs.
+ Given "the example rails app is setup with the latest generators"
+ When 'I run "rake db:migrate RAILS_ENV=test" in the rails root'
cmd.gsub!('cucumber', "#{Cucumber::RUBY_BINARY} #{Cucumber::BINARY}")
root_dir = File.join(File.expand_path(File.dirname(__FILE__)), "..")
Dir.chdir(File.join(root_dir, 'examples', 'sinatra')) do
|
making sinatra feature deterministic
Prior to this commit the sinatra feature would fail unless you ran the
rails feature prior. The sinatra app passing is no longer dependent upon that.
|
email-spec_email-spec
|
train
|
163efc79cb91d133b2f5e5ce19b8ca8305e2a7c7
|
diff --git a/src/android/test/com/test/thalitest/RegisterExecuteUT.java b/src/android/test/com/test/thalitest/RegisterExecuteUT.java
index <HASH>..<HASH> 100644
--- a/src/android/test/com/test/thalitest/RegisterExecuteUT.java
+++ b/src/android/test/com/test/thalitest/RegisterExecuteUT.java
@@ -79,7 +79,7 @@ public final class RegisterExecuteUT {
@Override
public void Receiver(ArrayList<Object> params, String callbackId) {
ConnectionHelperTest.mConnectionHelper = new ConnectionHelper();
- String logtag = "ExecuteNativeTests";
+ String logtag = "executeNativeTests";
Log.d(logtag, "Running unit tests");
Result resultTest = ThaliTestRunner.runTests();
diff --git a/test/www/jxcore/UnitTest_app.js b/test/www/jxcore/UnitTest_app.js
index <HASH>..<HASH> 100644
--- a/test/www/jxcore/UnitTest_app.js
+++ b/test/www/jxcore/UnitTest_app.js
@@ -17,7 +17,7 @@ var utResult = false;
if (process.platform === 'android' || process.platform === 'ios') {
console.log('Running unit tests');
- Mobile('ExecuteNativeTests').callNative(function (result) {
+ Mobile('executeNativeTests').callNative(function (result) {
utResult = true;
if (result && result.executed) {
console.log('Total number of executed tests: ', result.total);
|
Fixed executeNativeTests method name to be firstLowerCase
|
thaliproject_Thali_CordovaPlugin
|
train
|
8c29949a0e55890f4f1cd7b98e4c075892dbd6dd
|
diff --git a/salt/log/setup.py b/salt/log/setup.py
index <HASH>..<HASH> 100644
--- a/salt/log/setup.py
+++ b/salt/log/setup.py
@@ -930,8 +930,13 @@ def patch_python_logging_handlers():
def __process_multiprocessing_logging_queue(opts, queue):
import salt.utils
salt.utils.appendproctitle('MultiprocessingLoggingQueue')
+
+ # Assign UID/GID of user to proc if set
from salt.utils.verify import check_user
- check_user(opts['user'])
+ user = opts.get('user')
+ if user:
+ check_user(user)
+
if salt.utils.is_windows():
# On Windows, creating a new process doesn't fork (copy the parent
# process image). Due to this, we need to setup extended logging
|
log.setup: only assign user if defined
|
saltstack_salt
|
train
|
c225b80ca61257bb290401d3db98d5da7cba6b0a
|
diff --git a/salt/cloud/clouds/openstack.py b/salt/cloud/clouds/openstack.py
index <HASH>..<HASH> 100644
--- a/salt/cloud/clouds/openstack.py
+++ b/salt/cloud/clouds/openstack.py
@@ -462,7 +462,7 @@ def create(vm_):
# otherwise, attempt to obtain list without specifying pool
# this is the same as 'nova floating-ip-list'
elif ssh_interface(vm_) != 'private_ips':
- try:
+ try:
# This try/except is here because it appears some
# *cough* Rackspace *cough*
# OpenStack providers return a 404 Not Found for the
@@ -484,10 +484,10 @@ def create(vm_):
'available, please create some more'
)
except Exception as e:
- if str(e).startswith('404'):
- pass
- else:
- raise
+ if str(e).startswith('404'):
+ pass
+ else:
+ raise
files = config.get_cloud_config_value(
'files', vm_, __opts__, search_global=False
|
How did those tabs get in there?
|
saltstack_salt
|
train
|
49800923c24e563943cd19087f0c9895e7ba0353
|
diff --git a/features/step_definitions/rails_application_steps.rb b/features/step_definitions/rails_application_steps.rb
index <HASH>..<HASH> 100644
--- a/features/step_definitions/rails_application_steps.rb
+++ b/features/step_definitions/rails_application_steps.rb
@@ -257,7 +257,7 @@ Then /^the Airbrake notification should not contain any of the sensitive Rack va
sensitive_rack_data_regex = FILTERED_RACK_VARS.map do |var|
var.instance_of?(Regexp) ? var : Regexp.quote(var)
end.join("|")
- step %{the last notice sent should not contain "#{'key\=\"('+sensitive_rack_data_regex+')\"'}"}
+ step %{the last notice sent should not contain keys with "#{sensitive_rack_data_regex}"}
end
Then /^the last notice sent should contain "([^\"]*)"$/ do |data|
@@ -265,11 +265,16 @@ Then /^the last notice sent should contain "([^\"]*)"$/ do |data|
last_notice.should match(%r{#{data}})
end
-Then /^the last notice sent should not contain "(.*)"$/ do |data|
+Then /^the last notice sent should not contain "([^\"]*)"$/ do |data|
last_notice = File.read(LAST_NOTICE)
last_notice.should_not match(%r{#{data}})
end
+Then /^the last notice sent should not contain keys with "([^\"]*)"$/ do |data|
+ last_notice = File.read(LAST_NOTICE)
+ last_notice.should_not match(%r{key\=\"(#{data})\"})
+end
+
Then /^the Airbrake notification should contain the framework information$/ do
step %{the last notice sent should contain "Rails: #{ENV["RAILS_VERSION"]}"}
end
|
Make separate step for the cucumber test that checks for filtered keys
|
airbrake_airbrake
|
train
|
ae862716a6fa463ffff3139ef46218a5850ace19
|
diff --git a/js/cw/autoTitle.js b/js/cw/autoTitle.js
index <HASH>..<HASH> 100644
--- a/js/cw/autoTitle.js
+++ b/js/cw/autoTitle.js
@@ -6,7 +6,7 @@
goog.provide('cw.autoTitle');
-(function(){
+cw.autoTitle.setTitle = function() {
var split = String(document.location).split('/');
var last = split[split.length-1];
var almostLast = split[split.length-2];
@@ -17,4 +17,6 @@ goog.provide('cw.autoTitle');
} else {
document.title = almostLast + ' ' + scheme;
}
-})();
+};
+
+cw.autoTitle.setTitle();
|
js/cw/autoTitle.js: refactor self-calling function into cw.autoTitle.setTitle
|
ludiosarchive_Coreweb
|
train
|
7ddf336b84c89ebf58ac25696f1aa49c7c39f20e
|
diff --git a/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/relational/TPCHQuery3.java b/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/relational/TPCHQuery3.java
index <HASH>..<HASH> 100644
--- a/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/relational/TPCHQuery3.java
+++ b/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/relational/TPCHQuery3.java
@@ -46,14 +46,15 @@ import eu.stratosphere.pact.example.relational.util.Tuple;
* on http://www.tpc.org/tpch/ .This implementation is tested with
* the DB2 data format.
* THe PACT program implements a modified version of the query 3 of
- * the TPC-H benchmark including a join, aggregation, filtering and
- * projection.
+ * the TPC-H benchmark including one join, some filtering and an
+ * aggregation.
*
* SELECT l_orderkey, o_shippriority, sum(l_extendedprice) as revenue
* FROM orders, lineitem
* WHERE l_orderkey = o_orderkey
- * AND o_custkey IN [X]
- * AND o_orderdate > [Y]
+ * AND o_orderstatus = "X"
+ * AND YEAR(o_orderdate) > Y
+ * AND o_orderpriority LIKE "Z%"
* GROUP BY l_orderkey, o_shippriority;
*/
public class TPCHQuery3 implements PlanAssembler, PlanAssemblerDescription {
@@ -97,11 +98,11 @@ public class TPCHQuery3 implements PlanAssembler, PlanAssemblerDescription {
private final String PRIO_FILTER = "5";
/**
- * Filters the orders table by custKey and orderDate
- * TODO
- * o_custkey IN [X] AND o_orderdate > [Y]
- * o_orderstatus = "F" AND year(o_orderdate) = 1993
- * AND o_orderPriority LIKE "5%"
+ * Filters the orders table by year, orderstatus and orderpriority
+ *
+ * o_orderstatus = "X"
+ * AND YEAR(o_orderdate) > Y
+ * AND o_orderpriority LIKE "Z"
*
* Output Schema:
* Key: ORDERKEY
@@ -322,6 +323,9 @@ public class TPCHQuery3 implements PlanAssembler, PlanAssemblerDescription {
return new Plan(result, "TPCH Q3");
}
+ /**
+ * {@inheritDoc}
+ */
@Override
public String getDescription() {
return "Parameters: dop, orders-input, lineitem-input, result";
|
Updated JavaDoc for TPCH3 Query to new filter constraints
|
stratosphere_stratosphere
|
train
|
7d73727d6c40e617d5713577399e5430e3ab95e4
|
diff --git a/packages/net/csp/transports.js b/packages/net/csp/transports.js
index <HASH>..<HASH> 100644
--- a/packages/net/csp/transports.js
+++ b/packages/net/csp/transports.js
@@ -206,11 +206,8 @@ transports.xhr = Class(baseTransport, function(supr) {
} else if('onreadystatechange' in xhr) {
xhr.onreadystatechange = bind(this, '_onReadyStateChange', rType, cb, eb);
}
- if(data) {
- xhr.send(data);
- } else {
- xhr.send();
- }
+
+ setTimeout(bind(xhr, 'send', data), 0);
};
});
|
this line was accidently deleted in 3b<I>b7beb1d9ce<I> (mcarter) - fixes spinning loading indicators in webkit
|
gameclosure_js.io
|
train
|
d5de6489d7275374a3bb269b07780d6c13b6c3b7
|
diff --git a/core/types/transaction.go b/core/types/transaction.go
index <HASH>..<HASH> 100644
--- a/core/types/transaction.go
+++ b/core/types/transaction.go
@@ -3,6 +3,7 @@ package types
import (
"bytes"
"fmt"
+ "io"
"math/big"
"github.com/ethereum/go-ethereum/common"
@@ -27,12 +28,12 @@ type Transaction struct {
R, S []byte
}
-func NewContractCreationTx(Amount, gasAmount, price *big.Int, data []byte) *Transaction {
- return NewTransactionMessage(common.Address{}, Amount, gasAmount, price, data)
+func NewContractCreationTx(amount, gasAmount, price *big.Int, data []byte) *Transaction {
+ return NewTransactionMessage(common.Address{}, amount, gasAmount, price, data)
}
-func NewTransactionMessage(to common.Address, Amount, gasAmount, price *big.Int, data []byte) *Transaction {
- return &Transaction{Recipient: to, Amount: Amount, Price: price, GasLimit: gasAmount, Payload: data}
+func NewTransactionMessage(to common.Address, amount, gasAmount, price *big.Int, data []byte) *Transaction {
+ return &Transaction{Recipient: to, Amount: amount, Price: price, GasLimit: gasAmount, Payload: data}
}
func NewTransactionFromBytes(data []byte) *Transaction {
@@ -44,7 +45,7 @@ func NewTransactionFromBytes(data []byte) *Transaction {
func (tx *Transaction) Hash() (a common.Hash) {
h := sha3.NewKeccak256()
rlp.Encode(h, []interface{}{tx.AccountNonce, tx.Price, tx.GasLimit, tx.Recipient, tx.Amount, tx.Payload})
- h.Sum(a[:])
+ h.Sum(a[:0])
return a
}
@@ -84,7 +85,6 @@ func (tx *Transaction) Curve() (v byte, r []byte, s []byte) {
v = byte(tx.V)
r = common.LeftPadBytes(tx.R, 32)
s = common.LeftPadBytes(tx.S, 32)
-
return
}
@@ -124,6 +124,19 @@ func (tx *Transaction) SetSignatureValues(sig []byte) error {
return nil
}
+func (tx Transaction) EncodeRLP(w io.Writer) error {
+ return rlp.Encode(w, []interface{}{
+ tx.AccountNonce,
+ tx.Price, tx.GasLimit,
+ tx.Recipient,
+ tx.Amount,
+ tx.Payload,
+ tx.V,
+ tx.R,
+ tx.S,
+ })
+}
+
// TODO: remove
func (tx *Transaction) RlpData() interface{} {
data := []interface{}{tx.AccountNonce, tx.Price, tx.GasLimit, tx.Recipient, tx.Amount, tx.Payload}
diff --git a/core/types/transaction_test.go b/core/types/transaction_test.go
index <HASH>..<HASH> 100644
--- a/core/types/transaction_test.go
+++ b/core/types/transaction_test.go
@@ -1 +1,57 @@
package types
+
+import (
+ "bytes"
+ "math/big"
+ "testing"
+
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/rlp"
+)
+
+// The values in those tests are from the Transaction Tests
+// at github.com/ethereum/tests.
+
+var (
+ emptyTx = NewTransactionMessage(
+ common.HexToAddress("095e7baea6a6c7c4c2dfeb977efac326af552d87"),
+ big.NewInt(0), big.NewInt(0), big.NewInt(0),
+ nil,
+ )
+
+ rightvrsTx = &Transaction{
+ Recipient: common.HexToAddress("b94f5374fce5edbc8e2a8697c15331677e6ebf0b"),
+ AccountNonce: 3,
+ Price: big.NewInt(1),
+ GasLimit: big.NewInt(2000),
+ Amount: big.NewInt(10),
+ Payload: common.FromHex("5544"),
+ V: 28,
+ R: common.FromHex("98ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4a"),
+ S: common.FromHex("8887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3"),
+ }
+)
+
+func TestTransactionHash(t *testing.T) {
+ // "EmptyTransaction"
+ if emptyTx.Hash() != common.HexToHash("c775b99e7ad12f50d819fcd602390467e28141316969f4b57f0626f74fe3b386") {
+ t.Errorf("empty transaction hash mismatch, got %x", emptyTx.Hash())
+ }
+
+ // "RightVRSTest"
+ if rightvrsTx.Hash() != common.HexToHash("fe7a79529ed5f7c3375d06b26b186a8644e0e16c373d7a12be41c62d6042b77a") {
+ t.Errorf("RightVRS transaction hash mismatch, got %x", rightvrsTx.Hash())
+ }
+}
+
+func TestTransactionEncode(t *testing.T) {
+ // "RightVRSTest"
+ txb, err := rlp.EncodeToBytes(rightvrsTx)
+ if err != nil {
+ t.Fatalf("encode error: %v", err)
+ }
+ should := common.FromHex("f86103018207d094b94f5374fce5edbc8e2a8697c15331677e6ebf0b0a8255441ca098ff921201554726367d2be8c804a7ff89ccf285ebc57dff8ae4c44b9c19ac4aa08887321be575c8095f789dd4c743dfe42c1820f9231f98a962b210e3ac2452a3")
+ if !bytes.Equal(txb, should) {
+ t.Errorf("encoded RLP mismatch, got %x", txb)
+ }
+}
|
core/types: fix Transaction.Hash and add support for encoding with package rlp
|
ethereum_go-ethereum
|
train
|
67216aa5637a0e134750103abb74b5c2e3db3eb6
|
diff --git a/lib/puppet/provider/sshkey/parsed.rb b/lib/puppet/provider/sshkey/parsed.rb
index <HASH>..<HASH> 100755
--- a/lib/puppet/provider/sshkey/parsed.rb
+++ b/lib/puppet/provider/sshkey/parsed.rb
@@ -21,14 +21,14 @@ Puppet::Type.type(:sshkey).provide(:parsed,
:post_parse => proc { |hash|
names = hash[:name].split(",", -1)
hash[:name] = names.shift
- hash[:alias] = names
+ hash[:host_aliases] = names
},
:pre_gen => proc { |hash|
- if hash[:alias]
- names = [hash[:name], hash[:alias]].flatten
+ if hash[:host_aliases]
+ names = [hash[:name], hash[:host_aliases]].flatten
- hash[:name] = [hash[:name], hash[:alias]].flatten.join(",")
- hash.delete(:alias)
+ hash[:name] = [hash[:name], hash[:host_aliases]].flatten.join(",")
+ hash.delete(:host_aliases)
end
}
end
diff --git a/spec/unit/provider/sshkey/parsed.rb b/spec/unit/provider/sshkey/parsed.rb
index <HASH>..<HASH> 100755
--- a/spec/unit/provider/sshkey/parsed.rb
+++ b/spec/unit/provider/sshkey/parsed.rb
@@ -8,12 +8,31 @@ describe provider_class do
before do
@sshkey_class = Puppet::Type.type(:sshkey)
@provider_class = @sshkey_class.provider(:parsed)
+ @key = 'AAAAB3NzaC1yc2EAAAABIwAAAQEAzwHhxXvIrtfIwrudFqc8yQcIfMudrgpnuh1F3AV6d2BrLgu/yQE7W5UyJMUjfj427sQudRwKW45O0Jsnr33F4mUw+GIMlAAmp9g24/OcrTiB8ZUKIjoPy/cO4coxGi8/NECtRzpD/ZUPFh6OEpyOwJPMb7/EC2Az6Otw4StHdXUYw22zHazBcPFnv6zCgPx1hA7QlQDWTu4YcL0WmTYQCtMUb3FUqrcFtzGDD0ytosgwSd+JyN5vj5UwIABjnNOHPZ62EY1OFixnfqX/+dUwrFSs5tPgBF/KkC6R7tmbUfnBON6RrGEmu+ajOTOLy23qUZB4CQ53V7nyAWhzqSK+hw=='
end
- it "should not drop an empty alias" do
- line = 'test,alias, ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAzwHhxXvIrtfIwrudFqc8yQcIfMudrgpnuh1F3AV6d2BrLgu/yQE7W5UyJMUjfj427sQudRwKW45O0Jsnr33F4mUw+GIMlAAmp9g24/OcrTiB8ZUKIjoPy/cO4coxGi8/NECtRzpD/ZUPFh6OEpyOwJPMb7/EC2Az6Otw4StHdXUYw22zHazBcPFnv6zCgPx1hA7QlQDWTu4YcL0WmTYQCtMUb3FUqrcFtzGDD0ytosgwSd+JyN5vj5UwIABjnNOHPZ62EY1OFixnfqX/+dUwrFSs5tPgBF/KkC6R7tmbUfnBON6RrGEmu+ajOTOLy23qUZB4CQ53V7nyAWhzqSK+hw=='
- parsed = @provider_class.parse_line(line)
- parsed[:alias].should == ["alias",""]
+ it "should parse the name from the first field" do
+ @provider_class.parse_line('test ssh-rsa '+@key)[:name].should == "test"
+ end
+
+ it "should parse the first component of the first field as the name" do
+ @provider_class.parse_line('test,alias ssh-rsa '+@key)[:name].should == "test"
+ end
+
+ it "should parse host_aliases from the remaining components of the first field" do
+ @provider_class.parse_line('test,alias ssh-rsa '+@key)[:host_aliases].should == ["alias"]
+ end
+
+ it "should parse multiple host_aliases" do
+ @provider_class.parse_line('test,alias1,alias2,alias3 ssh-rsa '+@key)[:host_aliases].should == ["alias1","alias2","alias3"]
+ end
+
+ it "should not drop an empty host_alias" do
+ @provider_class.parse_line('test,alias, ssh-rsa '+@key)[:host_aliases].should == ["alias",""]
+ end
+
+ it "should recognise when there are no host aliases" do
+ @provider_class.parse_line('test ssh-rsa '+@key)[:host_aliases].should == []
end
end
|
Fix for #<I> (sshkey host_aliases ignored)
In the alias --> host_aliases conversion, I overlooked parsed file
provider for sshkeys.
Now with tests.
|
puppetlabs_puppet
|
train
|
14af38fb0f64f32e5d1754cb192d2fc346ba0b3a
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,8 @@
# v1.4.0-rc.1
## mm/dd/2017
+1. [](#new)
+ * Moved Twig `urlFunc()` to `Utils::url()` as its so darn handy
1. [](#improved)
* Made `modular` blueprint more flexible
1. [](#bugfix)
diff --git a/system/src/Grav/Common/Twig/TwigExtension.php b/system/src/Grav/Common/Twig/TwigExtension.php
index <HASH>..<HASH> 100644
--- a/system/src/Grav/Common/Twig/TwigExtension.php
+++ b/system/src/Grav/Common/Twig/TwigExtension.php
@@ -677,36 +677,7 @@ class TwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsIn
*/
public function urlFunc($input, $domain = false)
{
- if (!trim((string)$input)) {
- return false;
- }
-
- if ($this->grav['config']->get('system.absolute_urls', false)) {
- $domain = true;
- }
-
- if (Grav::instance()['uri']->isExternal($input)) {
- return $input;
- }
-
- $input = ltrim((string)$input, '/');
-
- if (Utils::contains((string)$input, '://')) {
- /** @var UniformResourceLocator $locator */
- $locator = $this->grav['locator'];
-
-
-
- // Get relative path to the resource (or false if not found).
- $resource = $locator->findResource($input, false);
- } else {
- $resource = $input;
- }
-
- /** @var Uri $uri */
- $uri = $this->grav['uri'];
-
- return $resource ? rtrim($uri->rootUrl($domain), '/') . '/' . $resource : null;
+ return Utils::url($input, $domain);
}
/**
diff --git a/system/src/Grav/Common/Utils.php b/system/src/Grav/Common/Utils.php
index <HASH>..<HASH> 100644
--- a/system/src/Grav/Common/Utils.php
+++ b/system/src/Grav/Common/Utils.php
@@ -17,6 +17,45 @@ abstract class Utils
protected static $nonces = [];
/**
+ * Simple helper method to make getting a Grav URL easier
+ *
+ * @param $input
+ * @param bool $domain
+ * @return bool|null|string
+ */
+ public static function url($input, $domain = false)
+ {
+ if (!trim((string)$input)) {
+ return false;
+ }
+
+ if (Grav::instance()['config']->get('system.absolute_urls', false)) {
+ $domain = true;
+ }
+
+ if (Grav::instance()['uri']->isExternal($input)) {
+ return $input;
+ }
+
+ $input = ltrim((string)$input, '/');
+
+ if (Utils::contains((string)$input, '://')) {
+ /** @var UniformResourceLocator $locator */
+ $locator = Grav::instance()['locator'];
+
+ // Get relative path to the resource (or false if not found).
+ $resource = $locator->findResource($input, false);
+ } else {
+ $resource = $input;
+ }
+
+ /** @var Uri $uri */
+ $uri = Grav::instance()['uri'];
+
+ return $resource ? rtrim($uri->rootUrl($domain), '/') . '/' . $resource : null;
+ }
+
+ /**
* Check if the $haystack string starts with the substring $needle
*
* @param string $haystack
|
Moved url() function into Utils class
|
getgrav_grav
|
train
|
3f933f1d9fb02d820bd8f4b34a49c8d690aeb60e
|
diff --git a/src/hdx/utilities/frictionless_wrapper.py b/src/hdx/utilities/frictionless_wrapper.py
index <HASH>..<HASH> 100644
--- a/src/hdx/utilities/frictionless_wrapper.py
+++ b/src/hdx/utilities/frictionless_wrapper.py
@@ -99,20 +99,11 @@ def get_frictionless_resource(
kwargs["detector"] = detector
kwargs["layout"] = layout
http_session = kwargs.pop("http_session", session)
- try:
- if http_session is not None:
- frictionless.system.use_http_session(http_session)
- if url:
- resource = frictionless.Resource(url, **kwargs)
- else:
- resource = frictionless.Resource(data=data, **kwargs)
- resource.open()
- return resource
- except Exception as e:
- msg = url
- if not msg:
- msg = "data"
- error = ResourceError(
- note=f"Getting Frictionless resource for {msg} failed!"
- )
- raise FrictionlessException(error=error) from e
+ if http_session is not None:
+ frictionless.system.use_http_session(http_session)
+ if url:
+ resource = frictionless.Resource(url, **kwargs)
+ else:
+ resource = frictionless.Resource(data=data, **kwargs)
+ resource.open()
+ return resource
|
Don't need to wrap frictionless exceptions
|
OCHA-DAP_hdx-python-utilities
|
train
|
2e8d5ad7ac64cc297566cd4305d5a383c2f32df3
|
diff --git a/client/client_test.go b/client/client_test.go
index <HASH>..<HASH> 100644
--- a/client/client_test.go
+++ b/client/client_test.go
@@ -1673,7 +1673,7 @@ func TestPublishUninitializedRepo(t *testing.T) {
requireRepoHasExpectedMetadata(t, repo, data.CanonicalTargetsRole, true)
}
-// Tnitializing a repo and republishing after should succeed
+// Initializing a repo and republishing after should succeed
func TestPublishInitializedRepo(t *testing.T) {
var gun data.GUN = "docker.com/notary"
ts := fullTestServer(t)
@@ -2647,19 +2647,17 @@ func TestRemoteRotationNoRootKey(t *testing.T) {
require.IsType(t, signed.ErrInsufficientSignatures{}, err)
}
-// The repo is initialized at publish time after
-// rotating the key. We should be denied the access
-// to metadata by the server when trying to retrieve it.
+// The repo should initialize successfully at publish time after
+// rotating the key.
func TestRemoteRotationNoInit(t *testing.T) {
- ts, _, _ := simpleTestServer(t)
+ ts := fullTestServer(t)
defer ts.Close()
repo := newBlankRepo(t, ts.URL)
defer os.RemoveAll(repo.baseDir)
err := repo.RotateKey(data.CanonicalTimestampRole, true, nil)
- require.Error(t, err)
- require.IsType(t, store.ErrMetaNotFound{}, err)
+ require.NoError(t, err)
}
// Rotates the keys. After the rotation, downloading the latest metadata
|
Fix test for rotation without explicit init by using a full test server
|
theupdateframework_notary
|
train
|
05fd597a671635037f369a85cce655ad302424e8
|
diff --git a/examples/cli.py b/examples/cli.py
index <HASH>..<HASH> 100644
--- a/examples/cli.py
+++ b/examples/cli.py
@@ -38,6 +38,10 @@ class CommandLineInterface(object):
for group in groups.split():
eval("self.add_{0}_options".format(group))(argument_parser)
+ argument_parser.add_argument(
+ "-l", "--loop", action="store_true",
+ help="restart after termination")
+
self.options = argument_parser.parse_args()
logformat = '%(message)s'
@@ -127,7 +131,7 @@ class CommandLineInterface(object):
def on_connect(self, llc):
return True
- def run(self):
+ def run_once(self):
if self.options.device is None:
self.options.device = ['']
@@ -141,9 +145,9 @@ class CommandLineInterface(object):
if self.options.mode is None:
self.options.role = None
- elif self.options.mode == 't':
+ elif self.options.mode in ('t', 'target'):
self.options.role = 'target'
- elif self.options.mode == 'i':
+ elif self.options.mode in ('i', 'initiator'):
self.options.role = 'initiator'
p2p_options = {
@@ -156,7 +160,10 @@ class CommandLineInterface(object):
}
try:
- while clf.connect(p2p=p2p_options): pass
+ return clf.connect(p2p=p2p_options)
finally:
clf.close()
+ def run(self):
+ while self.run_once() and self.options.loop:
+ pass
|
added loop flag for automatic restart, default behavior changed to exit after p2p link closed
|
nfcpy_nfcpy
|
train
|
de804eae7f9d3651037f155e28c1b4993947dca9
|
diff --git a/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/ArchiveExtractor.java b/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/ArchiveExtractor.java
index <HASH>..<HASH> 100644
--- a/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/ArchiveExtractor.java
+++ b/frontend-plugin-core/src/main/java/com/github/eirslett/maven/plugins/frontend/lib/ArchiveExtractor.java
@@ -37,6 +37,9 @@ final class DefaultArchiveExtractor implements ArchiveExtractor {
if (tarEntry.isDirectory()) {
destPath.mkdirs();
} else {
+ if (!destPath.getParentFile().exists()) {
+ destPath.getParentFile().mkdirs();
+ }
destPath.createNewFile();
boolean isExecutable = (tarEntry.getMode() & 0100) > 0;
destPath.setExecutable(isExecutable);
|
fixes case when Tarball extraction didn't create the parent directory for file we want to extract
|
eirslett_frontend-maven-plugin
|
train
|
dbbb1aeaab30e106f95d9f9a45571cb1e28bc760
|
diff --git a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/value/cas/JDBCValueContentAddressStorageImpl.java b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/value/cas/JDBCValueContentAddressStorageImpl.java
index <HASH>..<HASH> 100644
--- a/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/value/cas/JDBCValueContentAddressStorageImpl.java
+++ b/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/storage/value/cas/JDBCValueContentAddressStorageImpl.java
@@ -100,7 +100,7 @@ public class JDBCValueContentAddressStorageImpl implements ValueContentAddressSt
* %s must be replaced with original table name before compile Pattern.
*/
private static final String DB2_PK_CONSTRAINT_DETECT_PATTERN =
- "(.*DB2 SQL error+.*SQLCODE: -803+.*SQLSTATE: 23505+.*%s.*)+?";
+ "(.*DB2 SQL [Ee]rror+.*SQLCODE[:=].?-803+.*SQLSTATE[:=].?23505+.*JCR_VCAS_TEST.*)+?";
/**
* MYSQL_PK_CONSTRAINT_DETECT_PATTERN.
|
EXOJCR-<I>: "Some Unit Tests on DB2 related to the CAS plugin fail" fixed db2 error message parsing in accordance to a new driver
|
exoplatform_jcr
|
train
|
29949219034569659630bb2007a1b83ff46d4b81
|
diff --git a/src/shared/registerDependant.js b/src/shared/registerDependant.js
index <HASH>..<HASH> 100644
--- a/src/shared/registerDependant.js
+++ b/src/shared/registerDependant.js
@@ -15,6 +15,10 @@ define( function () {
deps[ deps.length ] = dependant;
dependant.registered = true;
+ if ( !keypath ) {
+ return;
+ }
+
// update dependants map
keys = keypath.split( '.' );
diff --git a/src/shared/resolveRef.js b/src/shared/resolveRef.js
index <HASH>..<HASH> 100644
--- a/src/shared/resolveRef.js
+++ b/src/shared/resolveRef.js
@@ -8,7 +8,7 @@ define( function () {
// `'bar.baz'` within the context stack `['foo']` might resolve to `'foo.bar.baz'`
resolveRef = function ( ractive, ref, contextStack ) {
- var keys, lastKey, contextKeys, innerMostContext, postfix, parentKeypath, parentValue, wrapped, keypath, context, ancestorErrorMessage;
+ var keypath, keys, lastKey, contextKeys, innerMostContext, postfix, parentKeypath, parentValue, wrapped, context, ancestorErrorMessage;
ancestorErrorMessage = 'Could not resolve reference - too many "../" prefixes';
@@ -18,12 +18,12 @@ define( function () {
return '';
}
- return contextStack[ contextStack.length - 1 ];
+ keypath = contextStack[ contextStack.length - 1 ];
}
// If a reference begins with '.', it's either a restricted reference or
// an ancestor reference...
- if ( ref.charAt( 0 ) === '.' ) {
+ else if ( ref.charAt( 0 ) === '.' ) {
// ...either way we need to get the innermost context
context = contextStack[ contextStack.length - 1 ];
@@ -41,47 +41,51 @@ define( function () {
}
contextKeys.push( ref );
- return contextKeys.join( '.' );
+ keypath = contextKeys.join( '.' );
}
// not an ancestor reference - must be a restricted reference (prepended with ".")
if ( !context ) {
- return ref.substring( 1 );
+ keypath = ref.substring( 1 );
}
- return context + ref;
+ else {
+ keypath = context + ref;
+ }
}
- keys = ref.split( '.' );
- lastKey = keys.pop();
- postfix = keys.length ? '.' + keys.join( '.' ) : '';
+ else {
+ keys = ref.split( '.' );
+ lastKey = keys.pop();
+ postfix = keys.length ? '.' + keys.join( '.' ) : '';
- // Clone the context stack, so we don't mutate the original
- contextStack = contextStack.concat();
+ // Clone the context stack, so we don't mutate the original
+ contextStack = contextStack.concat();
- // Take each context from the stack, working backwards from the innermost context
- while ( contextStack.length ) {
+ // Take each context from the stack, working backwards from the innermost context
+ while ( contextStack.length ) {
- innerMostContext = contextStack.pop();
- parentKeypath = innerMostContext + postfix;
+ innerMostContext = contextStack.pop();
+ parentKeypath = innerMostContext + postfix;
- parentValue = ractive.get( parentKeypath );
+ parentValue = ractive.get( parentKeypath );
- if ( wrapped = ractive._wrapped[ parentKeypath ] ) {
- parentValue = wrapped.get();
- }
+ if ( wrapped = ractive._wrapped[ parentKeypath ] ) {
+ parentValue = wrapped.get();
+ }
- if ( typeof parentValue === 'object' && parentValue !== null && parentValue.hasOwnProperty( lastKey ) ) {
- keypath = innerMostContext + '.' + ref;
- break;
+ if ( typeof parentValue === 'object' && parentValue !== null && parentValue.hasOwnProperty( lastKey ) ) {
+ keypath = innerMostContext + '.' + ref;
+ break;
+ }
}
- }
- if ( !keypath && ractive.get( ref ) !== undefined ) {
- keypath = ref;
+ if ( !keypath && ractive.get( ref ) !== undefined ) {
+ keypath = ref;
+ }
}
- return keypath;
+ return keypath.replace( /^./, '' );
};
return resolveRef;
diff --git a/src/shared/unregisterDependant.js b/src/shared/unregisterDependant.js
index <HASH>..<HASH> 100644
--- a/src/shared/unregisterDependant.js
+++ b/src/shared/unregisterDependant.js
@@ -19,6 +19,10 @@ define( function () {
deps.splice( index, 1 );
dependant.registered = false;
+ if ( !keypath ) {
+ return;
+ }
+
// update dependants map
keys = keypath.split( '.' );
|
prevent infinite recursion with ractive.update() (when called with no keypath)
|
ractivejs_ractive
|
train
|
d42535f5e52469cb195c75707709655fa2b62d30
|
diff --git a/airflow/models.py b/airflow/models.py
index <HASH>..<HASH> 100644
--- a/airflow/models.py
+++ b/airflow/models.py
@@ -528,7 +528,7 @@ class TaskInstance(Base):
end_date = Column(DateTime)
duration = Column(Float)
state = Column(String(20))
- try_number = Column(Integer)
+ try_number = Column(Integer, default=1)
hostname = Column(String(1000))
unixname = Column(String(1000))
job_id = Column(Integer)
@@ -926,20 +926,19 @@ class TaskInstance(Base):
"Next run after {0}".format(next_run)
)
elif force or self.state in State.runnable():
- msg = "\n" + ("-" * 80)
- if self.state == State.UP_FOR_RETRY:
- msg += "\nRetry run {self.try_number} out of {task.retries} "
- msg += "starting @{iso}\n"
- else:
- msg += "\nNew run starting @{iso}\n"
- msg += ("-" * 80)
- logging.info(msg.format(**locals()))
-
- self.start_date = datetime.now()
+ HR = "\n" + ("-" * 80) + "\n" # Line break
if self.state == State.UP_FOR_RETRY:
+ msg = (
+ "Retry run {self.try_number} out of {task.retries} "
+ "starting @{iso}")
self.try_number += 1
else:
+ msg = "New run starting @{iso}"
self.try_number = 1
+ msg = msg.format(**locals())
+ logging.info(HR + msg + HR)
+ self.start_date = datetime.now()
+
if self.state != State.QUEUED and (
self.pool or self.task.dag.concurrency_reached):
# If a pool is set for this task, marking the task instance
diff --git a/airflow/utils.py b/airflow/utils.py
index <HASH>..<HASH> 100644
--- a/airflow/utils.py
+++ b/airflow/utils.py
@@ -380,9 +380,8 @@ def json_ser(obj):
json serializer that deals with dates
usage: json.dumps(object, default=utils.json_ser)
"""
- if isinstance(obj, datetime):
- obj = obj.isoformat()
- return obj
+ if isinstance(obj, (datetime.datetime, datetime.date)):
+ return obj.isoformat()
def alchemy_to_dict(obj):
|
Addressing issues around try_number being off
|
apache_airflow
|
train
|
ca14bfba7d1eeea543c9e00ea33d1487a49e68e0
|
diff --git a/magic.py b/magic.py
index <HASH>..<HASH> 100644
--- a/magic.py
+++ b/magic.py
@@ -114,6 +114,13 @@ class Magic:
except MagicException as e:
return self._handle509Bug(e)
+ def from_descriptor(self, fd):
+ with self.lock:
+ try:
+ return maybe_decode(magic_descriptor(self.cookie, fd))
+ except MagicException as e:
+ return self._handle509Bug(e)
+
def _handle509Bug(self, e):
# libmagic 5.09 has a bug where it might fail to identify the
# mimetype of a file and returns null from magic_file (and
@@ -180,6 +187,20 @@ def from_buffer(buffer, mime=False):
return m.from_buffer(buffer)
+def from_descriptor(fd, mime=False):
+ """
+ Accepts a file descriptor and returns the detected filetype. Return
+ value is the mimetype if mime=True, otherwise a human readable
+ name.
+
+ >>> f = open("testdata/test.pdf")
+ >>> magic.from_descriptor(f.fileno())
+ 'PDF document, version 1.2'
+ """
+ m = _get_magic_type(mime)
+ return m.from_descriptor(fd)
+
+
libmagic = None
# Let's try to find magic or magic1
dll = ctypes.util.find_library('magic') \
@@ -287,6 +308,7 @@ _magic_file.errcheck = errorcheck_null
def magic_file(cookie, filename):
return _magic_file(cookie, coerce_filename(filename))
+
_magic_buffer = libmagic.magic_buffer
_magic_buffer.restype = c_char_p
_magic_buffer.argtypes = [magic_t, c_void_p, c_size_t]
@@ -297,6 +319,16 @@ def magic_buffer(cookie, buf):
return _magic_buffer(cookie, buf, len(buf))
+_magic_descriptor = libmagic.magic_descriptor
+_magic_descriptor.restype = c_char_p
+_magic_descriptor.argtypes = [magic_t, c_int]
+_magic_descriptor.errcheck = errorcheck_null
+
+
+def magic_descriptor(cookie, fd):
+ return _magic_descriptor(cookie, fd)
+
+
_magic_load = libmagic.magic_load
_magic_load.restype = c_int
_magic_load.argtypes = [magic_t, c_char_p]
@@ -306,6 +338,7 @@ _magic_load.errcheck = errorcheck_negative_one
def magic_load(cookie, filename):
return _magic_load(cookie, coerce_filename(filename))
+
magic_setflags = libmagic.magic_setflags
magic_setflags.restype = c_int
magic_setflags.argtypes = [magic_t, c_int]
diff --git a/magic.pyi b/magic.pyi
index <HASH>..<HASH> 100644
--- a/magic.pyi
+++ b/magic.pyi
@@ -13,12 +13,14 @@ class Magic:
def __init__(self, mime: bool = ..., magic_file: Optional[Any] = ..., mime_encoding: bool = ..., keep_going: bool = ..., uncompress: bool = ..., raw: bool = ...) -> None: ...
def from_buffer(self, buf: Union[bytes, str]) -> Text: ...
def from_file(self, filename: Union[bytes, str]) -> Text: ...
+ def from_descriptor(self, fd: int, mime: bool = ...) -> Text: ...
def setparam(self, param: Any, val: Any): ...
def getparam(self, param: Any): ...
def __del__(self) -> None: ...
def from_file(filename: Union[bytes, str], mime: bool = ...) -> Text: ...
def from_buffer(buffer: Union[bytes, str], mime: bool = ...) -> Text: ...
+def from_descriptor(fd: int, mime: bool = ...) -> Text: ...
libmagic: Any
dll: Any
@@ -39,6 +41,7 @@ magic_errno: Any
def magic_file(cookie: Any, filename: Any): ...
def magic_buffer(cookie: Any, buf: Any): ...
+def magic_descriptor(cookie: Any, fd: int): ...
def magic_load(cookie: Any, filename: Any): ...
magic_setflags: Any
diff --git a/test/test.py b/test/test.py
index <HASH>..<HASH> 100755
--- a/test/test.py
+++ b/test/test.py
@@ -56,6 +56,13 @@ class MagicTest(unittest.TestCase):
self.assertEqual('application/pdf',
magic.from_file(filename.encode('utf-8'), mime=True))
+ def test_from_descriptor_str_and_bytes(self):
+ with open(os.path.join(self.TESTDATA_DIR, "test.pdf")) as f:
+ self.assertEqual('application/pdf',
+ magic.from_descriptor(f.fileno(), mime=True))
+ self.assertEqual('application/pdf',
+ magic.from_descriptor(f.fileno(), mime=True))
+
def test_from_buffer_str_and_bytes(self):
m = magic.Magic(mime=True)
|
Added support for magic_descriptor routine
|
ahupp_python-magic
|
train
|
33f30f91482c67f50c679c5f12e649c0d6b3a8f6
|
diff --git a/packages/sproutcore-views/lib/views/collection_view.js b/packages/sproutcore-views/lib/views/collection_view.js
index <HASH>..<HASH> 100644
--- a/packages/sproutcore-views/lib/views/collection_view.js
+++ b/packages/sproutcore-views/lib/views/collection_view.js
@@ -65,7 +65,7 @@ SC.CollectionView = SC.ContainerView.extend(
var content = get(this, 'content');
if (content) {
- sc_assert(fmt("an ArrayController's content must implement SC.Array. You passed %@", [content]), content.addArrayObserver);
+ sc_assert(fmt("an ArrayController's content must implement SC.Array. You passed %@", [content]), content.addArrayObserver != null);
content.addArrayObserver(this);
}
this.arrayDidChange(content, 0, null, get(content, 'length'));
|
Incorrect use of sc_assert
You can't test for the existence of a function by passing it directly
to sc_assert, because it will try to invoke it instead.
|
emberjs_ember.js
|
train
|
39ab0705e29552ca5e8e2f4bceb920735e3e3646
|
diff --git a/js/cryptopia.js b/js/cryptopia.js
index <HASH>..<HASH> 100644
--- a/js/cryptopia.js
+++ b/js/cryptopia.js
@@ -3,7 +3,7 @@
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
-const { ExchangeError, InsufficientFunds, OrderNotFound, OrderNotCached } = require ('./base/errors');
+const { ExchangeError, InsufficientFunds, OrderNotFound, OrderNotCached, InvalidNonce } = require ('./base/errors');
// ---------------------------------------------------------------------------
@@ -527,24 +527,12 @@ module.exports = class cryptopia extends Exchange {
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
- let response = undefined;
- try {
- response = await this.privatePostCancelTrade (this.extend ({
- 'Type': 'Trade',
- 'OrderId': id,
- }, params));
- if (id in this.orders)
- this.orders[id]['status'] = 'canceled';
- } catch (e) {
- if (this.last_json_response) {
- let message = this.safeString (this.last_json_response, 'Error');
- if (message) {
- if (message.indexOf ('does not exist') >= 0)
- throw new OrderNotFound (this.id + ' cancelOrder() error: ' + this.last_http_response);
- }
- }
- throw e;
- }
+ let response = await this.privatePostCancelTrade (this.extend ({
+ 'Type': 'Trade',
+ 'OrderId': id,
+ }, params));
+ if (id in this.orders)
+ this.orders[id]['status'] = 'canceled';
return response;
}
@@ -729,25 +717,61 @@ module.exports = class cryptopia extends Exchange {
}
async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
- let response = await this.fetch2 (path, api, method, params, headers, body);
- if (api === 'web')
- return response;
- if (response) {
- if ('Success' in response)
- if (response['Success']) {
- return response;
- } else if ('Error' in response) {
- let error = this.safeString (response, 'error');
- if (typeof error !== 'undefined') {
- if (error.indexOf ('Insufficient Funds') >= 0)
- throw new InsufficientFunds (this.id + ' ' + this.json (response));
+ return this.fetch2 (path, api, method, params, headers, body);
+ }
+
nonce () {
return this.milliseconds ();
}
+ handleErrors (code, reason, url, method, headers, body) {
+ if (typeof body !== 'string')
+ return; // fallback to default error handler
+ if (body.length < 2)
+ return; // fallback to default error handler
+ const fixedJSONString = this.sanitizeBrokenJSONString (body);
+ if (fixedJSONString[0] === '{') {
+ let response = JSON.parse (fixedJSONString);
+ if ('Success' in response) {
+ if (response['Success'] === false) {
+ let error = this.safeString (response, 'Error');
+ let feedback = this.id;
+ if (typeof error === 'string') {
+ feedback = feedback + ' ' + error;
+ if (error.indexOf ('does not exist') >= 0) {
+ throw new OrderNotFound (feedback);
+ }
+ if (error.indexOf ('Insufficient Funds') >= 0) {
+ throw new InsufficientFunds (feedback);
+ }
+ if (error.indexOf ('Nonce has already been used') >= 0) {
+ throw new InvalidNonce (feedback);
+ }
+ } else {
+ feedback = feedback + ' ' + fixedJSONString;
}
+ throw new ExchangeError (feedback);
}
+ }
}
- throw new ExchangeError (this.id + ' ' + this.json (response));
+ }
+
+ // sometimes cryptopia will return a unicode symbol before actual JSON string begins,
+ // so we have to sanitize that broken response by finding the first occurence of '{'
+ // in the string and then parsing from there
+ sanitizeBrokenJSONString(jsonString) {
+ const braceCode = 123; // '{'
+ let i=0;
+ for (i=0; i < jsonString.length; i++) {
+ if (jsonString.charCodeAt (i) == braceCode) {
+ return jsonString.substr (i);
+ }
+ }
+ return jsonString;
+ }
+
+ // we have to sanitize JSON before trying to parse
+ parseJson (response, responseBody, url, method) {
+ return super.parseJson (response, this.sanitizeBrokenJSONString (responseBody), url, method);
}
};
|
cryptopia: implemented handleErrors, sanitized JSON responses, added exceptions
|
ccxt_ccxt
|
train
|
c9a65eb848f74693b35575940c8b9061b38d5118
|
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index <HASH>..<HASH> 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -28,4 +28,4 @@ bundle exec guard
Guard will re-run each test suite when changes are made to its corresponding files.
-To run **just one test**: Flavio Castelli blogged about [how to execute a single unit test (or even a single test method)](https://webcache.googleusercontent.com/search?q=cache:lVNaE5lsPq0J:http://flavio.castelli.name/2010/05/28/rails_execute_single_test%2Bflavio.castelli.name/2010/05/28/rails_execute_single_test+!g&num=1&hl=en&strip=1&vwsrc=0) instead of running the complete unit test suite.
+To run **just one test**: Flavio Castelli blogged about [how to execute a single unit test (or even a single test method)](https://flavio.castelli.me/2010/05/28/rails_execute_single_test/) instead of running the complete unit test suite.
diff --git a/app/controllers/devise_token_auth/application_controller.rb b/app/controllers/devise_token_auth/application_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/devise_token_auth/application_controller.rb
+++ b/app/controllers/devise_token_auth/application_controller.rb
@@ -42,5 +42,13 @@ module DeviseTokenAuth
return ActiveModelSerializers.config.adapter == :json_api
end
+ def recoverable_enabled?
+ resource_class.devise_modules.include?(:recoverable)
+ end
+
+ def confirmable_enabled?
+ resource_class.devise_modules.include?(:confirmable)
+ end
+
end
end
diff --git a/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb b/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb
+++ b/app/controllers/devise_token_auth/omniauth_callbacks_controller.rb
@@ -31,7 +31,7 @@ module DeviseTokenAuth
set_token_on_resource
create_auth_params
- if resource_class.devise_modules.include?(:confirmable)
+ if confirmable_enabled?
# don't send confirmation email!!!
@resource.skip_confirmation!
end
diff --git a/app/controllers/devise_token_auth/passwords_controller.rb b/app/controllers/devise_token_auth/passwords_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/devise_token_auth/passwords_controller.rb
+++ b/app/controllers/devise_token_auth/passwords_controller.rb
@@ -76,10 +76,10 @@ module DeviseTokenAuth
}
# ensure that user is confirmed
- @resource.skip_confirmation! if @resource.devise_modules.include?(:confirmable) && !@resource.confirmed_at
+ @resource.skip_confirmation! if confirmable_enabled? && !@resource.confirmed_at
# allow user to change password once without current_password
- @resource.allow_password_change = true;
+ @resource.allow_password_change = true if recoverable_enabled?
@resource.save!
@@ -113,7 +113,7 @@ module DeviseTokenAuth
end
if @resource.send(resource_update_method, password_resource_params)
- @resource.allow_password_change = false
+ @resource.allow_password_change = false if recoverable_enabled?
@resource.save!
yield @resource if block_given?
@@ -126,7 +126,8 @@ module DeviseTokenAuth
protected
def resource_update_method
- if DeviseTokenAuth.check_current_password_before_update == false or @resource.allow_password_change == true
+ allow_password_change = recoverable_enabled? && @resource.allow_password_change == true
+ if DeviseTokenAuth.check_current_password_before_update == false || allow_password_change
"update_attributes"
else
"update_with_password"
diff --git a/app/controllers/devise_token_auth/registrations_controller.rb b/app/controllers/devise_token_auth/registrations_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/devise_token_auth/registrations_controller.rb
+++ b/app/controllers/devise_token_auth/registrations_controller.rb
@@ -23,7 +23,7 @@ module DeviseTokenAuth
@redirect_url ||= DeviseTokenAuth.default_confirm_success_url
# success redirect url is required
- if resource_class.devise_modules.include?(:confirmable) && !@redirect_url
+ if confirmable_enabled? && !@redirect_url
return render_create_error_missing_confirm_success_url
end
|
Check if recoverable is enabled in case allow_password_change is used
|
lynndylanhurley_devise_token_auth
|
train
|
2fdb605580a8bbc78a02bf4d8b6b75b060691a79
|
diff --git a/Resources/public/js/sequence/Player/Question/Controllers/MatchQuestionCtrl.js b/Resources/public/js/sequence/Player/Question/Controllers/MatchQuestionCtrl.js
index <HASH>..<HASH> 100644
--- a/Resources/public/js/sequence/Player/Question/Controllers/MatchQuestionCtrl.js
+++ b/Resources/public/js/sequence/Player/Question/Controllers/MatchQuestionCtrl.js
@@ -39,28 +39,6 @@
}
}
};
-
- /**
- * find all orphan answers and set them in an array
- */
- this.setOrphanAnswers = function () {
- var hasSolution;
- for (var i=0; i<this.question.secondSet.length; i++) {
- hasSolution = false;
- console.log(this.solutions);
- for (var j=0; j<this.solutions.length; j++) {
- console.log(this.question.secondSet[i].id);
- console.log(this.solutions[j].secondId);
- if (this.question.secondSet[i].id === this.solutions[j].secondId) {
- hasSolution = true;
- }
- }
- if (!hasSolution) {
- this.orphanAnswers.push(this.question.secondSet[i]);
- }
- }
- console.log(this.orphanAnswers);
- };
/**
* check if a Hint has already been used (in paper)
@@ -138,11 +116,20 @@
this.feedbackIsVisible = true;
this.solutions = result.solutions;
this.questionFeedback = result.feedback;
- console.log(this.solutions);
+ console.log(this.question);
+ console.log(this.connections);
+ console.log(this.dropped);
}.bind(this));
};
this.checkAnswerValidity = function (label) {
+ var answers;
+ if (this.question.toBind) {
+ answers = this.connections;
+ }
+ else {
+ answers = this.dropped;
+ }
if (!this.orphanAnswersAreChecked) {
var hasSolution;
for (var i=0; i<this.question.secondSet.length; i++) {
@@ -160,11 +147,11 @@
}
var valid = false;
- for (var i=0; i<this.connections.length; i++) {
- if (this.connections[i].target === label.id) {
+ for (var i=0; i<answers.length; i++) {
+ if (answers[i].target === label.id) {
for (var j=0; j<this.solutions.length; j++) {
if (this.solutions[j].secondId === label.id) {
- if (this.solutions[j].firstId === this.connections[i].source) {
+ if (this.solutions[j].firstId === answers[i].source) {
valid = true;
}
}
@@ -175,8 +162,8 @@
for (var i=0; i<this.orphanAnswers.length; i++) {
if (this.orphanAnswers[i].id === label.id) {
valid2 = true;
- for (var j=0; j<this.connections.length; j++) {
- if (this.orphanAnswers[i].id === this.connections[j].target) {
+ for (var j=0; j<answers.length; j++) {
+ if (this.orphanAnswers[i].id === answers[j].target) {
valid2 = false;
}
}
@@ -186,11 +173,18 @@
};
this.getStudentAnswers = function (label) {
+ var answers_to_check;
+ if (this.question.toBind) {
+ answers_to_check = this.connections;
+ }
+ else {
+ answers_to_check = this.dropped;
+ }
var answers = [];
- for (var i=0; i<this.connections.length; i++) {
- if (this.connections[i].target === label.id) {
+ for (var i=0; i<answers_to_check.length; i++) {
+ if (answers_to_check[i].target === label.id) {
for (var j=0; j<this.question.firstSet.length; j++) {
- if (this.question.firstSet[j].id === this.connections[i].source) {
+ if (this.question.firstSet[j].id === answers_to_check[i].source) {
answers.push(this.question.firstSet[j].data);
}
}
|
[ExoBundle] Get immediate feedbacks on dragNdrop questions
|
claroline_Distribution
|
train
|
6fb88aa0f5749196fd63bae07833ec5e2af483e8
|
diff --git a/lib/Event.php b/lib/Event.php
index <HASH>..<HASH> 100644
--- a/lib/Event.php
+++ b/lib/Event.php
@@ -37,6 +37,7 @@ class Event extends ApiResource
const APPLICATION_FEE_REFUND_UPDATED = 'application_fee.refund.updated';
const BALANCE_AVAILABLE = 'balance.available';
const CHARGE_CAPTURED = 'charge.captured';
+ const CHARGE_EXPIRED = 'charge.expired';
const CHARGE_FAILED = 'charge.failed';
const CHARGE_PENDING = 'charge.pending';
const CHARGE_REFUNDED = 'charge.refunded';
diff --git a/lib/Product.php b/lib/Product.php
index <HASH>..<HASH> 100644
--- a/lib/Product.php
+++ b/lib/Product.php
@@ -19,9 +19,9 @@ namespace Stripe;
* @property string $name
* @property mixed $package_dimensions
* @property bool $shippable
- * @property Collection $skus
* @property string $statement_descriptor
* @property string $type
+ * @property string $unit_label
* @property int $updated
* @property string $url
*
|
Removed SKU collection from Product
Added unit_label to Product
Added charge.expired event to event list
|
stripe_stripe-php
|
train
|
c477d7b30eae511f2ea9c2a73ae24c113f2394ee
|
diff --git a/src/main/org/openscience/cdk/fingerprint/SignatureFingerprinter.java b/src/main/org/openscience/cdk/fingerprint/SignatureFingerprinter.java
index <HASH>..<HASH> 100644
--- a/src/main/org/openscience/cdk/fingerprint/SignatureFingerprinter.java
+++ b/src/main/org/openscience/cdk/fingerprint/SignatureFingerprinter.java
@@ -46,7 +46,6 @@ public class SignatureFingerprinter implements IFingerprinter {
/**
* Initialize the fingerprinter with a defult signature depth of 1.
*/
- @TestMethod("testFingerprint")
public SignatureFingerprinter() {
this(1);
}
@@ -56,7 +55,6 @@ public class SignatureFingerprinter implements IFingerprinter {
*
* @param depth The depth of the signatures to calculate.
*/
- @TestMethod("testFingerprint")
public SignatureFingerprinter(int depth) {
this.signatureDepth = depth;
}
|
removing test method annotation from constructors, this method was renamed to getRawFingerprint and does not explicit test object construction
Change-Id: Ibfca<I>f8ad8e7a7fd8c7bec<I>fe2cdc<I>d
|
cdk_cdk
|
train
|
e2ef4ec347a5d8096aa70c1d239d094cb0fcd6c1
|
diff --git a/core/eolearn/core/eoworkflow.py b/core/eolearn/core/eoworkflow.py
index <HASH>..<HASH> 100644
--- a/core/eolearn/core/eoworkflow.py
+++ b/core/eolearn/core/eoworkflow.py
@@ -252,12 +252,37 @@ class EOWorkflow:
:rtype: Digraph
"""
dot = Digraph()
+ dep_to_dot_name = self._get_dep_to_dot_name_mapping(self.ordered_dependencies)
+
for dep in self.ordered_dependencies:
for input_task in dep.inputs:
- dot.edge(self._get_dot_name(self.uuid_dict[input_task.uuid]), self._get_dot_name(dep))
+ dot.edge(dep_to_dot_name[self.uuid_dict[input_task.uuid]],
+ dep_to_dot_name[dep])
return dot
@staticmethod
+ def _get_dep_to_dot_name_mapping(dependencies):
+ dot_name_to_deps = {}
+ for dep in dependencies:
+ dot_name = EOWorkflow._get_dot_name(dep)
+
+ if dot_name not in dot_name_to_deps:
+ dot_name_to_deps[dot_name] = [dep]
+ else:
+ dot_name_to_deps[dot_name].append(dep)
+
+ dep_to_dot_name = {}
+ for dot_name, deps in dot_name_to_deps.items():
+ if len(deps) == 1:
+ dep_to_dot_name[deps[0]] = dot_name
+ continue
+
+ for idx, dep in enumerate(deps):
+ dep_to_dot_name[dep] = dot_name + str(idx)
+
+ return dep_to_dot_name
+
+ @staticmethod
def _get_dot_name(dependency):
""" Generates names of tasks used in dot graph
"""
diff --git a/core/eolearn/tests/test_eoworkflow.py b/core/eolearn/tests/test_eoworkflow.py
index <HASH>..<HASH> 100644
--- a/core/eolearn/tests/test_eoworkflow.py
+++ b/core/eolearn/tests/test_eoworkflow.py
@@ -2,8 +2,10 @@ import unittest
import logging
import functools
import concurrent.futures
+from io import StringIO
from hypothesis import given, strategies as st
+import networkx as nx
from eolearn.core import EOTask, EOWorkflow, Dependency, WorkflowResults
from eolearn.core.eoworkflow import CyclicDependencyError, _UniqueIdGenerator
@@ -151,6 +153,31 @@ class TestEOWorkflow(unittest.TestCase):
))
+class TestGraph(unittest.TestCase):
+
+ def setUp(self):
+ input_task1 = InputTask()
+ input_task2 = InputTask()
+ divide_task = DivideTask()
+
+ self.workflow = EOWorkflow(dependencies=[
+ Dependency(task=input_task1, inputs=[]),
+ Dependency(task=input_task2, inputs=[]),
+ Dependency(task=divide_task, inputs=[input_task1, input_task2])
+ ])
+
+ def test_graph_nodes_and_edges(self):
+ dot = self.workflow.get_dot()
+ dot_file = StringIO()
+ dot_file.write(dot.source)
+ dot_file.seek(0)
+
+ graph = nx.drawing.nx_pydot.read_dot(dot_file)
+
+ self.assertEqual(graph.number_of_nodes(), 3)
+ self.assertEqual(graph.number_of_edges(), 2)
+
+
class TestWorkflowResults(unittest.TestCase):
pass
|
In dependency graph, index tasks with the same name.
|
sentinel-hub_eo-learn
|
train
|
36c739bf0d4d0dfcee96499f37c4a08f8bb9d297
|
diff --git a/src/Transit/File.php b/src/Transit/File.php
index <HASH>..<HASH> 100644
--- a/src/Transit/File.php
+++ b/src/Transit/File.php
@@ -24,6 +24,13 @@ class File {
protected $_cache = array();
/**
+ * Raw $_FILES data.
+ *
+ * @var array
+ */
+ protected $_data = array();
+
+ /**
* Absolute file path.
*
* @var string
@@ -33,10 +40,19 @@ class File {
/**
* Store the file path.
*
- * @param string $path
+ * @param string|array $path
* @throws \Transit\Exception\IoException
*/
public function __construct($path) {
+ if (is_array($path)) {
+ if (empty($path['tmp_name'])) {
+ throw new IoException('Passing via array must use $_FILES data');
+ }
+
+ $this->_data = $path;
+ $path = $path['tmp_name'];
+ }
+
if (!file_exists($path)) {
throw new IoException(sprintf('%s does not exist', $path));
}
@@ -63,6 +79,16 @@ class File {
}
/**
+ * Return the $_FILES data.
+ *
+ * @param string $key
+ * @return string
+ */
+ public function data($key) {
+ return !empty($this->_data[$key]) ? $this->_data[$key] : null;
+ }
+
+ /**
* Delete the file.
*
* @return bool
@@ -123,10 +149,13 @@ class File {
*/
public function ext() {
return $this->_cache(__FUNCTION__, function($file) {
- // Removed because of fileinfo bug
- //$ext = MimeType::getExtFromType($file->type(), true);
+ // @version 1.1.1 Removed because of fileinfo bug
+ // return MimeType::getExtFromType($file->type(), true);
- return mb_strtolower(pathinfo($file->path(), PATHINFO_EXTENSION));
+ // @version 1.2.0 Allow support for $_FILES array
+ $path = $this->data('name') ?: $file->path();
+
+ return mb_strtolower(pathinfo($path, PATHINFO_EXTENSION));
});
}
@@ -265,7 +294,10 @@ class File {
* @return string
*/
public function name() {
- return pathinfo($this->_path, PATHINFO_FILENAME);
+ // @version 1.2.0 Don't use tmp_name if available
+ $path = $this->data('name') ?: $this->path();
+
+ return pathinfo($path, PATHINFO_FILENAME);
}
/**
@@ -344,7 +376,7 @@ class File {
// We can't use the file command on windows
if (!defined('PHP_WINDOWS_VERSION_MAJOR')) {
- $type = shell_exec(sprintf("file -i --mime %s", escapeshellarg($file->path())));
+ $type = shell_exec(sprintf("file -b --mime %s", escapeshellarg($file->path())));
if ($type && strpos($type, ';') !== false) {
$type = strstr($type, ';', true);
@@ -360,7 +392,7 @@ class File {
// Check the mimetype against the extension
// If they are different, use the extension since fileinfo returns invalid mimetypes
- $extType = MimeType::getTypeFromExt($file->ext());
+ $extType = $this->data('type') ?: MimeType::getTypeFromExt($file->ext());
if ($type !== $extType) {
$type = $extType;
diff --git a/tests/Transit/FileTest.php b/tests/Transit/FileTest.php
index <HASH>..<HASH> 100644
--- a/tests/Transit/FileTest.php
+++ b/tests/Transit/FileTest.php
@@ -8,6 +8,7 @@
namespace Transit;
use Transit\Test\TestCase;
+use \Exception;
class FileTest extends TestCase {
@@ -21,6 +22,25 @@ class FileTest extends TestCase {
}
/**
+ * Test object construction.
+ */
+ public function testConstruct() {
+ try {
+ $file = new File(array()); // missing tmp_name
+ $this->assertTrue(false);
+ } catch (Exception $e) {
+ $this->assertTrue(true);
+ }
+
+ try {
+ $file = new File(array('tmp_name' => 'some/path.jpg')); // invalid path
+ $this->assertTrue(false);
+ } catch (Exception $e) {
+ $this->assertTrue(true);
+ }
+ }
+
+ /**
* Test that basename() returns file name with extension.
*/
public function testBasename() {
@@ -28,6 +48,17 @@ class FileTest extends TestCase {
}
/**
+ * Test $_FILES data.
+ */
+ public function testData() {
+ $this->assertEquals(null, $this->object->data('name'));
+
+ // Test using an array
+ $file = new File($this->data);
+ $this->assertEquals('scott-pilgrim.jpg', $file->data('name'));
+ }
+
+ /**
* Test that delete() deletes the file.
*/
public function testDelete() {
@@ -60,6 +91,10 @@ class FileTest extends TestCase {
*/
public function testExt() {
$this->assertEquals('jpg', $this->object->ext());
+
+ // Test using an array
+ $file = new File($this->data);
+ $this->assertEquals('jpg', $file->ext());
}
/**
@@ -246,7 +281,7 @@ class FileTest extends TestCase {
// This will actually return text/plain because magic cant determine a text/javascript file
// It can also return text/x-c in some weird corner cases
- // If either of these happen, fall back to the extension derived mimetype
+ // If either of these happen, fall back to the extension derived mimetype (or from $_FILES)
$this->assertEquals('text/javascript', $file->type());
}
|
Added $_FILES support
Fixed "file" command
|
ljgpartners_transit
|
train
|
14594faa80f1e843082f17bdf1e680fc433a5f88
|
diff --git a/mod/data/restorelib.php b/mod/data/restorelib.php
index <HASH>..<HASH> 100644
--- a/mod/data/restorelib.php
+++ b/mod/data/restorelib.php
@@ -99,6 +99,14 @@ function data_restore_mods($mod,$restore) {
unset($database->notification); /// Unset it if null to get proper Moodle 2.0 default (0) applied
}
+ // We have to recode the scale field if it's <0 (positive is a grade, not a scale)
+ if ($database->scale < 0) {
+ $scale = backup_getid($restore->backup_unique_code, 'scale', abs($database->scale));
+ if ($scale) {
+ $database->scale = -($scale->new_id);
+ }
+ }
+
$newid = $DB->insert_record ('data', $database);
//Do some output
@@ -727,5 +735,3 @@ function data_decode_content_links_caller($restore) {
return $status;
}
-
-
|
MDL-<I> database activity - remap scale on restore ; merged from <I>_STABLE
|
moodle_moodle
|
train
|
52fcc5cf31e333b18162d16688e9c8ca5ee5ed8b
|
diff --git a/lib/client.js b/lib/client.js
index <HASH>..<HASH> 100644
--- a/lib/client.js
+++ b/lib/client.js
@@ -48,7 +48,7 @@ Client.prototype.send_message = function(msg) {
// console.log("Write:")
// console.log(" Length: " + len_str + " (" + msg_utf8.length + ")");
// console.log(" Msg: ...");
- // console.log(msg_overall)
+ console.log(msg_overall)
this.socket.write(msg_overall);
}
@@ -253,7 +253,7 @@ Client.prototype.autodoc = function(sexp_string, cursor_position, pkg) {
var didCursor = false;
for(var i = 0; i < forms.children.length; i++) {
var form = forms.children[i];
- output_forms.push('"' + form.source + '"');
+ output_forms.push('"' + form.source.replace(/\\/g, "\\\\").replace(/\"/g, "\\\"") + '"');
if (cursor_position >= form.start && cursor_position <= form.end && !didCursor) {
output_forms.push('SWANK::%CURSOR-MARKER%');
didCursor = true;
|
Fixed another escaping issue with autodoc
|
sjlevine_swank-client-js
|
train
|
40a816b2e05337778900f6bea551b5d81b398a74
|
diff --git a/css_optimiser.php b/css_optimiser.php
index <HASH>..<HASH> 100644
--- a/css_optimiser.php
+++ b/css_optimiser.php
@@ -76,9 +76,7 @@ if($is_custom)
{
setcookie ('custom_template', $_REQUEST['custom'], time()+360000);
}
-else {
- setcookie ('custom_template', '', time()-3600);
-}
+
rmdirr('temp');
if(isset($_REQUEST['case_properties'])) $css->set_cfg('case_properties',$_REQUEST['case_properties']);
@@ -88,9 +86,7 @@ if(!isset($_REQUEST['compress_fw']) && isset($_REQUEST['post'])) $css->set_cfg('
if(isset($_REQUEST['merge_selectors'])) $css->set_cfg('merge_selectors', $_REQUEST['merge_selectors']);
if(isset($_REQUEST['optimise_shorthands'])) $css->set_cfg('optimise_shorthands',$_REQUEST['optimise_shorthands']);
if(!isset($_REQUEST['rbs']) && isset($_REQUEST['post'])) $css->set_cfg('remove_bslash',false);
-if(isset($_REQUEST['preserve_css'])) {$css->set_cfg('preserve_css',true);
-print 3;exit;
-}
+if(isset($_REQUEST['preserve_css'])) $css->set_cfg('preserve_css',true);
if(isset($_REQUEST['sort_sel'])) $css->set_cfg('sort_selectors',true);
if(isset($_REQUEST['sort_de'])) $css->set_cfg('sort_properties',true);
if(isset($_REQUEST['remove_last_sem'])) $css->set_cfg('remove_last_;',true);
@@ -171,9 +167,9 @@ if(isset($_REQUEST['timestamp'])) $css->set_cfg('timestamp',true);
name="custom" cols="33" rows="4"><?php
if($is_custom) echo
htmlspecialchars($_REQUEST['custom']);
- // elseif(isset($_COOKIE['custom_template']) &&
- // !empty($_COOKIE['custom_template'])) echo
- // htmlspecialchars($_COOKIE['custom_template']);
+ elseif(isset($_COOKIE['custom_template']) &&
+ !empty($_COOKIE['custom_template'])) echo
+ htmlspecialchars($_COOKIE['custom_template']);
?></textarea>
</fieldset>
<fieldset id="options">
|
Whoops, sorry... fixes to my additions/debugging
|
Cerdic_CSSTidy
|
train
|
cc0179a2ec214d8501c150eabd902811e924e0b8
|
diff --git a/library/src/uk/co/senab/photoview/IPhotoView.java b/library/src/uk/co/senab/photoview/IPhotoView.java
index <HASH>..<HASH> 100644
--- a/library/src/uk/co/senab/photoview/IPhotoView.java
+++ b/library/src/uk/co/senab/photoview/IPhotoView.java
@@ -176,4 +176,12 @@ public interface IPhotoView {
*/
void setZoomable(boolean zoomable);
+ /**
+ * Enables rotation via PhotoView internal functions.
+ * Name is chosen so it won't collide with View.setRotation(float) in API since 11
+ *
+ * @param rotationDegree - Degree to rotate PhotoView by, should be in range 0 to 360
+ */
+ void setPhotoViewRotation(float rotationDegree);
+
}
diff --git a/library/src/uk/co/senab/photoview/PhotoView.java b/library/src/uk/co/senab/photoview/PhotoView.java
index <HASH>..<HASH> 100644
--- a/library/src/uk/co/senab/photoview/PhotoView.java
+++ b/library/src/uk/co/senab/photoview/PhotoView.java
@@ -53,6 +53,11 @@ public class PhotoView extends ImageView implements IPhotoView {
}
@Override
+ public void setPhotoViewRotation(float rotationDegree) {
+ mAttacher.setPhotoViewRotation(rotationDegree);
+ }
+
+ @Override
public boolean canZoom() {
return mAttacher.canZoom();
}
diff --git a/library/src/uk/co/senab/photoview/PhotoViewAttacher.java b/library/src/uk/co/senab/photoview/PhotoViewAttacher.java
index <HASH>..<HASH> 100644
--- a/library/src/uk/co/senab/photoview/PhotoViewAttacher.java
+++ b/library/src/uk/co/senab/photoview/PhotoViewAttacher.java
@@ -258,13 +258,14 @@ public class PhotoViewAttacher implements IPhotoView, View.OnTouchListener,
return true;
}
- private float lastRotation = 0;
+ private float mLastRotation = 0;
- public boolean setRotation(float degrees) {
- mSuppMatrix.postRotate(lastRotation - degrees);
- lastRotation = degrees;
+ @Override
+ public void setPhotoViewRotation(float degrees) {
+ degrees %= 360;
+ mSuppMatrix.postRotate(mLastRotation - degrees);
+ mLastRotation = degrees;
checkAndDisplayMatrix();
- return true;
}
public final ImageView getImageView() {
|
Rotation finalized with interface, javadoc and implementation
|
chrisbanes_PhotoView
|
train
|
da842cc8a5fb3bc098a1d4b29dfa3d8dcc79663e
|
diff --git a/lib/mactag/builder.rb b/lib/mactag/builder.rb
index <HASH>..<HASH> 100644
--- a/lib/mactag/builder.rb
+++ b/lib/mactag/builder.rb
@@ -41,12 +41,13 @@ module Mactag
# files are separated with a whitespace.
#
def tags
- @@tags.collect!(&:tag)
- @@tags.flatten! # For the Rails fucker...
- @@tags.collect! { |file| File.expand_path(file) }
- @@tags.collect! { |file| Dir.glob(file) }
- @@tags.uniq!
- @@tags.join(' ')
+ tags = all_tags
+ tags.flatten!
+ tags.compact!
+ tags.collect! { |file| File.expand_path(file) }
+ tags.collect! { |file| Dir.glob(file) }
+ tags.uniq!
+ tags.join(' ')
end
##
@@ -58,13 +59,20 @@ module Mactag
Mactag.warn 'Gem home path does not exist on your system'
end
- if @@tags.collect(&:files).flatten.empty?
+ if all_tags.flatten.compact.empty?
Mactag.warn 'You did not specify anything to tag'
else
system "cd #{Rails.root} && #{Mactag::Config.binary} #{Mactag::Builder.tags}"
puts "Successfully generated TAGS file"
end
end
+
+
+ private
+
+ def all_tags
+ @all_tags ||= @@tags.collect!(&:tag)
+ end
end
end
end
|
Cache all tags to avoid same error messages to be played more than once.
|
rejeep_mactag
|
train
|
0f100a16705b78dc54d61cde0ce8980913fe9f1e
|
diff --git a/pyemu/pst/pst_handler.py b/pyemu/pst/pst_handler.py
index <HASH>..<HASH> 100644
--- a/pyemu/pst/pst_handler.py
+++ b/pyemu/pst/pst_handler.py
@@ -2067,7 +2067,7 @@ class Pst(object):
if col == "count":
data["count"].append(par_pg.shape[0])
continue
- print(col)
+ #print(col)
mn = par_pg.loc[:,col].min()
mx = par_pg.loc[:,col].max()
if mn == mx:
diff --git a/pyemu/utils/gw_utils.py b/pyemu/utils/gw_utils.py
index <HASH>..<HASH> 100644
--- a/pyemu/utils/gw_utils.py
+++ b/pyemu/utils/gw_utils.py
@@ -1399,7 +1399,7 @@ def setup_sfr_obs(sfr_out_file,seg_group_dict=None,ins_file=None,model=None,
os.chdir(bd)
if df is not None:
df.loc[:,"obsnme"] = df.index.values
- df.obgnme = df.obsnme.apply(lambda x: "flaqx" if x.startswith("fa") else "flout")
+ df.loc[:,"obgnme"] = df.obsnme.apply(lambda x: "flaqx" if x.startswith("fa") else "flout")
return df
@@ -1440,6 +1440,7 @@ def apply_sfr_obs():
#print(obs_base,agg)
results.append([kper,obs_base,agg["flaqx"],agg["flout"]])
df = pd.DataFrame(data=results,columns=["kper","obs_base","flaqx","flout"])
+ df.sort_values(by=["kper","obs_base"],inplace=True)
df.to_csv(sfr_out_file+".processed",sep=' ',index=False)
return df
|
bug fix in sfr obs - need to make sure and sort after the df is read
|
jtwhite79_pyemu
|
train
|
051440758a8daaf28f840be01074366466d62821
|
diff --git a/insanities/web/reverse.py b/insanities/web/reverse.py
index <HASH>..<HASH> 100644
--- a/insanities/web/reverse.py
+++ b/insanities/web/reverse.py
@@ -81,9 +81,11 @@ class Reverse(object):
self._builder_kwargs = builder_kwargs or {}
def _copy(self, **kw):
+ builder_kwargs = dict(self._builder_kwargs)
+ builder_kwargs.update(kw.pop('builder_kwargs', {}))
vars = dict(locations=self._locations,
- builder=self._builder,
- builder_kwargs=self._builder_kwargs)
+ builder=self._builder,
+ builder_kwargs=builder_kwargs)
vars.update(kw)
return self.__class__(**vars)
@@ -104,7 +106,11 @@ class Reverse(object):
# path - urlencoded str
path = ''.join([b(**self._builder_kwargs) for b in self._builder.builders])
return URL(path, host=host)
- return URL('')
+ raise ReverseError('Unknown url %r' % self._locations)
+
+ @property
+ def as_url(self):
+ return str(self)
@classmethod
def from_handler(cls, handler, env=None):
diff --git a/tests/web/reverse.py b/tests/web/reverse.py
index <HASH>..<HASH> 100644
--- a/tests/web/reverse.py
+++ b/tests/web/reverse.py
@@ -119,7 +119,7 @@ class ReverseTests(unittest.TestCase):
def test_one_handler(self):
'Reverse one match'
r = web.Reverse.from_handler(web.match('/', 'index'))
- self.assertEqual(str(r.index), '/')
+ self.assertEqual(r.index.as_url, '/')
def test_few_handlers(self):
'Reverse a few handlers'
@@ -129,9 +129,9 @@ class ReverseTests(unittest.TestCase):
web.match('/news', 'news'),
)
r = web.Reverse.from_handler(chain)
- self.assertEqual(str(r.index), '/')
- self.assertEqual(str(r.docs), '/docs')
- self.assertEqual(str(r.news), '/news')
+ self.assertEqual(r.index.as_url, '/')
+ self.assertEqual(r.docs.as_url, '/docs')
+ self.assertEqual(r.news.as_url, '/news')
def test_nested_cases(self):
'Reverse with nested web.cases'
@@ -142,9 +142,9 @@ class ReverseTests(unittest.TestCase):
web.cases(
web.match('/news', 'news'))))
r = web.Reverse.from_handler(chain)
- self.assertEqual(str(r.index), '/')
- self.assertEqual(str(r.docs), '/docs')
- self.assertEqual(str(r.news), '/news')
+ self.assertEqual(r.index.as_url, '/')
+ self.assertEqual(r.docs.as_url, '/docs')
+ self.assertEqual(r.news.as_url, '/news')
def test_nested_cases_with_prefixes(self):
'Reverse with nested web.cases with web.prefixes'
@@ -158,11 +158,11 @@ class ReverseTests(unittest.TestCase):
web.match('/list', 'newslist')))
r = web.Reverse.from_handler(chain)
- self.assertEqual(str(r.index), '/')
- self.assertEqual(str(r.docs), '/docs/list')
- self.assertEqual(str(r.newslist), '/news/list')
- self.assertEqual(str(r.doc(id=1)), '/docs/1')
- self.assertEqual(str(r.news(id=1)), '/news/1')
+ self.assertEqual(r.index.as_url, '/')
+ self.assertEqual(r.docs.as_url, '/docs/list')
+ self.assertEqual(r.newslist.as_url, '/news/list')
+ self.assertEqual(r.doc(id=1).as_url, '/docs/1')
+ self.assertEqual(r.news(id=1).as_url, '/news/1')
def test_unicode(self):
'Reverse with unicode'
@@ -175,7 +175,7 @@ class ReverseTests(unittest.TestCase):
)
r = web.Reverse.from_handler(chain)
- self.assertEqual(str(r.unicode1), 'http://xn--o1a/%D0%B7/')
- self.assertEqual(str(r.unicode2(slug=u'ю')), 'http://xn--o1a/%D0%B7/%D1%8E')
- self.assertEqual(str(r.unicode3(slug=u'ю')), 'http://xn--o1a/%D0%B4/%D1%8E')
- self.assertEqual(str(r.unicode4(slug1=u'д', slug2=u'ю')), 'http://xn--o1a/%D0%B4/%D1%8E')
+ self.assertEqual(r.unicode1.as_url, 'http://xn--o1a/%D0%B7/')
+ self.assertEqual(r.unicode2(slug=u'ю').as_url, 'http://xn--o1a/%D0%B7/%D1%8E')
+ self.assertEqual(r.unicode3(slug=u'ю').as_url, 'http://xn--o1a/%D0%B4/%D1%8E')
+ self.assertEqual(r.unicode4(slug1=u'д', slug2=u'ю').as_url, 'http://xn--o1a/%D0%B4/%D1%8E')
|
`as_url` property of `Reverse`
|
SmartTeleMax_iktomi
|
train
|
bdec3b969707d418b136bda9dc5ae1c8deed5e18
|
diff --git a/mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/MapWorkerPool.java b/mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/MapWorkerPool.java
index <HASH>..<HASH> 100644
--- a/mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/MapWorkerPool.java
+++ b/mapsforge-map/src/main/java/org/mapsforge/map/layer/renderer/MapWorkerPool.java
@@ -34,9 +34,9 @@ public class MapWorkerPool implements Runnable {
// is likely to be blocked on I/O reading map data. Technically this value can change, so a
// better implementation, maybe one that also takes the available memory into account, would
// be good.
- public static final int DEFAULT_NUMBER_OF_THREADS = Runtime.getRuntime().availableProcessors() + 1;
- // For stability reasons (see #591), we set number of threads to 1
- public static int NUMBER_OF_THREADS = 1;
+ // For stability reasons (see #591), we set default number of threads to 1
+ public static final int DEFAULT_NUMBER_OF_THREADS = 1;//Runtime.getRuntime().availableProcessors() + 1;
+ public static int NUMBER_OF_THREADS = DEFAULT_NUMBER_OF_THREADS;
public static boolean DEBUG_TIMING = false;
|
Multithreaded rendering: better handling of default threads number
|
mapsforge_mapsforge
|
train
|
30804904885128ae2c2854897979d27485d88b50
|
diff --git a/Tests/TestDriver.php b/Tests/TestDriver.php
index <HASH>..<HASH> 100644
--- a/Tests/TestDriver.php
+++ b/Tests/TestDriver.php
@@ -92,20 +92,41 @@ $_test_names = array(
'OIDUtil',
'DiffieHellman',
'HMACSHA1',
- 'Association'
+ 'Association',
+ 'StoreTest',
);
-// Only run store tests if -s or --test-stores is specified on the
-// command line because store backends will probably not be installed.
-if (in_array('--test-stores', $argv) ||
- in_array('-s', $argv)) {
- $_test_names[] = 'StoreTest';
+function selectTests($names) {
+ global $_test_names;
+ $lnames = array_map('strtolower', $names);
+ $include = array();
+ $exclude = array();
+ foreach ($_test_names as $t) {
+ $l = strtolower($t);
+ if (in_array($l, $lnames)) {
+ $include[] = $t;
+ }
+
+ if (in_array("/$l", $lnames)) {
+ $exclude[] = $t;
+ }
+ }
+
+ if (!count($include)) {
+ $include = $_test_names;
+ }
+
+ return array_diff($include, $exclude);
}
// Load OpenID library tests
-function loadSuite() {
+function loadSuite($names=null) {
global $_test_names;
global $_test_dir;
- return loadTests($_test_dir, $_test_names);
+ if ($names === null) {
+ $names = $_test_names;
+ }
+ $selected = selectTests($names);
+ return loadTests($_test_dir, $selected);
}
?>
diff --git a/texttest.php b/texttest.php
index <HASH>..<HASH> 100644
--- a/texttest.php
+++ b/texttest.php
@@ -39,12 +39,12 @@ function microtime_float()
// Drop $argv[0] (command name)
array_shift($argv);
-$t = array_search('thorough', $argv);
+$t = array_search('--thorough', $argv);
if ($t !== FALSE && $t !== NULL) {
define('Tests_Net_OpenID_DH_thorough', TRUE);
}
-$suites = loadSuite();
+$suites = loadSuite($argv);
$totals = array(
'run' => 0,
|
[project @ Add test-selection logic to command-line test driver]
|
openid_php-openid
|
train
|
3f658065aba215b5ac5998a4fe37f66e3db5bc6e
|
diff --git a/tests/test_pagination.py b/tests/test_pagination.py
index <HASH>..<HASH> 100644
--- a/tests/test_pagination.py
+++ b/tests/test_pagination.py
@@ -45,7 +45,7 @@ class PaginationTest(MapMyFitnessTestCase):
workouts_paginator = self.mmf.workout.search(user=9118466, started_after=datetime.datetime(2014, 4, 1), per_page=2)
- self.assertEqual(workouts_paginator.page_range, [1, 2])
+ self.assertTrue((workouts_paginator.page_range == [1, 2]) or (workouts_paginator.page_range == range(1, 3)))
page1 = workouts_paginator.page(1)
page2 = workouts_paginator.page(2)
|
Cover Py3 returning a range, not a list.
|
JasonSanford_mapmyfitness-python
|
train
|
a87a06b139c174a08d4d5714825a72477cc08b71
|
diff --git a/lib/watir/element_locator.rb b/lib/watir/element_locator.rb
index <HASH>..<HASH> 100644
--- a/lib/watir/element_locator.rb
+++ b/lib/watir/element_locator.rb
@@ -184,12 +184,14 @@ module Watir
end
def by_id
- id = @selector[:id]
+ selector = @selector.dup
+ id = selector.delete(:id)
return unless id && id.kind_of?(String)
- element = @driver.find_element(:id, id)
- tag_name = @selector[:tag_name]
+ tag_name = selector.delete(:tag_name)
+ return unless selector.empty? # multiple attributes
+ element = @driver.find_element(:id, id)
return if tag_name && !(tag_name === element.tag_name)
element
|
Take all conditions into account when locating by id (if needed)
|
watir_watir
|
train
|
156acb012a2e980269f9332b86c595c0d1b62636
|
diff --git a/lib/train/platforms/detect/helpers/os_common.rb b/lib/train/platforms/detect/helpers/os_common.rb
index <HASH>..<HASH> 100644
--- a/lib/train/platforms/detect/helpers/os_common.rb
+++ b/lib/train/platforms/detect/helpers/os_common.rb
@@ -35,19 +35,23 @@ module Train::Platforms::Detect::Helpers
def command_output(cmd)
res = @backend.run_command(cmd)
+ stdout = res.stdout
+ stderr = res.stderr
# When you try to execute command using ssh connction as root user and you have provided ssh user identity file
# it gives standard output to login as authorised user other than root. To show this standard ouput as an error
# to user we are matching the string of stdout and raising the error here so that user gets exact information.
- if @backend.class.to_s == "Train::Transports::SSH::Connection" && res.stdout =~ /Please login as the user/
- raise Train::UserError, "SSH failed: #{res.stdout}"
+ if @backend.class.to_s == "Train::Transports::SSH::Connection"
+ if stdout =~ /Please login as the user/
+ raise Train::UserError, "SSH failed: #{stdout}"
+ end
+
+ if stderr =~ /WARNING: Your password has expired/
+ raise Train::UserError, "SSH failed: #{stderr}"
+ end
end
- if @backend.class.to_s == "Train::Transports::SSH::Connection" && res.stderr =~ /WARNING: Your password has expired/
- raise Train::UserError, "SSH failed: #{res.stderr}"
- end
-
- res.stdout.strip! unless res.stdout.nil?
- res.stdout
+ stdout.strip! unless stdout.nil?
+ stdout
end
def unix_uname_s
|
assign vars to avoid mock failure
|
inspec_train
|
train
|
129d58c64f4130b49aa99cbcc74bdfc6813fe7cb
|
diff --git a/Database/Model.php b/Database/Model.php
index <HASH>..<HASH> 100644
--- a/Database/Model.php
+++ b/Database/Model.php
@@ -127,9 +127,6 @@ class Model
*/
public function __construct(array $data = [], $isNew = true)
{
- // Get table schema
- static::loadSchema();
-
// Set defaults
foreach (static::schema() as $field => $properties) {
$this->{$field} = $properties['default'];
@@ -153,6 +150,7 @@ class Model
*/
protected static function loadSchema()
{
+ // Make sure there's a place to store the schema
if (!array_key_exists(static::$_table, static::$_schema)) {
static::$_schema[static::$_table] = null;
}
@@ -180,6 +178,7 @@ class Model
*/
public static function schema()
{
+ static::loadSchema();
return array_key_exists(static::$_table, static::$_schema) ? static::$_schema[static::$_table] : null;
}
|
Load the schema when calling Model::schema() instead of having to do it manually.
|
nirix_radium
|
train
|
5d5cc018d3e1dbef16d8ee5721e4bb9ba8c706d9
|
diff --git a/core/codegen/vdm2jml/src/test/java/org/overture/vdm2jml/tests/OpenJmlValidationBase.java b/core/codegen/vdm2jml/src/test/java/org/overture/vdm2jml/tests/OpenJmlValidationBase.java
index <HASH>..<HASH> 100644
--- a/core/codegen/vdm2jml/src/test/java/org/overture/vdm2jml/tests/OpenJmlValidationBase.java
+++ b/core/codegen/vdm2jml/src/test/java/org/overture/vdm2jml/tests/OpenJmlValidationBase.java
@@ -65,26 +65,23 @@ abstract public class OpenJmlValidationBase
{
String openJmlDir = System.getenv(OPENJML_ENV_VAR);
- if (openJmlDir != null)
- {
- openJml = new File(openJmlDir, OPEN_JML);
- jmlRuntime = new File(openJmlDir, JML_RUNTIME);
- }
+ openJml = new File(openJmlDir, OPEN_JML);
+ jmlRuntime = new File(openJmlDir, JML_RUNTIME);
}
public void assumeOpenJml()
{
- assumeFile(openJml);
+ assumeFile(OPEN_JML, openJml);
}
public void assumeJmlRuntime()
{
- assumeFile(jmlRuntime);
+ assumeFile(JML_RUNTIME, jmlRuntime);
}
- private void assumeFile(File file)
+ private void assumeFile(String fileName, File file)
{
- Assume.assumeTrue("Could not find " + file.getName(), file != null
+ Assume.assumeTrue("Could not find " + fileName, file != null
&& file.exists());
}
|
Small tweak to the testing of the JML Generator when no $OPENJML environment variable can be located
|
overturetool_overture
|
train
|
56db00180f588cd3a5da7ae5861eefda00fbac56
|
diff --git a/CHANGES.txt b/CHANGES.txt
index <HASH>..<HASH> 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,4 +1,5 @@
2.1.0
+ * Fix ordering of static cells (CASSANDRA-7763)
Merged from 2.0:
* Fix dropping collection when it's the last regular column (CASSANDRA-7744)
* Properly reject operations on list index with conditions (CASSANDRA-7499)
diff --git a/src/java/org/apache/cassandra/db/composites/AbstractCType.java b/src/java/org/apache/cassandra/db/composites/AbstractCType.java
index <HASH>..<HASH> 100644
--- a/src/java/org/apache/cassandra/db/composites/AbstractCType.java
+++ b/src/java/org/apache/cassandra/db/composites/AbstractCType.java
@@ -104,6 +104,17 @@ public abstract class AbstractCType implements CType
public int compare(Composite c1, Composite c2)
{
+ if (c1.isStatic() != c2.isStatic())
+ {
+ // Static sorts before non-static no matter what, except for empty which
+ // always sort first
+ if (c1.isEmpty())
+ return c2.isEmpty() ? 0 : -1;
+ if (c2.isEmpty())
+ return 1;
+ return c1.isStatic() ? -1 : 1;
+ }
+
int s1 = c1.size();
int s2 = c2.size();
int minSize = Math.min(s1, s2);
diff --git a/src/java/org/apache/cassandra/db/composites/CompoundSparseCellNameType.java b/src/java/org/apache/cassandra/db/composites/CompoundSparseCellNameType.java
index <HASH>..<HASH> 100644
--- a/src/java/org/apache/cassandra/db/composites/CompoundSparseCellNameType.java
+++ b/src/java/org/apache/cassandra/db/composites/CompoundSparseCellNameType.java
@@ -267,6 +267,17 @@ public class CompoundSparseCellNameType extends AbstractCompoundCellNameType
@Override
public int compare(Composite c1, Composite c2)
{
+ if (c1.isStatic() != c2.isStatic())
+ {
+ // Static sorts before non-static no matter what, except for empty which
+ // always sort first
+ if (c1.isEmpty())
+ return c2.isEmpty() ? 0 : -1;
+ if (c2.isEmpty())
+ return 1;
+ return c1.isStatic() ? -1 : 1;
+ }
+
int s1 = c1.size();
int s2 = c2.size();
int minSize = Math.min(s1, s2);
|
Fix ordering of static cells
patch by slebresne; reviewed by benedict for CASSANDRA-<I>
|
Stratio_stratio-cassandra
|
train
|
2c8001417a82cb2448cf47acc19c8e5dbace678d
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLocalResultSet.java b/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLocalResultSet.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLocalResultSet.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLocalResultSet.java
@@ -83,6 +83,10 @@ public class OLocalResultSet implements OResultSet {
}
}
+ public long getTotalExecutionTime() {
+ return totalExecutionTime;
+ }
+
@Override
public void close() {
executionPlan.close();
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLocalResultSetLifecycleDecorator.java b/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLocalResultSetLifecycleDecorator.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLocalResultSetLifecycleDecorator.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLocalResultSetLifecycleDecorator.java
@@ -89,4 +89,8 @@ public class OLocalResultSetLifecycleDecorator implements OResultSet {
public boolean isDetached() {
return entity instanceof OInternalResultSet;
}
+
+ public OResultSet getInternal() {
+ return entity;
+ }
}
|
Exposed elapsed time for internal use
|
orientechnologies_orientdb
|
train
|
96429ff94f29ba6d14625e92ad7d0a8185568503
|
diff --git a/src/Psalm/ErrorBaseline.php b/src/Psalm/ErrorBaseline.php
index <HASH>..<HASH> 100644
--- a/src/Psalm/ErrorBaseline.php
+++ b/src/Psalm/ErrorBaseline.php
@@ -285,7 +285,7 @@ class ErrorBaseline
$baselineDoc->formatOutput = true;
$xml = preg_replace_callback(
- '/<files (psalm-version="[^"]+") (?:php-version="(.+)">\n)/',
+ '/<files (psalm-version="[^"]+") (?:php-version="(.+)"(\/?>)\n)/',
/**
* @param array<int, string> $matches
*/
@@ -301,7 +301,7 @@ class ErrorBaseline
"\n" .
' "' .
"\n" .
- '>' .
+ $matches[3] .
"\n";
},
$baselineDoc->saveXML()
|
apply pretty formatting when there are no issues (#<I>)
|
vimeo_psalm
|
train
|
1cf0538df029f579cb992f108e1b01ddec518e9f
|
diff --git a/aeron-client/src/main/java/io/aeron/logbuffer/LogBufferUnblocker.java b/aeron-client/src/main/java/io/aeron/logbuffer/LogBufferUnblocker.java
index <HASH>..<HASH> 100644
--- a/aeron-client/src/main/java/io/aeron/logbuffer/LogBufferUnblocker.java
+++ b/aeron-client/src/main/java/io/aeron/logbuffer/LogBufferUnblocker.java
@@ -42,16 +42,15 @@ public class LogBufferUnblocker
final int index = indexByTermCount(expectedTermCount);
final long rawTail = rawTailVolatile(logMetaDataBuffer, index);
final int termId = termId(rawTail);
+ final int tailOffset = termOffset(rawTail, termLength);
+ final int blockedOffset = computeTermOffsetFromPosition(blockedPosition, positionBitsToShift);
- if (activeTermCount == (expectedTermCount - 1) && (blockedPosition & 0xFFFF_FFFFL) == termLength)
+ if (activeTermCount == (expectedTermCount - 1) && blockedOffset == 0)
{
- final int currentTermId = termId(rawTailVolatile(logMetaDataBuffer));
+ final int currentTermId = termId(rawTailVolatile(logMetaDataBuffer, indexByTermCount(activeTermCount)));
return rotateLog(logMetaDataBuffer, activeTermCount, currentTermId);
}
- final int tailOffset = termOffset(rawTail, termLength);
- final int blockedOffset = computeTermOffsetFromPosition(blockedPosition, positionBitsToShift);
-
switch (TermUnblocker.unblock(logMetaDataBuffer, termBuffers[index], blockedOffset, tailOffset, termId))
{
case UNBLOCKED_TO_END:
|
[Java] Check that the block position is the end of the previous term. Issue #<I>.
|
real-logic_aeron
|
train
|
58699a55627fd9ac942c343b93b46e6c578a67de
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -45,6 +45,12 @@ Bug.prototype.parse = function() {
readable += ' which is tracked for Firefox ' + firstTracked;
}
+ // do you know if there's an open needinfo
+
+ if (this.hasNeedInfo()) {
+ readable += ' awaiting an answer on a request for information';
+ }
+
return readable;
}
|
add the text for awaiting needinfo
|
mozilla-bteam_bugzilla-readable-status
|
train
|
16496b5e7f751af7418bb76537ea4b09af197096
|
diff --git a/lib/Route.php b/lib/Route.php
index <HASH>..<HASH> 100644
--- a/lib/Route.php
+++ b/lib/Route.php
@@ -22,7 +22,7 @@ class Route
*/
private $callback;
/**
- * @var string
+ * @var array
*/
private $parameter;
@@ -64,7 +64,7 @@ class Route
}
/**
- * @return string
+ * @return array
*/
public function getParameter()
{
diff --git a/lib/Router.php b/lib/Router.php
index <HASH>..<HASH> 100644
--- a/lib/Router.php
+++ b/lib/Router.php
@@ -69,12 +69,8 @@ class Router
}
if (method_exists($controller, $method)) {
- if (is_array($route->getParameter())) {
- $refMethod = new ReflectionMethod($callback->getController(), $method);
- $return = $refMethod->invokeArgs($controller, $route->getParameter());
- } else {
- $return = $controller->$method();
- }
+ $refMethod = new ReflectionMethod($callback->getController(), $method);
+ $return = $refMethod->invokeArgs($controller, $route->getParameter());
if ($this->postProcessor != null) {
return $this->postProcessor->process($return);
|
Simplified Router and fixed PHPDoc
|
timtegeler_routerunner
|
train
|
1a0bdff3af6e4f0e5ff2f5f5f0cb40ee51bb4668
|
diff --git a/packages/reporters/cli/src/BundleReport.js b/packages/reporters/cli/src/BundleReport.js
index <HASH>..<HASH> 100644
--- a/packages/reporters/cli/src/BundleReport.js
+++ b/packages/reporters/cli/src/BundleReport.js
@@ -58,7 +58,7 @@ export default function BundleReport(
for (let asset of largestAssets) {
// Add a row for the asset.
rows.push(
- <Row key={`asset:${asset.id}`}>
+ <Row key={`bundle:${bundle.id}:asset:${asset.id}`}>
<Cell>
{asset == assets[assets.length - 1] ? '└── ' : '├── '}
{formatFilename(asset.filePath, {})}
|
BundleReport: assets based on their bundle as well
|
parcel-bundler_parcel
|
train
|
8aa72fc1be5bfa5653ff703ac20245aeeb7f86e6
|
diff --git a/src/xray/backends.py b/src/xray/backends.py
index <HASH>..<HASH> 100644
--- a/src/xray/backends.py
+++ b/src/xray/backends.py
@@ -60,14 +60,27 @@ class InMemoryDataStore(AbstractDataStore):
def convert_to_cf_variable(array):
+ """Converts an XArray into an XArray suitable for saving as a netCDF
+ variable
+ """
data = array.data
attributes = array.attributes.copy()
if isinstance(data, pd.DatetimeIndex):
+ # DatetimeIndex objects need to be encoded into numeric arrays
(data, units, calendar) = datetimeindex2num(data)
attributes['units'] = units
attributes['calendar'] = calendar
elif data.dtype == np.dtype('O'):
+ # Unfortunately, pandas.Index arrays are often have dtype=object even
+ # if they were created from an array with a sensible datatype (e.g.,
+ # pandas.Float64Index always dtype=object for some reason). Because we
+ # allow for doing math with coordinates, these object arrays can
+ # propagate onward into other variables, which is why we don't only
+ # apply this check to XArrays with data that is a pandas.Index.
dtype = np.array(data.reshape(-1)[0]).dtype
+ # N.B. the "astype" call will fail if data cannot be cast to the type
+ # of its first element (which is probably the only sensible thing to
+ # do).
data = np.asarray(data).astype(dtype)
return xarray.XArray(array.dimensions, data, attributes)
|
Better comments describing convert_to_cf_variable
|
pydata_xarray
|
train
|
4e656726761fad97cc256fe3022e360e0c5cd390
|
diff --git a/picocli-examples/src/main/java/picocli/examples/defaultprovider/TwoPass.java b/picocli-examples/src/main/java/picocli/examples/defaultprovider/TwoPass.java
index <HASH>..<HASH> 100644
--- a/picocli-examples/src/main/java/picocli/examples/defaultprovider/TwoPass.java
+++ b/picocli-examples/src/main/java/picocli/examples/defaultprovider/TwoPass.java
@@ -31,8 +31,8 @@ public class TwoPass {
List<String> remainder;
}
- @Command(name = "my-command", mixinStandardHelpOptions = true, version = "...",
- description = "...")
+ @Command(name = "my-command", mixinStandardHelpOptions = true, version = "my-command 1.0",
+ description = "Demonstrates a command that allows users to specify the location of a \"profile\" file with default values for the command line arguments")
static class FinalPass implements Runnable {
@Option(names = "--profile", description = "...")
File profilePath = new File(System.getProperty("user.dir"), "my-command.properties");
@@ -65,6 +65,8 @@ public class TwoPass {
args = ("--profile=" + path.getAbsolutePath() + " -b123 --long-option USER-SPECIFIED").split(" ");
+ //args = new String[] {"-h"}; // shows help for my-command (not for FirstPass)
+
FirstPass firstPass = new FirstPass();
CommandLine cmd = new CommandLine(firstPass);
cmd.parseArgs(args); // first pass
|
[#<I>] add (commented out) user request for help to demonstrate that the correct help message would be shown
|
remkop_picocli
|
train
|
a54ad33b9f69b8ff419380931399c53c57d27612
|
diff --git a/azurerm/internal/services/appconfiguration/app_configuration_resource_test.go b/azurerm/internal/services/appconfiguration/app_configuration_resource_test.go
index <HASH>..<HASH> 100644
--- a/azurerm/internal/services/appconfiguration/app_configuration_resource_test.go
+++ b/azurerm/internal/services/appconfiguration/app_configuration_resource_test.go
@@ -54,7 +54,7 @@ func TestAccAppConfiguration_requiresImport(t *testing.T) {
data.ResourceTest(t, r, []resource.TestStep{
{
- Config: r.free(data),
+ Config: r.standard(data),
Check: resource.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
|
r/app_configuration: updating the requiresImport test to use a standard tier
There can only be a single "free" instance in a subscription at any one time,
as there's a free test checking that sku can be provisioned - updating the
requiresImport test to use a standard sku makes this pass consistently.
|
terraform-providers_terraform-provider-azurerm
|
train
|
5c5c1b6bee07ec79c8757c35bd6a183b7f48d819
|
diff --git a/Alchemy/Kernel/Kernel.php b/Alchemy/Kernel/Kernel.php
index <HASH>..<HASH> 100755
--- a/Alchemy/Kernel/Kernel.php
+++ b/Alchemy/Kernel/Kernel.php
@@ -244,7 +244,7 @@ class Kernel implements KernelInterface
if (! ($response instanceof Response || $response instanceof JsonResponse)) {
if ($this->annotationReader->getAnnotation('JsonResponse')) {
-
+ $controllerData = $response;
$response = new JsonResponse();
$response->setData($controllerData);
} else {
|
litle fix for json response data, bug
|
phpalchemy_phpalchemy
|
train
|
18bbde4cdc1706110831e6d1d9495b57261d0f1b
|
diff --git a/netmiko/base_connection.py b/netmiko/base_connection.py
index <HASH>..<HASH> 100644
--- a/netmiko/base_connection.py
+++ b/netmiko/base_connection.py
@@ -321,8 +321,18 @@ class BaseSSHConnection(object):
raise AttributeError("Network device does not support 'check_enable_mode()' method")
- def check_config_mode(self):
- pass
+ def check_config_mode(self, check_string=')#'):
+ '''
+ Checks if the device is in configuration mode or not
+
+ Returns a boolean
+ '''
+
+ output = self.send_command('\n', strip_prompt=False, strip_command=False)
+ if check_string in output:
+ return True
+ else:
+ return False
def send_config_file(self, config_file=None, commit=False):
diff --git a/netmiko/juniper/juniper_ssh.py b/netmiko/juniper/juniper_ssh.py
index <HASH>..<HASH> 100644
--- a/netmiko/juniper/juniper_ssh.py
+++ b/netmiko/juniper/juniper_ssh.py
@@ -61,6 +61,17 @@ class JuniperSSH(BaseSSHConnection):
return output
+ def check_config_mode(self, check_string=']'):
+ '''
+ Checks if the device is in configuration mode or not
+
+ Returns a boolean
+ '''
+
+ # Call parent class with Juniper check_string
+ return super(JuniperSSH, self).check_config_mode(check_string=check_string)
+
+
def commit(self, delay_factor=10):
"""Commit the candidate configuration.
diff --git a/netmiko/ssh_connection.py b/netmiko/ssh_connection.py
index <HASH>..<HASH> 100644
--- a/netmiko/ssh_connection.py
+++ b/netmiko/ssh_connection.py
@@ -67,16 +67,3 @@ class SSHConnection(BaseSSHConnection):
return output
-
- def check_config_mode(self, check_string=')#'):
- '''
- Checks if the device is in configuration mode or not
-
- Returns a boolean
- '''
-
- output = self.send_command('\n', strip_prompt=False, strip_command=False)
- if check_string in output:
- return True
- else:
- return False
|
Moving check_config_mode to BaseSSHConnection; creating Juniper specific call of check_config_Mode
|
ktbyers_netmiko
|
train
|
7b24607fe21558c54c0dc9a87144c044e5d4790b
|
diff --git a/pusher/pusher.py b/pusher/pusher.py
index <HASH>..<HASH> 100644
--- a/pusher/pusher.py
+++ b/pusher/pusher.py
@@ -40,7 +40,7 @@ def join_attributes(attributes):
if not isinstance(attr, six.text_type):
raise TypeError('Each attr should be %s' % text)
- return u','.join(attributes)
+ return six.text_type(',').join(attributes)
class Pusher(object):
"""Client for the Pusher HTTP API.
|
Replace u'' literal with six.text_type() for python <I> support
|
pusher_pusher-http-python
|
train
|
b90b9038716f1b1af2eb60ef099904f8f1428867
|
diff --git a/leaflet_storage/views.py b/leaflet_storage/views.py
index <HASH>..<HASH> 100644
--- a/leaflet_storage/views.py
+++ b/leaflet_storage/views.py
@@ -253,6 +253,7 @@ class UpdateMapPermissions(UpdateView):
user = self.request.user
if self.object.owner and not user == self.object.owner:
del form.fields['edit_status']
+ del form.fields['share_status']
return form
def form_valid(self, form):
|
Only owner can change share_status
|
umap-project_django-leaflet-storage
|
train
|
985e8caaf2e0b927e6d63bcdf19d65cf50cf88d5
|
diff --git a/spyderlib/plugins/inspector.py b/spyderlib/plugins/inspector.py
index <HASH>..<HASH> 100644
--- a/spyderlib/plugins/inspector.py
+++ b/spyderlib/plugins/inspector.py
@@ -531,7 +531,7 @@ class ObjectInspector(SpyderPluginWidget):
definition = ''
if text['note']:
- note = ''.join(['Type: ', text['note'], '\n\n\n'])
+ note = ''.join(['Type: ', text['note'], '\n\n----\n\n'])
else:
note = ''
|
Object Inspector: Add a transition marker between header and docstring in plain text
|
spyder-ide_spyder
|
train
|
c4ec182c50ad01f8bab4619ff8fbc678590a4e2a
|
diff --git a/vendor/showdown.js b/vendor/showdown.js
index <HASH>..<HASH> 100644
--- a/vendor/showdown.js
+++ b/vendor/showdown.js
@@ -676,7 +676,8 @@ var _DoHeaders = function(text) {
/*
text = text.replace(/
- ^(\#{1,6}) // $1 = string of #'s
+ ^[ ]{0,3}
+ (\#{1,6}) // $1 = string of #'s
[ \t]*
(.+?) // $2 = Header text
[ \t]*
@@ -685,7 +686,7 @@ var _DoHeaders = function(text) {
/gm, function() {...});
*/
- text = text.replace(/^(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
+ text = text.replace(/^[ ]{0,3}(\#{1,6})[ \t]*(.+?)[ \t]*\#*\n+/gm,
function(wholeMatch,m1,m2) {
var h_level = m1.length;
return hashBlock("<h" + h_level + ' id="' + headerId(m2) + '">' + _RunSpanGamut(m2) + "</h" + h_level + ">");
|
Handle 0 to 3 spaces before # in headings (Solves #<I>)
This solves the problem where we for example have a heading inside a
<div>. It is solved in the same way as lists and other stuff is handled
in Showdown. There are, however, several problems still, e.g. handling
headings within a deeper HTML structure.
|
gnab_remark
|
train
|
ccd7d7de3d550a18822b953a4d8f8467f30e62bf
|
diff --git a/keyring/backend.py b/keyring/backend.py
index <HASH>..<HASH> 100644
--- a/keyring/backend.py
+++ b/keyring/backend.py
@@ -224,6 +224,17 @@ class SchemeSelectable:
"""
Allow a backend to select different "schemes" for the
username and service.
+
+ >>> backend = SchemeSelectable()
+ >>> backend._query('contoso', 'alice')
+ {'username': 'alice', 'service': 'contoso'}
+ >>> backend._query('contoso')
+ {'service': 'contoso'}
+ >>> backend.scheme = 'KeypassXC'
+ >>> backend._query('contoso', 'alice')
+ {'UserName': 'alice', 'Title': 'contoso'}
+ >>> backend._query('contoso', 'alice', foo='bar')
+ {'UserName': 'alice', 'Title': 'contoso', 'foo': 'bar'}
"""
scheme = 'default'
|
Add tests for SchemeSelectable.
|
jaraco_keyring
|
train
|
e4f41e7883a54bc6773617f6267b435f5c31413e
|
diff --git a/allennlp/data/dataset_readers/multiprocess_dataset_reader.py b/allennlp/data/dataset_readers/multiprocess_dataset_reader.py
index <HASH>..<HASH> 100644
--- a/allennlp/data/dataset_readers/multiprocess_dataset_reader.py
+++ b/allennlp/data/dataset_readers/multiprocess_dataset_reader.py
@@ -3,7 +3,7 @@ import glob
import logging
import random
-from torch.multiprocessing import Process, Queue, log_to_stderr
+from torch.multiprocessing import Manager, Process, Queue, log_to_stderr
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.instance import Instance
@@ -94,16 +94,17 @@ class MultiprocessDatasetReader(DatasetReader):
to use the _instances iterator we define here.)
"""
def __init__(self) -> None:
- self.output_queue = Queue(outer_self.output_queue_size)
+ self.manager = Manager()
+ self.output_queue = self.manager.Queue(outer_self.output_queue_size)
self.num_workers = outer_self.num_workers
def __iter__(self) -> Iterator[Instance]:
# pylint: disable=protected-access
- return outer_self._instances(file_path, self.output_queue)
+ return outer_self._instances(file_path, self.manager, self.output_queue)
return QIterable()
- def _instances(self, file_path: str, output_queue: Queue) -> Iterator[Instance]:
+ def _instances(self, file_path: str, manager: Manager, output_queue: Queue) -> Iterator[Instance]:
"""
A generator that reads instances off the output queue and yields them up
until none are left (signified by all ``num_workers`` workers putting their
@@ -113,7 +114,7 @@ class MultiprocessDatasetReader(DatasetReader):
num_shards = len(shards)
# If we want multiple epochs per read, put shards in the queue multiple times.
- input_queue = Queue(num_shards * self.epochs_per_read + self.num_workers)
+ input_queue = manager.Queue(num_shards * self.epochs_per_read + self.num_workers)
for _ in range(self.epochs_per_read):
random.shuffle(shards)
for shard in shards:
diff --git a/allennlp/data/iterators/multiprocess_iterator.py b/allennlp/data/iterators/multiprocess_iterator.py
index <HASH>..<HASH> 100644
--- a/allennlp/data/iterators/multiprocess_iterator.py
+++ b/allennlp/data/iterators/multiprocess_iterator.py
@@ -1,7 +1,7 @@
from typing import Iterable, Iterator, List, Optional
import logging
-from torch.multiprocessing import Process, Queue, get_logger
+from torch.multiprocessing import Manager, Process, Queue, get_logger
from allennlp.common.checks import ConfigurationError
from allennlp.data.instance import Instance
@@ -107,8 +107,9 @@ class MultiprocessIterator(DataIterator):
if num_epochs is None:
raise ConfigurationError("Multiprocess Iterator must be run for a fixed number of epochs")
- output_queue = Queue(self.output_queue_size)
- input_queue = Queue(self.output_queue_size * self.batch_size)
+ manager = Manager()
+ output_queue = manager.Queue(self.output_queue_size)
+ input_queue = manager.Queue(self.output_queue_size * self.batch_size)
# Start process that populates the queue.
self.queuer = Process(target=_queuer, args=(instances, input_queue, self.num_workers, num_epochs))
|
use managers for queues (#<I>)
|
allenai_allennlp
|
train
|
a35cce5f7a457e9aee9a0f794b88d7bc4da4e0eb
|
diff --git a/spec/chromium-spec.js b/spec/chromium-spec.js
index <HASH>..<HASH> 100644
--- a/spec/chromium-spec.js
+++ b/spec/chromium-spec.js
@@ -21,8 +21,9 @@ describe('chromium feature', function () {
listener = null
})
- xdescribe('heap snapshot', function () {
+ describe('heap snapshot', function () {
it('does not crash', function () {
+ if (process.env.TRAVIS === 'true') return
process.atomBinding('v8_util').takeHeapSnapshot()
})
})
|
Enable takeHeapSnapshot spec
|
electron_electron
|
train
|
daea43619d4ce7af026cc92912e6e50f6d6adf56
|
diff --git a/persephone/model.py b/persephone/model.py
index <HASH>..<HASH> 100644
--- a/persephone/model.py
+++ b/persephone/model.py
@@ -330,11 +330,11 @@ class Model:
steps_since_last_record = 0
# Save the model.
- path = os.path.join(self.exp_dir, "model", "model_best.ckpt")
- if not os.path.exists(os.path.dirname(path)):
- os.mkdir(os.path.dirname(path))
- saver.save(sess, path)
- self.saved_model_path = path
+ checkpoint_path = os.path.join(self.exp_dir, "model", "model_best.ckpt")
+ if not os.path.exists(os.path.dirname(checkpoint_path)):
+ os.mkdir(os.path.dirname(checkpoint_path))
+ saver.save(sess, checkpoint_path)
+ self.saved_model_path = checkpoint_path
# Output best hyps
with open(os.path.join(hyps_dir, "best_hyps"), "w") as hyps_f:
|
Rename checpoint path variable
|
persephone-tools_persephone
|
train
|
963fc45bfe4ca79cd4de95e83ae1b6650d1fac43
|
diff --git a/components/storage/storage.test.js b/components/storage/storage.test.js
index <HASH>..<HASH> 100644
--- a/components/storage/storage.test.js
+++ b/components/storage/storage.test.js
@@ -1,4 +1,3 @@
-var when = require('when');
var noop = function () {};
function testStorage(storage) {
@@ -131,7 +130,7 @@ function testStorage(storage) {
});
}
-function testStorageEvents(storage) {
+function testStorageEvents(storage) {
describe('events', function () {
var stop;
@@ -142,7 +141,7 @@ function testStorageEvents(storage) {
it('on after set should be fired', function () {
var testEvent = 'testKey';
- var change = when.promise(function (resolve) {
+ var change = new Promise(function (resolve) {
stop = storage.on(testEvent, resolve);
});
@@ -155,7 +154,7 @@ function testStorageEvents(storage) {
var testEvent = 'testKey2';
var testValue = 'testValue';
- var change = when.promise(function (resolve) {
+ var change = new Promise(function (resolve) {
stop = storage.on(testEvent, resolve);
});
@@ -169,7 +168,7 @@ function testStorageEvents(storage) {
var testValue = 'testValue';
var change = storage.set(testEvent, testValue).then(function () {
- return when.promise(function (resolve) {
+ return new Promise(function (resolve) {
stop = storage.on(testEvent, resolve);
storage.remove(testEvent);
@@ -179,26 +178,30 @@ function testStorageEvents(storage) {
return change.should.become(null);
});
- it('on after set with other key shouldn\'t be fired', function () {
- var change = when.promise(function (resolve) {
- stop = storage.on('testKey4', resolve);
- });
+ it('on after set with other key shouldn\'t be fired', function (done) {
+ var spy = this.sinon.stub();
+
+ stop = storage.on('testKey4', spy);
storage.set('testWrong', 'testValue');
- return change.timeout(300).should.be.rejected;
+ setTimeout(function () {
+ spy.should.not.have.been.called;
+ done();
+ }, 300);
});
- it('stop should stop', function () {
- var testEvent = 'testKey5';
-
- var change = when.promise(function (resolve) {
- stop = storage.on(testEvent, resolve);
- stop();
- });
+ it('stop should stop', function (done) {
+ var spy = this.sinon.spy();
+ var testEvent = 'testKey5';
+ stop = storage.on(testEvent, spy);
+ stop();
storage.set(testEvent, 'testValue');
- return change.timeout(300).should.be.rejected;
+ setTimeout(function () {
+ spy.should.not.have.been.called;
+ done();
+ }, 300);
});
});
}
diff --git a/components/storage/storage__fallback.js b/components/storage/storage__fallback.js
index <HASH>..<HASH> 100644
--- a/components/storage/storage__fallback.js
+++ b/components/storage/storage__fallback.js
@@ -167,24 +167,23 @@ FallbackStorage.prototype.each = function (callback) {
* @return {Function}
*/
FallbackStorage.prototype.on = function (key, calback) {
- var self = this;
var stop = false;
- function checkForChange(value) {
- self.get(key).then(function (newValue) {
+ const checkForChange = oldValue => {
+ this.get(key).then(newValue => {
if (stop) {
return;
}
- if (!deepEquals(value, newValue)) {
+ if (!deepEquals(oldValue, newValue)) {
calback(newValue);
}
- Promise.resolve(value).then(() => window.setTimeout(checkForChange, self.checkDelay));
+ window.setTimeout(() => checkForChange(oldValue), this.checkDelay);
});
- }
+ };
- self.get(key).then(checkForChange);
+ this.get(key).then(checkForChange);
return function () {
stop = true;
|
es6 promises: fix storage & its tests
Former-commit-id: d<I>de<I>b<I>fc8c6cb9d<I>d<I>cca<I>e7e<I>d8c<I>
|
JetBrains_ring-ui
|
train
|
985999c6670e6f2d0ab1de7393f59ac1a447ac38
|
diff --git a/send.php b/send.php
index <HASH>..<HASH> 100644
--- a/send.php
+++ b/send.php
@@ -31,6 +31,10 @@ $dir = dirname($file);
$old = $file;
$file = $dir . '/analytics-' . rand() . '.log';
+if(!file_exists($old)) {
+ exit(0);
+}
+
if (!rename($old, $file)) {
print("error renaming from $old to $new\n");
exit(1);
|
Send.php should exit gracefully when there is no log file to process. Otherwise, cron/supervisord executions of this command causes excessive system errors to be triggered on when rename($old, $file) fails.
|
segmentio_analytics-php
|
train
|
2ab099a9ac8ef7b0d6a5cb5cc265cf793023fa3a
|
diff --git a/test/unit/reorder-objects.spec.js b/test/unit/reorder-objects.spec.js
index <HASH>..<HASH> 100644
--- a/test/unit/reorder-objects.spec.js
+++ b/test/unit/reorder-objects.spec.js
@@ -1,6 +1,8 @@
import {createAssertionQueue, fireEvent} from './utils';
import {StageComponent} from 'aurelia-testing';
import {bootstrap} from 'aurelia-bootstrapper';
+import {Container} from 'aurelia-dependency-injection';
+import {DndService} from 'bcx-aurelia-dnd';
import $ from 'jquery';
const nq = createAssertionQueue();
@@ -64,7 +66,7 @@ describe('reorderable-repeat: objects', () => {
.boundTo(model);
component.create(bootstrap).then(() => {
- const dndService = component.viewModel.view.controllers[0].viewModel.dndService;
+ const dndService = Container.instance.get(DndService);
expect(dndService.dndSources.length).toBe(3);
expect(dndService.dndTargets.length).toBe(3);
|
test: simplify DI singleton fetch
|
buttonwoodcx_bcx-aurelia-reorderable-repeat
|
train
|
b4d516ea29cae709b05bc57ca05c839f687af3fc
|
diff --git a/src/main/java/com/threerings/presents/peer/server/PeerManager.java b/src/main/java/com/threerings/presents/peer/server/PeerManager.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/threerings/presents/peer/server/PeerManager.java
+++ b/src/main/java/com/threerings/presents/peer/server/PeerManager.java
@@ -689,6 +689,19 @@ public abstract class PeerManager
}
/**
+ * Returns the NodeObject of the named peer, or <code>null</code> if null if the peer is not
+ * currently connected to this server.
+ */
+ public NodeObject getPeerNodeObject (String nodeName)
+ {
+ if (_nodeName.equals(nodeName)) {
+ return _nodeobj;
+ }
+ PeerNode peer = _peers.get(nodeName);
+ return (peer == null) ? null : peer.nodeobj;
+ }
+
+ /**
* Returns the client object representing the connection to the named peer, or
* <code>null</code> if we are not currently connected to it.
*/
|
Add a method to make a named peer's node object available.
git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@<I> <I>f4-<I>e9-<I>-aa3c-eee0fc<I>fb1
|
threerings_narya
|
train
|
8054c43ce63120d81baf27caa4b0ec42b537a0ad
|
diff --git a/vyper/context/types/function.py b/vyper/context/types/function.py
index <HASH>..<HASH> 100644
--- a/vyper/context/types/function.py
+++ b/vyper/context/types/function.py
@@ -258,13 +258,15 @@ class ContractFunction(BaseTypeDefinition):
f"Visibility must be set to one of: {', '.join(FunctionVisibility.values())}", node
)
- if (
- node.name == "__default__"
- and kwargs["function_visibility"] != FunctionVisibility.EXTERNAL
- ):
- raise FunctionDeclarationException(
- "Default function must be marked as `@external`", node
- )
+ if node.name == "__default__":
+ if kwargs["function_visibility"] != FunctionVisibility.EXTERNAL:
+ raise FunctionDeclarationException(
+ "Default function must be marked as `@external`", node
+ )
+ if node.args.args:
+ raise FunctionDeclarationException(
+ "Default function may not receive any arguments", node.args.args[0]
+ )
if "state_mutability" not in kwargs:
# Assume nonpayable if not set at all (cannot accept Ether, but can modify state)
diff --git a/vyper/parser/function_definitions/parse_external_function.py b/vyper/parser/function_definitions/parse_external_function.py
index <HASH>..<HASH> 100644
--- a/vyper/parser/function_definitions/parse_external_function.py
+++ b/vyper/parser/function_definitions/parse_external_function.py
@@ -1,7 +1,6 @@
import ast
from typing import Any, List, Union
-from vyper.exceptions import FunctionDeclarationException
from vyper.parser.arg_clamps import make_arg_clamper
from vyper.parser.context import Context, VariableRecord
from vyper.parser.expr import Expr
@@ -104,10 +103,6 @@ def parse_external_function(
)
# Is default function.
elif sig.is_default_func():
- if len(sig.args) > 0:
- raise FunctionDeclarationException(
- "Default function may not receive any arguments.", code
- )
o = LLLnode.from_list(
["seq"] + clampers + [parse_body(code.body, context)], # type: ignore
pos=getpos(code),
|
refactor: move default fn arg count check to type checking
|
ethereum_vyper
|
train
|
ba4768a4874c79642b3a3b408d2abb9cab2d8d30
|
diff --git a/spec/octokit/client_spec.rb b/spec/octokit/client_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/octokit/client_spec.rb
+++ b/spec/octokit/client_spec.rb
@@ -19,7 +19,7 @@ describe Octokit::Client do
end
it 'should work with basic auth and password' do
- stub_request(:get, "https://foo%2Fbar@github.com/api/v2/json/commits/list/baz/quux/master").
+ stub_request(:get, "https://foo:bar@github.com/api/v2/json/commits/list/baz/quux/master").
with(:headers => {'Accept'=>'*/*'}).
to_return(:status => 200, :body => '{"commits":[]}', :headers => {})
proc {
|
Really fix specs in Ruby <I>
|
octokit_octokit.rb
|
train
|
ee726776f5578ac49b3800e246ba5f63225dd2b5
|
diff --git a/test/opentracing_test.rb b/test/opentracing_test.rb
index <HASH>..<HASH> 100644
--- a/test/opentracing_test.rb
+++ b/test/opentracing_test.rb
@@ -28,8 +28,8 @@ class OpenTracingTest < Minitest::Test
OpenTracing.global_tracer = tracer
scope = Minitest::Mock.new
- tracer.expect(:start_active_span, scope, ["span"])
- OpenTracing.start_active_span("span")
+ tracer.expect(:start_active_span, scope, ['span'])
+ OpenTracing.start_active_span('span')
end
def test_global_tracer_start_span
|
Fixing failed RuboCop check
|
opentracing_opentracing-ruby
|
train
|
9c2ee66a9f6855e7dccdd5c804df58ed35c91918
|
diff --git a/models/player.go b/models/player.go
index <HASH>..<HASH> 100644
--- a/models/player.go
+++ b/models/player.go
@@ -73,6 +73,8 @@ type Player struct {
Settings []PlayerSetting
MumbleUsername string `sql:"unique"`
MumbleAuthkey string `sql:"not null;unique"`
+
+ TwitchAccessToken string
}
// Create a new player with the given steam id.
|
Add Twitch Access Token field to Player
|
TF2Stadium_Helen
|
train
|
9492dc7f7cd324d2cd5a619cbf727371e1b9d6b9
|
diff --git a/src/Composer/Plugin/PluginManager.php b/src/Composer/Plugin/PluginManager.php
index <HASH>..<HASH> 100644
--- a/src/Composer/Plugin/PluginManager.php
+++ b/src/Composer/Plugin/PluginManager.php
@@ -149,6 +149,12 @@ class PluginManager
return;
}
+
+ if ($package->getName() === 'symfony/flex' && version_compare($package->getVersion(), '1.9.8', '<')) {
+ $this->io->writeError('<warning>The "' . $package->getName() . '" plugin was skipped because it is not compatible with Composer 2+. Make sure to update it to version 1.9.8 or greater.</warning>');
+
+ return;
+ }
}
$oldInstallerPlugin = ($package->getType() === 'composer-installer');
|
Make sure symfony/flex does not get loaded in a buggy version to avoid bogus issue reports
|
composer_composer
|
train
|
4316a7b0103977a2a1547e28cd04c842d9839f1e
|
diff --git a/dev/merge_spark_pr.py b/dev/merge_spark_pr.py
index <HASH>..<HASH> 100755
--- a/dev/merge_spark_pr.py
+++ b/dev/merge_spark_pr.py
@@ -214,15 +214,10 @@ def fix_version_from_branch(branch, versions):
return filter(lambda x: x.name.startswith(branch_ver), versions)[-1]
-def resolve_jira(title, merge_branches, comment):
+def resolve_jira_issue(merge_branches, comment, default_jira_id=""):
asf_jira = jira.client.JIRA({'server': JIRA_API_BASE},
basic_auth=(JIRA_USERNAME, JIRA_PASSWORD))
- default_jira_id = ""
- search = re.findall("SPARK-[0-9]{4,5}", title)
- if len(search) > 0:
- default_jira_id = search[0]
-
jira_id = raw_input("Enter a JIRA id [%s]: " % default_jira_id)
if jira_id == "":
jira_id = default_jira_id
@@ -280,6 +275,15 @@ def resolve_jira(title, merge_branches, comment):
print "Succesfully resolved %s with fixVersions=%s!" % (jira_id, fix_versions)
+def resolve_jira_issues(title, merge_branches, comment):
+ jira_ids = re.findall("SPARK-[0-9]{4,5}", title)
+
+ if len(jira_ids) == 0:
+ resolve_jira_issue(merge_branches, comment)
+ for jira_id in jira_ids:
+ resolve_jira_issue(merge_branches, comment, jira_id)
+
+
branches = get_json("%s/branches" % GITHUB_API_BASE)
branch_names = filter(lambda x: x.startswith("branch-"), [x['name'] for x in branches])
# Assumes branch names can be sorted lexicographically
@@ -338,7 +342,7 @@ if JIRA_IMPORTED:
if JIRA_USERNAME and JIRA_PASSWORD:
continue_maybe("Would you like to update an associated JIRA?")
jira_comment = "Issue resolved by pull request %s\n[%s/%s]" % (pr_num, GITHUB_BASE, pr_num)
- resolve_jira(title, merged_refs, jira_comment)
+ resolve_jira_issues(title, merged_refs, jira_comment)
else:
print "JIRA_USERNAME and JIRA_PASSWORD not set"
print "Exiting without trying to close the associated JIRA."
|
SPARK-<I>: PR merge script should support closing multiple JIRA tickets
This will fix SPARK-<I>.
For pull requests that reference multiple JIRAs in their titles, it would be helpful if the PR merge script offered to close all of them.
|
apache_spark
|
train
|
5df4e2b279b4f203808db17747818f548b321787
|
diff --git a/invenio_base/app.py b/invenio_base/app.py
index <HASH>..<HASH> 100644
--- a/invenio_base/app.py
+++ b/invenio_base/app.py
@@ -84,13 +84,9 @@ def create_app_factory(app_name, config_loader=None,
.. versionadded: 1.0.0
"""
def _create_app(**kwargs):
- if 'instance_path' in app_kwargs and \
- callable(app_kwargs['instance_path']):
- app_kwargs['instance_path'] = app_kwargs['instance_path']()
-
- if 'static_folder' in app_kwargs and \
- callable(app_kwargs['static_folder']):
- app_kwargs['static_folder'] = app_kwargs['static_folder']()
+ for k in ('instance_path', 'root_path', 'static_folder'):
+ if k in app_kwargs and callable(app_kwargs[k]):
+ app_kwargs[k] = app_kwargs[k]()
app = base_app(app_name, **app_kwargs)
app_created.send(_create_app, app=app)
@@ -250,7 +246,7 @@ def _loader(app, init_func, entry_points=None, modules=None):
def base_app(import_name, instance_path=None, static_folder=None,
static_url_path='/static', template_folder='templates',
- instance_relative_config=True, app_class=Flask):
+ instance_relative_config=True, root_path=None, app_class=Flask):
"""Invenio base application factory.
If the instance folder does not exists, it will be created.
@@ -274,6 +270,7 @@ def base_app(import_name, instance_path=None, static_folder=None,
static_folder=static_folder,
static_url_path=static_url_path,
template_folder=template_folder,
+ root_path=root_path,
)
# Create instance path if it doesn't exists
|
app: add "root_path" to the base app factory
|
inveniosoftware_invenio-base
|
train
|
7a9ed983a0b28cb183a3934aacd4bb819b0c19bb
|
diff --git a/lib/JavaScriptLoader.js b/lib/JavaScriptLoader.js
index <HASH>..<HASH> 100644
--- a/lib/JavaScriptLoader.js
+++ b/lib/JavaScriptLoader.js
@@ -43,7 +43,6 @@ JavaScriptLoader.prototype.load = function (assetConfigs, cb) {
that.assetGraph.transform(
transforms.loadAssets(assetConfigs),
transforms.populate({type: 'JavaScriptStaticInclude'}),
- transforms.stats(),
function (err, assetGraph) {
seq()
.seq(function () {
|
JavaScriptLoader: Removed transforms.stats from the stack (leftover debugging code).
|
assetgraph_assetgraph
|
train
|
383cfb50ff8f823d40e4ba086a2208bfededc9bd
|
diff --git a/mungegithub/pulls/blunderbuss.go b/mungegithub/pulls/blunderbuss.go
index <HASH>..<HASH> 100644
--- a/mungegithub/pulls/blunderbuss.go
+++ b/mungegithub/pulls/blunderbuss.go
@@ -88,11 +88,6 @@ func (b *BlunderbussMunger) MungePullRequest(client *github.Client, pr *github.P
glog.Warningf("Skipping invalid commit for %d: %#v", *pr.Number, commit)
continue
}
- commit, _, err := client.Repositories.GetCommit(*commit.Author.Login, opts.Project, *commit.SHA)
- if err != nil {
- glog.Errorf("Can't load commit %s %s %s", *commit.Author.Login, opts.Project, *commit.SHA)
- continue
- }
for _, file := range commit.Files {
fileOwners := b.config.FindOwners(*file.Filename)
if len(fileOwners) == 0 {
diff --git a/mungegithub/pulls/pulls.go b/mungegithub/pulls/pulls.go
index <HASH>..<HASH> 100644
--- a/mungegithub/pulls/pulls.go
+++ b/mungegithub/pulls/pulls.go
@@ -111,6 +111,15 @@ func mungePullRequestList(list []github.PullRequest, client *github.Client, mung
if err != nil {
return err
}
+ filledCommits := []github.RepositoryCommit{}
+ for _, c := range commits {
+ commit, _, err := client.Repositories.GetCommit(opts.Org, opts.Project, *c.SHA)
+ if err != nil {
+ glog.Errorf("Can't load commit %s %s %s", opts.Org, opts.Project, *commit.SHA)
+ continue
+ }
+ filledCommits = append(filledCommits, *commit)
+ }
events, _, err := client.Issues.ListIssueEvents(opts.Org, opts.Project, *pr.Number, &github.ListOptions{})
if err != nil {
return err
@@ -120,7 +129,7 @@ func mungePullRequestList(list []github.PullRequest, client *github.Client, mung
return err
}
for _, munger := range mungers {
- munger.MungePullRequest(client, pr, issue, commits, events, opts)
+ munger.MungePullRequest(client, pr, issue, filledCommits, events, opts)
}
}
return nil
|
mungegithub: GetCommit in the generic code, not just in blunderbuss
Others want to use it
|
kubernetes-retired_contrib
|
train
|
ab103e19c011f99c51666b90ce3a41b77b5d647d
|
diff --git a/src/configupdater/document.py b/src/configupdater/document.py
index <HASH>..<HASH> 100644
--- a/src/configupdater/document.py
+++ b/src/configupdater/document.py
@@ -164,6 +164,8 @@ class Document(Container[ConfigContent], MutableMapping[str, Section]):
return False
def clear(self):
+ for block in self._structure:
+ block.detach()
self._structure.clear()
def add_section(self, section: Union[str, Section]):
diff --git a/src/configupdater/section.py b/src/configupdater/section.py
index <HASH>..<HASH> 100644
--- a/src/configupdater/section.py
+++ b/src/configupdater/section.py
@@ -268,4 +268,6 @@ class Section(Block, Container[Content], MutableMapping[str, "Option"]):
return BlockBuilder(self, idx)
def clear(self):
+ for block in self._structure:
+ block.detach()
self._structure.clear()
|
Detach blocks when cleaning containers
Blocks hold a reference to their containers, so if someone for some
reason is keeping a reference to a block, it would be nice (for the sake
of consistency) to guarantee that block does not hold a reference to its
former container if that container is emptied via `.clear()`
There is another aspect: Python GC is based on reference counter... I
don't know if keeping references around in the blocks might interfere
with that also.
|
pyscaffold_configupdater
|
train
|
250d7b8d90360ab43b63088096fcc99bca5a25dc
|
diff --git a/stagemonitor-alerting/src/main/java/org/stagemonitor/alerting/AlertingPlugin.java b/stagemonitor-alerting/src/main/java/org/stagemonitor/alerting/AlertingPlugin.java
index <HASH>..<HASH> 100644
--- a/stagemonitor-alerting/src/main/java/org/stagemonitor/alerting/AlertingPlugin.java
+++ b/stagemonitor-alerting/src/main/java/org/stagemonitor/alerting/AlertingPlugin.java
@@ -124,36 +124,38 @@ public class AlertingPlugin extends StagemonitorPlugin implements ServletContain
"</#if>\n" +
"Old status: ${incident.oldStatus!'OK'}<br>\n" +
"New status: ${incident.newStatus}<br>\n" +
+ "<#if incident.failedChecks gt 0>" +
"Failing check<#if incident.failedChecks gt 1>s</#if>: ${incident.failedChecks}<br>\n" +
"Hosts: ${incident.hosts?join(\", \")}<br>\n" +
"Instances: ${incident.instances?join(\", \")}<br><br>\n" +
"\n" +
- "<#if incident.checkResults?has_content>\n" +
+ " <#if incident.checkResults?has_content>\n" +
"<table>\n" +
- "\t<thead>\n" +
- "\t<tr>\n" +
- "\t\t<th>Host</th>\n" +
- "\t\t<th>Instance</th>\n" +
- "\t\t<th>Status</th>\n" +
- "\t\t<th>Description</th>\n" +
- "\t\t<th>Current Value</th>\n" +
- "\t</tr>\n" +
- "\t</thead>\n" +
- "\t<tbody>\n" +
- "\t\t<#list incident.checkResults as results>\n" +
- "\t\t\t<#assign measurementSession=results.measurementSession/>\n" +
- "\t\t\t<#list results.getResults() as result>\n" +
- "\t\t\t<tr>\n" +
- "\t\t\t\t<td>${measurementSession.hostName}</td>\n" +
- "\t\t\t\t<td>${measurementSession.instanceName}</td>\n" +
- "\t\t\t\t<td>${result.status}</td>\n" +
- "\t\t\t\t<td>${result.failingExpression}</td>\n" +
- "\t\t\t\t<td>${result.currentValue}</td>\n" +
- "\t\t\t</tr>\n" +
- "\t\t\t</#list>\n" +
- "\t\t</#list>\n" +
- "\t</tbody>\n" +
+ " <thead>\n" +
+ " <tr>\n" +
+ " <th>Host</th>\n" +
+ " <th>Instance</th>\n" +
+ " <th>Status</th>\n" +
+ " <th>Description</th>\n" +
+ " <th>Current Value</th>\n" +
+ " </tr>\n" +
+ " </thead>\n" +
+ " <tbody>\n" +
+ " <#list incident.checkResults as results>\n" +
+ " <#assign measurementSession=results.measurementSession/>\n" +
+ " <#list results.getResults() as result>\n" +
+ " <tr>\n" +
+ " <td>${measurementSession.hostName}</td>\n" +
+ " <td>${measurementSession.instanceName}</td>\n" +
+ " <td>${result.status}</td>\n" +
+ " <td>${result.failingExpression}</td>\n" +
+ " <td>${result.currentValue}</td>\n" +
+ " </tr>\n" +
+ " </#list>\n" +
+ " </#list>\n" +
+ " </tbody>\n" +
"</table>\n" +
+ " </#if>\n" +
"</#if>\n")
.configurationCategory(ALERTING_PLUGIN_NAME)
.build();
@@ -169,6 +171,7 @@ public class AlertingPlugin extends StagemonitorPlugin implements ServletContain
"</#if>\n" +
"Old status: ${incident.oldStatus!'OK'}\n" +
"New status: ${incident.newStatus}\n" +
+ "<#if incident.failedChecks gt 0>" +
"Failing check<#if incident.failedChecks gt 1>s</#if>: ${incident.failedChecks}\n" +
"Hosts: ${incident.hosts?join(\", \")}\n" +
"Instances: ${incident.instances?join(\", \")}\n" +
@@ -176,16 +179,17 @@ public class AlertingPlugin extends StagemonitorPlugin implements ServletContain
"Details:" +
"\n" +
"<#list incident.checkResults as results>\n" +
- " <#assign measurementSession=results.measurementSession/>\n" +
- " <#list results.getResults() as result>\n" +
+ "<#assign measurementSession=results.measurementSession/>\n" +
+ "<#list results.getResults() as result>\n" +
"Host: ${measurementSession.hostName}\n" +
"Instance: ${measurementSession.instanceName}\n" +
"Status: ${result.status}\n" +
"Description: ${result.failingExpression}\n" +
"Current value: ${result.currentValue}\n" +
"\n" +
- " </#list>" +
- "</#list>")
+ "</#list>" +
+ "</#list>" +
+ "</#if>")
.configurationCategory(ALERTING_PLUGIN_NAME)
.build();
private ConfigurationOption<String> shortDescriptionAlertTemplate = ConfigurationOption.stringOption()
|
Only show alert detail is status is not ok
|
stagemonitor_stagemonitor
|
train
|
479542362f927d11052ca64c1866edc6302c3fa4
|
diff --git a/src/share/classes/com/sun/tools/javac/code/TypeAnnotationPosition.java b/src/share/classes/com/sun/tools/javac/code/TypeAnnotationPosition.java
index <HASH>..<HASH> 100644
--- a/src/share/classes/com/sun/tools/javac/code/TypeAnnotationPosition.java
+++ b/src/share/classes/com/sun/tools/javac/code/TypeAnnotationPosition.java
@@ -159,7 +159,7 @@ public class TypeAnnotationPosition {
// the catch type index. Then in
// com.sun.tools.javac.jvm.Code.fillExceptionParameterPositions we
// use that value to determine the exception table index.
- private int exception_index = Integer.MIN_VALUE;
+ public int exception_index = Integer.MIN_VALUE;
// If this type annotation is within a lambda expression,
// store a pointer to the lambda expression tree in order
|
Make a field public to allow direct access. This makes compatibility between Java 8 and 9 easier, as the field can be accessed directly in both. Reflective access will need to be used eventually.
|
wmdietl_jsr308-langtools
|
train
|
b90166ee4f83002777e74457c755ee0d391be87f
|
diff --git a/db/topology.go b/db/topology.go
index <HASH>..<HASH> 100644
--- a/db/topology.go
+++ b/db/topology.go
@@ -326,7 +326,7 @@ func (d *Database) GetFragmentForBitmap(slice *Slice, bitmap *Bitmap) (*Fragment
}
frag_id_s, err := fsi.hashring.Get(fmt.Sprintf("%d", bitmap.Id))
if err != nil {
- log.Println("ERROR FSI.GET:", bitmap.Id)
+ log.Println("ERROR FSI.GET:", bitmap.Id, bitmap.FrameType, frame, slice)
log.Println(err)
return nil, err
}
|
added better logging for hashring errors
|
pilosa_pilosa
|
train
|
1bb531965f8e1a546129c95d183d4e7633dea719
|
diff --git a/src/Mcfedr/AwsPushBundle/Service/Devices.php b/src/Mcfedr/AwsPushBundle/Service/Devices.php
index <HASH>..<HASH> 100644
--- a/src/Mcfedr/AwsPushBundle/Service/Devices.php
+++ b/src/Mcfedr/AwsPushBundle/Service/Devices.php
@@ -54,7 +54,7 @@ class Devices
]
];
- if ($userData && is_string($userData)) {
+ if ($userData) {
$args['CustomUserData'] = $userData;
}
|
Removed checking typo of user data.
|
mcfedr_awspushbundle
|
train
|
68dea085707e7ceef85ef06d66ee0c860a05cb3c
|
diff --git a/lib/Vespolina/Billing/Manager/BillingManager.php b/lib/Vespolina/Billing/Manager/BillingManager.php
index <HASH>..<HASH> 100755
--- a/lib/Vespolina/Billing/Manager/BillingManager.php
+++ b/lib/Vespolina/Billing/Manager/BillingManager.php
@@ -97,8 +97,13 @@ class BillingManager implements BillingManagerInterface
->setInitialBillingDate(new \DateTime('now'))
->setNextBillingDate($startDate)
->setBillingAmount($recurringCharge)
+ ->setBillingCycles($pricingSet->get('cycles'))
+ ->setBillingInterval($pricingSet->get('interval'))
->setOrderItem($item)
;
+
+ $this->gateway->persistBillingAgreement($billingAgreement);
+
$billingAgreements[] = $billingAgreement;
}
|
persisting billing agreements + added cycles interval
|
vespolina_commerce
|
train
|
2a94b86604c4067b96e351497e7870f565ab037a
|
diff --git a/dev/components/components/stepper.vue b/dev/components/components/stepper.vue
index <HASH>..<HASH> 100644
--- a/dev/components/components/stepper.vue
+++ b/dev/components/components/stepper.vue
@@ -104,6 +104,9 @@ export default {
color: 'secondary',
text: ''
}
+ },
+ mounted () {
+ window.x = this.$refs.stepper
}
}
</script>
diff --git a/src/components/stepper/QStep.js b/src/components/stepper/QStep.js
index <HASH>..<HASH> 100644
--- a/src/components/stepper/QStep.js
+++ b/src/components/stepper/QStep.js
@@ -79,6 +79,14 @@ export default {
'-ms-flex-order': ord,
order: ord
}
+ },
+ classes () {
+ if (!this.__stepper.vertical) {
+ const cls = []
+ !this.active && cls.push('hidden')
+ this.__stepper.animation !== null && cls.push(this.__stepper.animation)
+ return cls
+ }
}
},
methods: {
@@ -86,6 +94,23 @@ export default {
if (this.done) {
this.__stepper.goToStep(this.name)
}
+ },
+
+ __getContainer (h) {
+ const content = this.active
+ ? h('div', {
+ staticClass: 'q-stepper-step-content',
+ 'class': this.classes
+ }, [
+ h('div', {
+ staticClass: 'q-stepper-step-inner'
+ }, this.$slots.default)
+ ])
+ : null
+
+ return this.__stepper.vertical
+ ? h(QSlideTransition, [ content ])
+ : content
}
},
mounted () {
@@ -105,17 +130,7 @@ export default {
this.__stepper.vertical
? h(StepTab, { props: { vm: this } })
: null,
- h(QSlideTransition, [
- this.active
- ? h('div', {
- staticClass: 'q-stepper-step-content'
- }, [
- h('div', {
- staticClass: 'q-stepper-step-inner'
- }, this.$slots.default)
- ])
- : null
- ])
+ this.__getContainer(h)
])
}
}
diff --git a/src/components/stepper/QStepper.js b/src/components/stepper/QStepper.js
index <HASH>..<HASH> 100644
--- a/src/components/stepper/QStepper.js
+++ b/src/components/stepper/QStepper.js
@@ -19,6 +19,7 @@ export default {
},
data () {
return {
+ animation: null,
step: this.value || null,
steps: []
}
@@ -31,6 +32,17 @@ export default {
watch: {
value (v) {
this.goToStep(v)
+ },
+ step (cur, old) {
+ if (!this.vertical) {
+ const
+ curIndex = this.steps.findIndex(step => step.name === cur),
+ oldIndex = this.steps.findIndex(step => step.name === old)
+
+ this.animation = curIndex < oldIndex
+ ? 'animate-fade-left'
+ : (curIndex > oldIndex ? 'animate-fade-right' : null)
+ }
}
},
computed: {
|
feat(QStepper): Improve animation for horizontal stepper
|
quasarframework_quasar
|
train
|
9270a146da2c4e487074c1dc1b3646cf328f3868
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -214,7 +214,7 @@ class WebTorrent extends EventEmitter {
}
port.postMessage(chunk)
if (!chunk) cleanup()
- if (!this.workerKeepAliveInterval) this.workerKeepAliveInterval = setInterval(() => fetch(`${this.serviceWorker.scriptURL.substr(0, this.serviceWorker.scriptURL.lastIndexOf('/') + 1).slice(window.location.origin.length)}webtorrent/keepalive/`), keepAliveTime)
+ if (!this.workerKeepAliveInterval) this.workerKeepAliveInterval = setInterval(() => fetch(`${this.serviceWorker.scriptURL.slice(0, this.serviceWorker.scriptURL.lastIndexOf('/') + 1).slice(window.location.origin.length)}webtorrent/keepalive/`), keepAliveTime)
} else {
cleanup()
}
diff --git a/lib/file.js b/lib/file.js
index <HASH>..<HASH> 100644
--- a/lib/file.js
+++ b/lib/file.js
@@ -206,7 +206,7 @@ class File extends EventEmitter {
if (typeof window === 'undefined') throw new Error('browser-only method')
if (!this._serviceWorker) throw new Error('No worker registered')
if (this._serviceWorker.state !== 'activated') throw new Error('Worker isn\'t activated')
- const workerPath = this._serviceWorker.scriptURL.substr(0, this._serviceWorker.scriptURL.lastIndexOf('/') + 1).slice(window.location.origin.length)
+ const workerPath = this._serviceWorker.scriptURL.slice(0, this._serviceWorker.scriptURL.lastIndexOf('/') + 1).slice(window.location.origin.length)
const url = `${workerPath}webtorrent/${this._torrent.infoHash}/${encodeURI(this.path)}`
cb(null, url)
}
@@ -215,7 +215,7 @@ class File extends EventEmitter {
if (typeof window === 'undefined') throw new Error('browser-only method')
if (!this._serviceWorker) throw new Error('No worker registered')
if (this._serviceWorker.state !== 'activated') throw new Error('Worker isn\'t activated')
- const workerPath = this._serviceWorker.scriptURL.substr(0, this._serviceWorker.scriptURL.lastIndexOf('/') + 1).slice(window.location.origin.length)
+ const workerPath = this._serviceWorker.scriptURL.slice(0, this._serviceWorker.scriptURL.lastIndexOf('/') + 1).slice(window.location.origin.length)
elem.src = `${workerPath}webtorrent/${this._torrent.infoHash}/${encodeURI(this.path)}`
cb(null, elem)
}
|
refactor: replace deprecated String.prototype.substr() (#<I>)
.substr() is deprecated so we replace it with .slice() which works similarily but isn't deprecated
|
webtorrent_webtorrent
|
train
|
25d3bc237b2fa8ca0427644572bab3a4a4da3ed2
|
diff --git a/lib/main.js b/lib/main.js
index <HASH>..<HASH> 100644
--- a/lib/main.js
+++ b/lib/main.js
@@ -97,11 +97,17 @@ var csv = isLocal ? csvLocal.initialize() : csvRemote.initialize(info, log);
var registerCommands = typeof browser !== 'undefined' && _.isUndefined(browser.testableLogInfo);
if (registerCommands) {
- wdio.registerLogCommands(log);
- wdio.registerCsvCommands(csv);
- wdio.registerResultsCommands(results);
- wdio.registerInfoCommands(info);
- wdio.registerStopwatchCommands(stopwatch);
+ const browsers = [ browser ];
+ if (process.env.TESTABLE_BROWSERS) {
+ browsers.push.apply(browsers, process.env.TESTABLE_BROWSERS.split(","));
+ }
+ _.forEach(browsers, function(brwsr) {
+ wdio.registerLogCommands(brwsr, log);
+ wdio.registerCsvCommands(brwsr, csv);
+ wdio.registerResultsCommands(brwsr, results);
+ wdio.registerInfoCommands(brwsr, info);
+ wdio.registerStopwatchCommands(brwsr, stopwatch);
+ });
}
module.exports.isLocal = isLocal;
diff --git a/lib/wdio-commands.js b/lib/wdio-commands.js
index <HASH>..<HASH> 100644
--- a/lib/wdio-commands.js
+++ b/lib/wdio-commands.js
@@ -1,11 +1,11 @@
var _ = require('lodash');
-function isWdioContext() {
+function isWdioContext(browser) {
return _.isObject(browser) && _.isFunction(browser.addCommand);
}
-function registerLogCommands(log) {
- if (isWdioContext()) {
+function registerLogCommands(browser, log) {
+ if (isWdioContext(browser)) {
browser.addCommand('testableLogTrace', function async() {
return log.trace.apply(log, arguments);
});
@@ -24,8 +24,8 @@ function registerLogCommands(log) {
}
}
-function registerCsvCommands(csv) {
- if (isWdioContext()) {
+function registerCsvCommands(browser, csv) {
+ if (isWdioContext(browser)) {
browser.addCommand('testableCsvGet', function async(name, index) {
return csv.open(name).get(index);
});
@@ -38,8 +38,8 @@ function registerCsvCommands(csv) {
}
}
-function registerResultsCommands(results) {
- if (isWdioContext()) {
+function registerResultsCommands(browser, results) {
+ if (isWdioContext(browser)) {
browser.addCommand('testableResult', function(resource, url) {
return results(resource, url);
});
@@ -58,8 +58,8 @@ function registerResultsCommands(results) {
}
}
-function registerInfoCommands(info) {
- if (isWdioContext()) {
+function registerInfoCommands(browser, info) {
+ if (isWdioContext(browser)) {
browser.addCommand('testableInfo', function () {
return info;
});
@@ -71,8 +71,8 @@ function registerInfoCommands(info) {
}
}
-function registerStopwatchCommands(stopwatch) {
- if (isWdioContext()) {
+function registerStopwatchCommands(browser, stopwatch) {
+ if (isWdioContext(browser)) {
browser.addCommand('testableStopwatch', function async(code, metricName, resource) {
return stopwatch(code, metricName, resource);
});
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "testable-utils",
- "version": "0.2.0",
+ "version": "0.2.1",
"description": "Utilities for Testable scripts",
"author": "Avi Stramer",
"keywords": [
|
register commands on multi-browser setups
|
testable_node-script-utils
|
train
|
c3ba183b31e3914bfcf3690ead4a4bf9ca78de3c
|
diff --git a/lib/phobos.rb b/lib/phobos.rb
index <HASH>..<HASH> 100644
--- a/lib/phobos.rb
+++ b/lib/phobos.rb
@@ -50,15 +50,16 @@ module Phobos
log_file = config.logger.file
ruby_kafka = config.logger.ruby_kafka
date_pattern = '%Y-%m-%dT%H:%M:%S:%L%zZ'
- log_layout = Logging.layouts.pattern(date_pattern: date_pattern)
- appenders = [Logging.appenders.stdout(layout: log_layout)]
+ file_layout = Logging.layouts.json(date_pattern: date_pattern)
+ stdout_layout = Logging.layouts.pattern(date_pattern: date_pattern)
+ appenders = [Logging.appenders.stdout(layout: stdout_layout)]
Logging.backtrace(true)
Logging.logger.root.level = silence_log ? :fatal : config.logger.level
if log_file
FileUtils.mkdir_p(File.dirname(log_file))
- appenders << Logging.appenders.file(log_file, layout: log_layout)
+ appenders << Logging.appenders.file(log_file, layout: file_layout)
end
@ruby_kafka_logger = nil
|
bugfix: ensures json layout for log file (it was the previous behavior)
|
phobos_phobos
|
train
|
3aac08a9296d5ce4b10e22ad1d4e8f3eee52bb4e
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -5,11 +5,11 @@ from setuptools import setup, find_packages
setup(
name = "a10-neutron-lbaas",
- version = "1.7.4",
+ version = "1.8.1",
packages = find_packages(),
author = "A10 Networks",
- author_email = "mdurrant@a10networks.com",
+ author_email = "openstack@a10networks.com",
description = "A10 Networks Openstack LBaaS Driver Middleware",
license = "Apache",
keywords = "a10 axapi acos adc slb load balancer openstack neutron lbaas",
|
Updated version in setup.py
|
a10networks_a10-neutron-lbaas
|
train
|
bfceeb395109e846dddd553d4572ed53a51b50ec
|
diff --git a/go/vt/srvtopo/resilient_server.go b/go/vt/srvtopo/resilient_server.go
index <HASH>..<HASH> 100644
--- a/go/vt/srvtopo/resilient_server.go
+++ b/go/vt/srvtopo/resilient_server.go
@@ -20,6 +20,7 @@ import (
"flag"
"fmt"
"html/template"
+ "net/url"
"sort"
"sync"
"time"
@@ -468,7 +469,9 @@ func (server *ResilientServer) watchSrvKeyspace(callerCtx context.Context, entry
server.counts.Add(errorCategory, 1)
log.Errorf("Initial WatchSrvKeyspace failed for %v/%v: %v", cell, keyspace, current.Err)
- if time.Since(entry.lastValueTime) > server.cacheTTL {
+ // This watcher will able to continue to return the last value till it is not able to connect to the topo server even if the cache TTL is reached.
+ _, netErr := current.Err.(*url.Error)
+ if !netErr && time.Since(entry.lastValueTime) > server.cacheTTL {
log.Errorf("WatchSrvKeyspace clearing cached entry for %v/%v", cell, keyspace)
entry.value = nil
}
|
do not evict cache if unable to connect to topo server
|
vitessio_vitess
|
train
|
4fd141247cafc1acaa0cdb81db59b0a930ce41e8
|
diff --git a/TodoBase.py b/TodoBase.py
index <HASH>..<HASH> 100644
--- a/TodoBase.py
+++ b/TodoBase.py
@@ -43,11 +43,16 @@ class TodoBase(object):
matches = [tag[1] for tag in tags if tag[0] == p_key]
return matches if len(matches) else []
- def has_tag(self, p_key):
+ def has_tag(self, p_key, p_value=""):
"""
- Returns true iff this todo has at least one tag with the given key.
+ Returns true when there is at least one tag with the given key. If a
+ value is passed, it will only return true when there exists a tag with
+ the given key-value combination.
"""
- return len(self.tag_values(p_key)) > 0
+
+ result = [t for t in self.tag_values(p_key) \
+ if p_value == "" or t == p_value]
+ return len(result) > 0
def set_tag(self, p_key, p_value=""):
"""
|
Also make it possible to check on the value when checking tag existence.
|
bram85_topydo
|
train
|
d2248705cdef10b4c65448b4d839f84d022cbed6
|
diff --git a/test/test_en_weekday.js b/test/test_en_weekday.js
index <HASH>..<HASH> 100644
--- a/test/test_en_weekday.js
+++ b/test/test_en_weekday.js
@@ -176,6 +176,27 @@ test("Test - Single Expression", function () {
}
});
+test("Test - Weekday With Casual Time", function () {
+ var text = "Lets meet on Tuesday morning";
+ var results = chrono.casual.parse(text, new Date(2015, 3, 18));
+ ok(results.length == 1, JSON.stringify(results));
+ var result = results[0];
+ if (result) {
+ ok(result.index == 10, 'Wrong index');
+ ok(result.text == 'on Tuesday morning', result.text);
+
+ ok(result.start, JSON.stringify(result.start));
+ ok(result.start.get('year') == 2015, 'Test Result - (Year) ' + JSON.stringify(result.start));
+ ok(result.start.get('month') == 4, 'Test Result - (Month) ' + JSON.stringify(result.start));
+ ok(result.start.get('day') == 21, 'Test Result - (Day) ' + JSON.stringify(result.start));
+ ok(result.start.get('weekday') == 2, 'Test Result - (Weekday) ' + JSON.stringify(result.start));
+ ok(result.start.get('hour') == 6, 'Test Result - (Hour) ' + JSON.stringify(result.start));
+
+ var resultDate = result.start.date();
+ var expectDate = new Date(2015, 3, 21, 6);
+ ok(Math.abs(expectDate.getTime() - resultDate.getTime()) < 100000, 'Test result.startDate ' + resultDate + '/' + expectDate)
+ }
+});
test("Test - Weekday Overlap", function () {
|
add test for day of the week and casual time
|
wanasit_chrono
|
train
|
d7929ed1d950908f979af7791e4b0e2e1340b036
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -1,12 +1,14 @@
-module.exports = function rangeInclusive (start, stop, step) {
+module.exports = function rangeInclusive (start, stop, stepSize) {
if (stop == null) {
stop = start
start = 1
}
- if (step == null) step = 1
+ if (stepSize == null) stepSize = 1
+
+ var steps = (stop - start) / stepSize
var set = []
- for (; (stop - start) * step >= 0; start += step) set.push(start)
+ for (var step = 0; step <= steps; step++) set.push(start + step * stepSize)
return set
}
|
Revise algorithm to avoid global truncation
|
emilbayes_range-inclusive
|
train
|
0470822ad66fbf0fe1a4a21b8cdf04cc058dc815
|
diff --git a/blimpy/calib_utils/fluxcal.py b/blimpy/calib_utils/fluxcal.py
index <HASH>..<HASH> 100644
--- a/blimpy/calib_utils/fluxcal.py
+++ b/blimpy/calib_utils/fluxcal.py
@@ -190,9 +190,8 @@ def calibrate_fluxes(name,dio_name,dspec,fullstokes=False,**kwargs):
#Write calibrated data to a new filterbank file with ".fluxcal" extension
obs.data = data
- obs.write_to_filterbank(name[:-4]+'.fluxcal.fil')
+ obs.write_to_fil(name[:-4]+'.fluxcal.fil')
print 'Finished: calibrated product written to ' + name[:-4]+'.fluxcal.fil'
#end module
-
|
Used write_to_fil instead of write_to_filterbank for calibrated product
|
UCBerkeleySETI_blimpy
|
train
|
2bb43dcd5da44d466eb18955241099e0d4d6c65b
|
diff --git a/config/routes.rb b/config/routes.rb
index <HASH>..<HASH> 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,7 +1,7 @@
Refinery::Application.routes.draw do
# REFINERY CMS ================================================================
-
+
filter(:refinery_locales)
root :to => 'pages#home'
|
This is a very important commit. It ensures that the whole repository is kept consistent.
|
refinery_refinerycms
|
train
|
f5ad895ba624b6baddfa0c54a2da439b41b0535f
|
diff --git a/integration-cli/docker_cli_events_test.go b/integration-cli/docker_cli_events_test.go
index <HASH>..<HASH> 100644
--- a/integration-cli/docker_cli_events_test.go
+++ b/integration-cli/docker_cli_events_test.go
@@ -317,26 +317,7 @@ func TestEventsFilterContainerID(t *testing.T) {
t.Fatalf("Failed to get events, error: %s(%s)", err, out)
}
events := strings.Split(out, "\n")
- events = events[:len(events)-1]
- if len(events) == 0 || len(events) > 3 {
- t.Fatalf("Expected 3 events, got %d: %v", len(events), events)
- }
- createEvent := strings.Fields(events[0])
- if createEvent[len(createEvent)-1] != "create" {
- t.Fatalf("first event should be create, not %#v", createEvent)
- }
- if len(events) > 1 {
- startEvent := strings.Fields(events[1])
- if startEvent[len(startEvent)-1] != "start" {
- t.Fatalf("second event should be start, not %#v", startEvent)
- }
- }
- if len(events) == 3 {
- dieEvent := strings.Fields(events[len(events)-1])
- if dieEvent[len(dieEvent)-1] != "die" {
- t.Fatalf("event should be die, not %#v", dieEvent)
- }
- }
+ checkEvents(t, events[:len(events)-1])
}
logDone("events - filters using container id")
@@ -363,27 +344,27 @@ func TestEventsFilterContainerName(t *testing.T) {
t.Fatalf("Failed to get events, error : %s(%s)", err, out)
}
events := strings.Split(out, "\n")
- events = events[:len(events)-1]
- if len(events) == 0 || len(events) > 3 {
- t.Fatalf("Expected 3 events, got %d: %v", len(events), events)
- }
- createEvent := strings.Fields(events[0])
- if createEvent[len(createEvent)-1] != "create" {
- t.Fatalf("first event should be create, not %#v", createEvent)
- }
- if len(events) > 1 {
- startEvent := strings.Fields(events[1])
- if startEvent[len(startEvent)-1] != "start" {
- t.Fatalf("second event should be start, not %#v", startEvent)
- }
- }
- if len(events) == 3 {
- dieEvent := strings.Fields(events[len(events)-1])
- if dieEvent[len(dieEvent)-1] != "die" {
- t.Fatalf("event should be die, not %#v", dieEvent)
- }
- }
+ checkEvents(t, events[:len(events)-1])
}
logDone("events - filters using container name")
}
+
+func checkEvents(t *testing.T, events []string) {
+ if len(events) != 3 {
+ t.Fatalf("Expected 3 events, got %d: %v", len(events), events)
+ }
+ createEvent := strings.Fields(events[0])
+ if createEvent[len(createEvent)-1] != "create" {
+ t.Fatalf("first event should be create, not %#v", createEvent)
+ }
+ startEvent := strings.Fields(events[1])
+ if startEvent[len(startEvent)-1] != "start" {
+ t.Fatalf("second event should be start, not %#v", startEvent)
+ }
+ dieEvent := strings.Fields(events[len(events)-1])
+ if dieEvent[len(dieEvent)-1] != "die" {
+ t.Fatalf("event should be die, not %#v", dieEvent)
+ }
+
+}
|
Use common code to test all events, when using filter that expect all lifecycle events.
Addresses: #<I>
|
containers_storage
|
train
|
2b51abaced74e6e062382b1f01fb86002147b2e7
|
diff --git a/all-update.sh b/all-update.sh
index <HASH>..<HASH> 100755
--- a/all-update.sh
+++ b/all-update.sh
@@ -52,7 +52,7 @@ for REPO in "${DIRECTORIES[@]}"; do
# yarn config set registry "https://npm.pkg.github.com/"
if [ -f ".yarnrc.yml" ]; then
# yarn 2, assuming we only use those there
- yarn | grep -v 'YN0013'
+ yarn install | grep -v 'YN0013'
else
yarn --ignore-engines
fi
diff --git a/packages/dev/scripts/polkadot-ci-ghact-build.js b/packages/dev/scripts/polkadot-ci-ghact-build.js
index <HASH>..<HASH> 100755
--- a/packages/dev/scripts/polkadot-ci-ghact-build.js
+++ b/packages/dev/scripts/polkadot-ci-ghact-build.js
@@ -79,6 +79,7 @@ function lernaBump () {
function npmBump () {
execSync('npm --no-git-tag-version --force version patch');
+ execSync('yarn install');
}
function npmGetVersion (noLerna) {
@@ -147,7 +148,6 @@ function gitBump () {
npmBump();
}
- execSync('yarn install');
execSync('git add --all .');
}
diff --git a/packages/dev/scripts/polkadot-dev-version.js b/packages/dev/scripts/polkadot-dev-version.js
index <HASH>..<HASH> 100755
--- a/packages/dev/scripts/polkadot-dev-version.js
+++ b/packages/dev/scripts/polkadot-dev-version.js
@@ -3,6 +3,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
+const { execSync } = require('./execSync');
const { type } = require('yargs')
.options({
type: {
@@ -26,3 +27,5 @@ require('lerna')(
)
.concat(['--yes', '--exact', '--no-git-tag-version', '--no-push', '--allow-branch', '*'])
);
+
+execSync('yarn install');
|
Run yarn on polkadot-dev-version (#<I>)
|
polkadot-js_dev
|
train
|
ca2f9a6027467e43868e4a5b3ba0a23829218133
|
diff --git a/lib/download.js b/lib/download.js
index <HASH>..<HASH> 100644
--- a/lib/download.js
+++ b/lib/download.js
@@ -43,7 +43,6 @@ module.exports.allLibsFile = function allLibsFile(options) {
module.exports.schemas = function schemas(options, allLibs) {
const allLibsRegistry = allLibs.all_libs;
const downloadPromises = [];
- fs.emptyDirSync(path.join(options.outputDir, options.version));
for (let i = 0; i < allLibsRegistry.length; i += 1) {
const schemaFileName = allLibsRegistry[i].entry.replace(/\//g, '.') + schemaSuffix;
|
stops cleaning directory (which cleaned the wrong path anyways)
schema files will seamlessly override old files.
|
ui5experts_ui5-schemas
|
train
|
95c8e7159113469983a8f5e31006899cd349dca9
|
diff --git a/core/src/main/java/hudson/cli/CliCrumbExclusion.java b/core/src/main/java/hudson/cli/CliCrumbExclusion.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/cli/CliCrumbExclusion.java
+++ b/core/src/main/java/hudson/cli/CliCrumbExclusion.java
@@ -43,7 +43,7 @@ public class CliCrumbExclusion extends CrumbExclusion {
@Override
public boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String pathInfo = request.getPathInfo();
- if (pathInfo != null && "/cli".equals(pathInfo)) {
+ if ("/cli".equals(pathInfo)) {
chain.doFilter(request, response);
return true;
}
diff --git a/core/src/main/java/hudson/tasks/ArtifactArchiver.java b/core/src/main/java/hudson/tasks/ArtifactArchiver.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/tasks/ArtifactArchiver.java
+++ b/core/src/main/java/hudson/tasks/ArtifactArchiver.java
@@ -327,7 +327,7 @@ public class ArtifactArchiver extends Recorder implements SimpleBuildStep {
return FormValidation.ok();
}
// defensive approach to remain case sensitive in doubtful situations
- boolean bCaseSensitive = caseSensitive == null || !"false".equals(caseSensitive);
+ boolean bCaseSensitive = !"false".equals(caseSensitive);
return FilePath.validateFileMask(project.getSomeWorkspace(), value, bCaseSensitive);
}
|
String.equals(null) is fast enough...
|
jenkinsci_jenkins
|
train
|
30f6cac131e411c90b6843cb02ad328162e13e07
|
diff --git a/src/frontend/org/voltdb/export/ExportDataSource.java b/src/frontend/org/voltdb/export/ExportDataSource.java
index <HASH>..<HASH> 100644
--- a/src/frontend/org/voltdb/export/ExportDataSource.java
+++ b/src/frontend/org/voltdb/export/ExportDataSource.java
@@ -443,7 +443,7 @@ public class ExportDataSource implements Comparable<ExportDataSource> {
//the USO in stream block
if (buffer.capacity() > 8) {
final BBContainer cont = DBBPool.wrapBB(buffer);
- if (m_lastReleaseOffset > 0 && m_lastReleaseOffset >= (uso + (buffer.capacity() - 8))) {
+ if (m_lastReleaseOffset > 0 && m_lastReleaseOffset >= (uso + (buffer.capacity() - 8) - 1)) {
//What ack from future is known?
if (exportLog.isDebugEnabled()) {
exportLog.debug("Dropping already acked USO: " + m_lastReleaseOffset
|
ENG-<I>:
Fixed another off by one error.
|
VoltDB_voltdb
|
train
|
df67aebb502c101a8ed6fbb01bdaf8a2278a2120
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -9,6 +9,7 @@
"babel-plugin-add-module-exports": "0.2.1",
"babel-plugin-transform-class-properties": "^6.16.0",
"babel-plugin-transform-es2015-modules-umd": "6.18.0",
+ "babel-plugin-transform-flow-strip-types": "^6.18.0",
"babel-preset-es2015": "6.16.0",
"babel-preset-es2015-rollup": "1.2.0",
"babel-preset-react": "^6.5.0",
diff --git a/rollup.config.js b/rollup.config.js
index <HASH>..<HASH> 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -10,6 +10,7 @@ const presetEs2015 = require('babel-preset-es2015-rollup');
const babel = rollupBabel({
presets: presetEs2015,
+ plugins: ['transform-flow-strip-types']
});
const plugins = [
babel,
diff --git a/webpack.config.js b/webpack.config.js
index <HASH>..<HASH> 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -41,7 +41,7 @@ const standardConfig = {
test: /\.js$/,
exclude: /node_modules/,
query: {
- plugins: ['transform-class-properties'],
+ plugins: ['transform-class-properties', 'transform-flow-strip-types'],
presets: ['babel-preset-es2015', 'babel-preset-react'],
},
}],
|
feat(FlowType): Remove Flow Types at build-time
Allow building code that contains Flow Type annotations
Issue #<I>
|
skatejs_build
|
train
|
681c4578a70137b45913a3fbde2dd125a9786ed2
|
diff --git a/lib/slop.rb b/lib/slop.rb
index <HASH>..<HASH> 100644
--- a/lib/slop.rb
+++ b/lib/slop.rb
@@ -430,6 +430,7 @@ class Slop
elsif config[:multiple_switches] && argument
execute_multiple_switches(option, argument, index)
else
+ option.value = option.count > 0
option.call(nil)
end
else
diff --git a/lib/slop/option.rb b/lib/slop/option.rb
index <HASH>..<HASH> 100644
--- a/lib/slop/option.rb
+++ b/lib/slop/option.rb
@@ -84,8 +84,11 @@ class Slop
#
# Returns the Object once any type conversions have taken place.
def value
- value = @value || config[:default]
- return if value.nil?
+ value = instance_variable_defined?(:@value) ? @value : config[:default]
+ case value
+ when true, false, nil
+ return value
+ end
type = config[:as]
if type.respond_to?(:call)
|
consider how options are (un-)specified
|
leejarvis_slop
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.