hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
84b8bcb479cd8e30e6b80788686bb77b92fa80dd | diff --git a/vectors.go b/vectors.go
index <HASH>..<HASH> 100644
--- a/vectors.go
+++ b/vectors.go
@@ -387,18 +387,17 @@ func (x *Vector) Push(y float64) {
return
}
-func (x *Vector) PushFixed(y float64) {
+func (x *Vector) PushFixed(y float64) error {
lenx := len(*x)
- //fmt.Printf("len %d cap: %d\n", lenx, cap(*x))
if lenx == cap(*x) {
slicex := (*x)[1:]
z := make([]float64, lenx, lenx)
copy(z, slicex)
z[lenx-1] = y
- //fmt.Println(z)
*x = z
+ return nil
} else {
- fmt.Printf("Vector len and cap different!", x)
+ return fmt.Errorf("GoVector len and cap different! %#v", x)
}
}
diff --git a/vectors_test.go b/vectors_test.go
index <HASH>..<HASH> 100644
--- a/vectors_test.go
+++ b/vectors_test.go
@@ -85,13 +85,15 @@ func TestFixedPush(t *testing.T) {
arr := make([]float64, 3, 3)
v := Vector(arr)
- v.PushFixed(5.0)
- v.PushFixed(25.0)
- v.PushFixed(125.0)
+ err := v.PushFixed(5.0)
+ err = v.PushFixed(25.0)
+ err = v.PushFixed(125.0)
assert.Equal(t, v[2], 125.0)
- v.PushFixed(250.0)
- assert.Equal(t, v[2], 250.0)
- assert.Equal(t, v[0], 25.0)
+ err = v.PushFixed(250.0)
+ err = v.PushFixed(350.0)
+ assert.Equal(t, err, nil)
+ assert.Equal(t, v[2], 350.0)
+ assert.Equal(t, v[0], 125.0)
assert.Equal(t, len(v), 3)
} | Updating tests to handle returned error | drewlanenga_govector | train |
11733c6bf1266086b04e13a46e4feed537c5d2cc | diff --git a/ontrack-web/src/app/service/service.buildfilter.js b/ontrack-web/src/app/service/service.buildfilter.js
index <HASH>..<HASH> 100644
--- a/ontrack-web/src/app/service/service.buildfilter.js
+++ b/ontrack-web/src/app/service/service.buildfilter.js
@@ -18,7 +18,12 @@ angular.module('ot.service.buildfilter', [
title: "New filter",
form: config.buildFilterForm.form,
submit: function (filterData) {
- // TODO Stores locally the filter data if named
+ // Stores locally the filter data if named
+ if (filterData.name) {
+ // TODO self.storeForBranch(config, filterData);
+ }
+ // Stores locally as current
+ self.storeCurrent(config, filterData);
// Stores for the reuse
result.filterData = filterData;
// OK
@@ -30,6 +35,12 @@ angular.module('ot.service.buildfilter', [
return d.promise;
};
+ self.storeCurrent = function (config, filterData) {
+ localStorage.setItem('build_filter_' + config.branchId + '_current',
+ JSON.stringify(filterData)
+ );
+ };
+
return self;
})
;
\ No newline at end of file | Build filter: storing the current filter locally | nemerosa_ontrack | train |
53baa676adb85984b85d4313cba61bb1edcedd09 | diff --git a/docs/conf.py b/docs/conf.py
index <HASH>..<HASH> 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -26,6 +26,12 @@ class Mock(object):
def __call__(self, *args, **kwargs):
return Mock()
+ def __div__(self, other):
+ pass
+
+ def __truediv__(self, other):
+ pass
+
@classmethod
def __getattr__(cls, name):
if name in ('__file__', '__path__'): | try to fix RTFD build again | tdsmith_eleven | train |
24b6b478bc2be291b9bc38fce3656b5d60ec6362 | diff --git a/web3/contract.py b/web3/contract.py
index <HASH>..<HASH> 100644
--- a/web3/contract.py
+++ b/web3/contract.py
@@ -1027,7 +1027,7 @@ class ContractEvent:
fromBlock=None,
toBlock="latest",
address=None,
- topics=dict()):
+ topics=list()):
"""
Create filter object that tracks logs emitted by this contract event.
:param filter_params: other parameters to limit the events
@@ -1035,6 +1035,9 @@ class ContractEvent:
if not fromBlock:
raise ValueError("Missing mandatory keyword argument to createFilter: fromBlock")
+ if not address:
+ address = self.address
+
_filters = dict(**argument_filters)
data_filter_set, event_filter_params = construct_event_filter_params(
diff --git a/web3/providers/eth_tester/middleware.py b/web3/providers/eth_tester/middleware.py
index <HASH>..<HASH> 100644
--- a/web3/providers/eth_tester/middleware.py
+++ b/web3/providers/eth_tester/middleware.py
@@ -36,11 +36,11 @@ def is_named_block(value):
return value in {"latest", "earliest", "pending"}
-def is_str_is_hex(value):
+def is_hexstr(value):
return is_string(value) and is_hex(value)
-to_integer_if_hex = apply_formatter_if(is_str_is_hex, hex_to_integer)
+to_integer_if_hex = apply_formatter_if(is_hexstr, hex_to_integer)
is_not_named_block = complement(is_named_block) | Make contract address default for createEvent | ethereum_web3.py | train |
d1d40cc4bbe230161a903c38325d6a48b38cfe15 | diff --git a/lib/gir_ffi/i_repository.rb b/lib/gir_ffi/i_repository.rb
index <HASH>..<HASH> 100644
--- a/lib/gir_ffi/i_repository.rb
+++ b/lib/gir_ffi/i_repository.rb
@@ -109,15 +109,7 @@ module GirFFI
def dependencies namespace
strz = Lib.g_irepository_get_dependencies @gobj, namespace
- return [] if strz.null?
- arr = []
- i = 0
- loop do
- ptr = strz.get_pointer i * FFI.type_size(:pointer)
- return arr if ptr.null?
- arr << ptr.read_string
- i += 1
- end
+ ArgHelper.strz_to_utf8_array strz
end
def shared_library namespace | Use newly created argument helper method in IRepository implementation. | mvz_gir_ffi | train |
2b58f53708d39f1e3de78b831cd049a90890705e | diff --git a/js/impress.js b/js/impress.js
index <HASH>..<HASH> 100644
--- a/js/impress.js
+++ b/js/impress.js
@@ -16,6 +16,9 @@
* source: http://github.com/bartaz/impress.js/
*/
+/*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, latedef:true, newcap:true,
+ noarg:true, noempty:true, undef:true, strict:true, browser:true */
+
(function ( document, window ) {
'use strict';
@@ -116,7 +119,7 @@
var impressSupported = ( pfx("perspective") !== null ) &&
( body.classList ) &&
( body.dataset ) &&
- ( ua.search(/(iphone)|(ipod)|(android)/) == -1 );
+ ( ua.search(/(iphone)|(ipod)|(android)/) === -1 );
if (!impressSupported) {
// we can't be sure that `classList` is supported
@@ -158,7 +161,7 @@
// hardcoding these values looks pretty bad, as they kind of depend on the content
// so they should be at least configurable
meta.content = "width=device-width, minimum-scale=1, maximum-scale=1, user-scalable=no";
- if (meta.parentNode != document.head) {
+ if (meta.parentNode !== document.head) {
meta.name = 'viewport';
document.head.appendChild(meta);
}
@@ -281,7 +284,7 @@
var windowScale = computeWindowScale();
var stepTo = function ( el, force ) {
- if ( !isStep(el) || (el == active && !force) ) {
+ if ( !isStep(el) || (el === active && !force) ) {
// selected element is not defined as step or is already active
return false;
}
@@ -422,14 +425,14 @@
// prevent default keydown action when one of supported key is pressed
document.addEventListener("keydown", function ( event ) {
- if ( event.keyCode == 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) {
+ if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) {
event.preventDefault();
}
}, false);
// trigger impress action on keyup
document.addEventListener("keyup", function ( event ) {
- if ( event.keyCode == 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) {
+ if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) {
switch( event.keyCode ) {
case 33: // pg up
case 37: // left
@@ -454,16 +457,16 @@
// event delegation with "bubbling"
// check if event target (or any of its parents is a link)
var target = event.target;
- while ( (target.tagName != "A") &&
- (target != document.documentElement) ) {
+ while ( (target.tagName !== "A") &&
+ (target !== document.documentElement) ) {
target = target.parentNode;
}
- if ( target.tagName == "A" ) {
+ if ( target.tagName === "A" ) {
var href = target.getAttribute("href");
// if it's a link to presentation step, target this step
- if ( href && href[0] == '#' ) {
+ if ( href && href[0] === '#' ) {
target = document.getElementById( href.slice(1) );
}
}
@@ -479,7 +482,7 @@
var target = event.target;
// find closest step element
while ( !target.classList.contains("step") &&
- (target != document.documentElement) ) {
+ (target !== document.documentElement) ) {
target = target.parentNode;
} | "making jshint even more happy with custom config" | impress_impress.js | train |
54c68373fb4dbb4272519ba2b856bdc63cc20d6d | diff --git a/installation-bundle/src/Controller/InstallationController.php b/installation-bundle/src/Controller/InstallationController.php
index <HASH>..<HASH> 100644
--- a/installation-bundle/src/Controller/InstallationController.php
+++ b/installation-bundle/src/Controller/InstallationController.php
@@ -12,6 +12,7 @@ namespace Contao\InstallationBundle\Controller;
use Contao\CoreBundle\Command\InstallCommand;
use Contao\CoreBundle\Command\SymlinksCommand;
+use Contao\CoreBundle\Exception\IncompleteInstallationException;
use Contao\Encryption;
use Contao\Environment;
use Contao\InstallationBundle\Config\ParameterDumper;
@@ -62,14 +63,18 @@ class InstallationController implements ContainerAwareInterface
*/
public function installAction()
{
- if ($this->container->has('contao.framework')) {
- $this->container->get('contao.framework')->initialize();
- }
-
if (null !== ($response = $this->runPostInstallCommands())) {
return $response;
}
+ if ($this->container->has('contao.framework')) {
+ try {
+ $this->container->get('contao.framework')->initialize();
+ } catch (IncompleteInstallationException $e) {
+ // ignore
+ }
+ }
+
$installTool = $this->container->get('contao.install_tool');
if ($installTool->isLocked()) { | [Installation] Ignore the IncompleteInstallationException in the install tool. | contao_contao | train |
c542975f182af77d66aea1efc8d8b5e2958a371e | diff --git a/spec/facemock/config_spec.rb b/spec/facemock/config_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/facemock/config_spec.rb
+++ b/spec/facemock/config_spec.rb
@@ -175,19 +175,19 @@ describe Facemock::Config do
expect(Facemock::Application.all.count).to eq app_count
expect(Facemock::User.all.count).to eq user_count
end
- end
- context 'when already exist specified users' do
- before do
- @path = create_temporary_yaml_file(yaml_load_data)
- Facemock::Config.load_users(@path)
- end
+ context 'when already exist specified users' do
+ before do
+ Facemock::Config.load_users(@path)
+ end
- it 'should not raise error' do
- size = Facemock::User.all.size
- expect(size).to eq 3
- Facemock::Config.load_users(@path)
- expect(size).to eq 3
+ it 'should not raise error' do
+ size = Facemock::User.all.size
+ expect(size).to eq 3
+ path = create_temporary_yaml_file(yaml_load_data)
+ Facemock::Config.load_users(path)
+ expect(size).to eq 3
+ end
end
end
end | :bug: FM-5 : Fixed to bug in test | ogawatti_facemock | train |
0095c37f8650437a5dfe741b8518d4e0f86c7cdc | diff --git a/actor-apps/app-web/src/app/components/ActivitySection.react.js b/actor-apps/app-web/src/app/components/ActivitySection.react.js
index <HASH>..<HASH> 100644
--- a/actor-apps/app-web/src/app/components/ActivitySection.react.js
+++ b/actor-apps/app-web/src/app/components/ActivitySection.react.js
@@ -21,18 +21,18 @@ class ActivitySection extends React.Component {
constructor() {
super();
- this._setActivityClosed = this._setActivityClosed.bind(this);
- this._onChange = this._onChange.bind(this);
+ this.setActivityClosed = this.setActivityClosed.bind(this);
+ this.onChange = this.onChange.bind(this);
this.state = getStateFromStores();
}
componentDidMount() {
- ActivityStore.addChangeListener(this._onChange);
+ ActivityStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
- ActivityStore.removeChangeListener(this._onChange);
+ ActivityStore.removeChangeListener(this.onChange);
}
render() {
@@ -59,7 +59,7 @@ class ActivitySection extends React.Component {
return (
<section className={activityClassName}>
- <ActivitySection.Header close={this._setActivityClosed} title={activityTitle}/>
+ <ActivitySection.Header close={this.setActivityClosed} title={activityTitle}/>
{activityBody}
</section>
);
@@ -68,11 +68,11 @@ class ActivitySection extends React.Component {
}
}
- _setActivityClosed() {
+ setActivityClosed() {
ActivityActionCreators.hide();
}
- _onChange() {
+ onChange() {
this.setState(getStateFromStores());
}
} | refactor(web): remove dash from functions name; | actorapp_actor-platform | train |
3a0893f8430551e9d75a84e8b16b12921ffd5b19 | diff --git a/openquake/calculators/risk/general.py b/openquake/calculators/risk/general.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/risk/general.py
+++ b/openquake/calculators/risk/general.py
@@ -276,9 +276,9 @@ def fetch_vulnerability_model(job_id, retrofitted=False):
"""
if retrofitted:
- input_type = "vulnerability"
- else:
input_type = "vulnerability_retrofitted"
+ else:
+ input_type = "vulnerability"
return models.OqJob.objects.get(pk=job_id).risk_calculation.model(
input_type).to_risklib()
diff --git a/tests/calculators/risk/classical_bcr/core_test.py b/tests/calculators/risk/classical_bcr/core_test.py
index <HASH>..<HASH> 100644
--- a/tests/calculators/risk/classical_bcr/core_test.py
+++ b/tests/calculators/risk/classical_bcr/core_test.py
@@ -35,7 +35,7 @@ class ClassicalBCRRiskCalculatorTestCase(
def shortDescription(self):
"""
- Use method names instead of comments for verbose output
+ Use method names instead of docstrings for verbose output
"""
return None | changed signature of fetch_vulnerability_model | gem_oq-engine | train |
e088b319e725d100076905e26880291dad687e9b | diff --git a/sramongo/sra2mongo.py b/sramongo/sra2mongo.py
index <HASH>..<HASH> 100644
--- a/sramongo/sra2mongo.py
+++ b/sramongo/sra2mongo.py
@@ -11,6 +11,7 @@ from logging import INFO, DEBUG
import pandas as pd
import time
from shutil import rmtree
+from glob import glob
from Bio import Entrez
from mongoengine import connect
@@ -52,6 +53,12 @@ class Cache(object):
with open(os.path.join(self.cachedir, fname), 'w') as fh:
fh.write(data)
+ def remove_from_cache(self, name):
+ self.cached.discard(name)
+ for fn in glob(os.path.join(self.cachedir, name + '*')):
+ if os.path.exists(fn):
+ os.remove(fn)
+
def get_cache(self, name, _type):
if _type == 'xml':
ext = 'xml'
@@ -228,6 +235,7 @@ def fetch_ncbi(records, cache, runinfo_retmode='text', **kwargs):
else:
logger.error("Received error from server %s" % err)
logger.error("Please re-run command latter.")
+ cache.remove_from_cache(start)
sys.exit(1)
except IncompleteRead as err:
if attempt < 3:
@@ -237,15 +245,18 @@ def fetch_ncbi(records, cache, runinfo_retmode='text', **kwargs):
else:
logger.error("Received error from server %s" % err)
logger.error("Please re-run command latter.")
+ cache.remove_from_cache(start)
sys.exit(1)
except URLError as err:
if (err.code == 60) & (attempt < 3):
logger.warning("Received error from server %s" % err)
logger.warning("Attempt %i of 3" % attempt)
+ cache.remove_from_cache(start)
time.sleep(15)
else:
logger.error("Received error from server %s" % err)
logger.error("Please re-run command latter.")
+ cache.remove_from_cache(start)
sys.exit(1) | Adds logic to remove item from cache if download failed.
Added a new function to the cache object to allow removal of cached
files if the download fails for some reason. | jfear_sramongo | train |
691f254feb94bda19eaf54fbc6de363cd3ee7f5c | diff --git a/src/postfix.js b/src/postfix.js
index <HASH>..<HASH> 100644
--- a/src/postfix.js
+++ b/src/postfix.js
@@ -1,9 +1,9 @@
-
+
var Mexp=require('./lexer.js');
- if(!Array.indexOf)
+ if(!(Array.indexOf || Array.prototype.indexOf))
Array.prototype.indexOf = function (vItem) {
for (var i=0; i < this.length; i++) {
- if (vItem == this[i]) {
+ if (vItem === this[i]) {
return i;
}
}
diff --git a/test/index.js b/test/index.js
index <HASH>..<HASH> 100644
--- a/test/index.js
+++ b/test/index.js
@@ -111,3 +111,13 @@ describe('Testing Unit', function () {
assert.equal(a.eval("5*.8"),"4");
});
});
+
+describe('Verifying indexOf', function () {
+ it('does not break indexOf', function () {
+ var a = 1;
+ var b = '1';
+ var array = [a, b];
+ assert.equal(array.indexOf(a), 0);
+ assert.equal(array.indexOf(b), 1);
+ });
+});
\ No newline at end of file | Improve check for indexOf polyfill. Use triple equals within indexOf implementation. | redhivesoftware_math-expression-evaluator | train |
51943195bffd4511dcdb832c184b7e7c5556c7dc | diff --git a/config.js b/config.js
index <HASH>..<HASH> 100755
--- a/config.js
+++ b/config.js
@@ -48,15 +48,12 @@ if(cluster.isMaster){
}
// file logger
+try{
+ fs.mkdirSync("./log");
+}catch(e){
+ if(e.code != "EEXIST"){ console.log(e); process.exit(); }
+}
configData.logger.transports.push(function(api, winston){
- try{
- fs.mkdirSync("./log");
- console.log("created ./log directory");
- }catch(e){
- if(e.code != "EEXIST"){
- console.log(e); process.exit();
- }
- }
return new (winston.transports.File)({
filename: './log/' + api.pids.title + '.log',
level: "info",
diff --git a/initializers/logger.js b/initializers/logger.js
index <HASH>..<HASH> 100644
--- a/initializers/logger.js
+++ b/initializers/logger.js
@@ -15,7 +15,17 @@ var logger = function(api, next){
}
api.logger = new (winston.Logger)({
- levels: winston.config.syslog.levels,
+ // TODO We need to manually make these levels until winston switches the order back
+ levels: {
+ emerg: 7,
+ alert: 6,
+ crit: 5,
+ error: 4,
+ warning: 3,
+ notice: 2,
+ info: 1,
+ debug: 0
+ },
transports: transports
});
@@ -26,7 +36,11 @@ var logger = function(api, next){
api.log = function(message, severity, data){
if(severity == null){ severity = "info"; }
if(api.logger.levels[severity] == null){ severity = "info"; }
- api.logger.log(severity, message, data);
+ if(data != null){
+ api.logger.log(severity, message, data);
+ }else{
+ api.logger.log(severity, message);
+ }
}
var logLevels = [];
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100755
--- a/package.json
+++ b/package.json
@@ -37,7 +37,7 @@
"mime": "1.2.x",
"redis": "0.8.x",
"optimist": "0.5.x",
- "winston": "0.6.x",
+ "winston": "0.7.2",
"node-uuid": "1.4.x",
"fakeredis": "0.1.x",
"faye": "0.8.x", | update winston version to fix file logs | actionhero_actionhero | train |
406d047fe84ed063f02f045ae9a0d67ecb45a76a | diff --git a/auto_lens/test_galaxy_prior.py b/auto_lens/test_galaxy_prior.py
index <HASH>..<HASH> 100644
--- a/auto_lens/test_galaxy_prior.py
+++ b/auto_lens/test_galaxy_prior.py
@@ -53,3 +53,12 @@ class TestGalaxyPrior:
instance = MockModelInstance()
with pytest.raises(gp.PriorException):
galaxy_prior.galaxy_for_model_instance(instance)
+
+ def test_multiple_galaxies(self, galaxy_prior, mapper):
+ galaxy_prior_2 = gp.GalaxyPrior(light_profile_classes=[light_profiles.EllipticalDevVaucouleurs],
+ mass_profile_classes=[mass_profiles.EllipticalCoredIsothermal])
+
+ galaxy_prior.attach_to_model_mapper(mapper)
+ galaxy_prior_2.attach_to_model_mapper(mapper)
+
+ assert len(mapper.classes) == 4 | writing test for multiple galaxies | Jammy2211_PyAutoLens | train |
eae81b9c353e25b9317c1d4a3c1f70b60f5e21d2 | diff --git a/lib/rubycritic/source_locator.rb b/lib/rubycritic/source_locator.rb
index <HASH>..<HASH> 100644
--- a/lib/rubycritic/source_locator.rb
+++ b/lib/rubycritic/source_locator.rb
@@ -23,15 +23,11 @@ module Rubycritic
def expand_paths
@user_paths.map do |path|
if File.directory?(path)
- Pathname.glob(files_contained_in(path))
+ Pathname.glob(File.join(path, RUBY_FILES))
elsif File.exists?(path) && File.extname(path) == RUBY_EXTENSION
Pathname.new(path)
end
- end.flatten.compact.sort
- end
-
- def files_contained_in(path)
- (path == ".") ? RUBY_FILES : File.join(path, RUBY_FILES)
+ end.flatten.compact.map(&:cleanpath).sort
end
end
diff --git a/test/lib/rubycritic/source_locator_test.rb b/test/lib/rubycritic/source_locator_test.rb
index <HASH>..<HASH> 100644
--- a/test/lib/rubycritic/source_locator_test.rb
+++ b/test/lib/rubycritic/source_locator_test.rb
@@ -18,15 +18,21 @@ describe Rubycritic::SourceLocator do
Rubycritic::SourceLocator.new(paths).paths.must_equal paths
end
+ it "finds all the files inside a given directory" do
+ initial_paths = ["dir1"]
+ final_paths = ["dir1/file1.rb"]
+ Rubycritic::SourceLocator.new(initial_paths).paths.must_equal final_paths
+ end
+
it "finds all the files" do
initial_paths = ["."]
final_paths = ["dir1/file1.rb", "file0.rb"]
Rubycritic::SourceLocator.new(initial_paths).paths.must_equal final_paths
end
- it "finds all the files inside a given directory" do
- initial_paths = ["dir1"]
- final_paths = ["dir1/file1.rb"]
+ it "cleans paths of consecutive slashes and useless dots" do
+ initial_paths = [".//file0.rb"]
+ final_paths = ["file0.rb"]
Rubycritic::SourceLocator.new(initial_paths).paths.must_equal final_paths
end | Remove consecutive slashes and useless dots from paths | whitesmith_rubycritic | train |
1df69870b410b12d0665440f387fd968e2a95c40 | diff --git a/Behat/WebContext.php b/Behat/WebContext.php
index <HASH>..<HASH> 100644
--- a/Behat/WebContext.php
+++ b/Behat/WebContext.php
@@ -377,23 +377,49 @@ class WebContext extends DefaultContext
}
/**
+ * @Given /^I add following attributes:$/
+ */
+ public function iAddFollowingAttributes(TableNode $attributes)
+ {
+ $pickedAttributes = array();
+ foreach ($attributes->getRows() as $attribute) {
+ $pickedAttributes[] = $attribute[0];
+ }
+
+ $this->addAttributes($pickedAttributes);
+ }
+
+ /**
* @Given /^I add "([^"]*)" attribute$/
*/
public function iAddAttribute($attribute)
{
+ $this->addAttributes(array($attribute));
+ }
+
+ /**
+ * @param array $attributes
+ */
+ private function addAttributes(array $attributes)
+ {
$this->clickLink('Add');
$attributesModalContainer = $this->getSession()->getPage()->find('css', '#attributes-modal');
$addAttributesButton = $attributesModalContainer->find('css', sprintf('button:contains("%s")', 'Add attributes'));
+ $this->getSession()->wait(200);
+
$this->waitForModalToAppear($attributesModalContainer);
- $this->getSession()->getPage()->checkField($attribute.' attribute');
+ foreach ($attributes as $attribute) {
+ $this->getSession()->getPage()->checkField($attribute.' attribute');
+ }
+
$addAttributesButton->press();
$this->waitForModalToDisappear($attributesModalContainer);
- $this->getSession()->wait(500);
+ $this->getSession()->wait(200);
}
/** | [Attribute] Final fixed in attribute scenarios
- slightly change adding attributes to product
- written additional scenario for adding multiple attributes
- added some waits to prevent errors | Sylius_SyliusResourceBundle | train |
1a9b2d515507ba04600f68fd5a2de996058ebd5c | diff --git a/src/core.js b/src/core.js
index <HASH>..<HASH> 100644
--- a/src/core.js
+++ b/src/core.js
@@ -416,28 +416,45 @@ Crafty.fn = Crafty.prototype = {
/**@
* #.attr
* @comp Crafty Core
- * @sign public this .attr(String property, * value)
+ * @trigger Change - when properties change - {key: value}
+ *
+ * @sign public this .attr(String property, Any value[, Boolean silent[, Boolean recursive]])
* @param property - Property of the entity to modify
* @param value - Value to set the property to
* @param silent - If you would like to supress events
* @param recursive - If you would like merge recursively
- * @sign public this .attr(Object map)
- * @param map - Object where the key is the property to modify and the value as the property value
- * @trigger Change - when properties change - {key: value}
- *
* Use this method to set any property of the entity.
*
+ * @sign public this .attr(Object map[, Boolean silent[, Boolean recursive]])
+ * @param map - Object where each key is the property to modify and the value as the property value
+ * @param silent - If you would like to supress events
+ * @param recursive - If you would like merge recursively
+ * Use this method to set multiple properties of the entity.
+ *
+ * Setter options:
+ * `silent`: If you want to prevent it from firing events.
+ * `recursive`: If you pass in an object you could overwrite sibling keys, this recursively merges instead of just merging it. This is `false` by default, unless you are using dot notation `name.first`.
+ *
+ * @sign public Any .attr(String property)
+ * @param property - Property of the entity to modify
+ * @returns Value - the value of the property
+ * Use this method to get any property of the entity. You can also retrieve the property using `this.property`.
+ *
+ *
* @example
* ~~~
* this.attr({key: "value", prop: 5});
- * this.key; //value
- * this.prop; //5
+ * this.attr("key"); // returns "value"
+ * this.attr("prop"); // returns 5
+ * this.key; // "value"
+ * this.prop; // 5
*
* this.attr("key", "newvalue");
- * this.key; //newvalue
+ * this.attr("key"); // returns "newvalue"
+ * this.key; // "newvalue"
*
* this.attr("parent.child", "newvalue");
- * this.parent; //{child: "newvalue"};
+ * this.parent; // {child: "newvalue"};
* this.attr('parent.child'); // "newvalue"
* ~~~
*/
@@ -450,13 +467,13 @@ Crafty.fn = Crafty.prototype = {
},
/**
- * Getter method for data on the entity.
+ * Internal getter method for data on the entity. Called by `.attr`.
*
- * @example
+ * example
* ~~~
* person._attr_get('name'); // Foxxy
- * person._attr_get('contact'); // {email: '[email protected]'}
- * person._attr_get('contact.email'); // [email protected]
+ * person._attr_get('contact'); // {email: 'fox_at_example.com'}
+ * person._attr_get('contact.email'); // fox_at_example.com
* ~~~
*/
_attr_get: function(key, context) {
@@ -475,7 +492,7 @@ Crafty.fn = Crafty.prototype = {
},
/**
- * Setter function for attributes on the component.
+ * Internal setter method for attributes on the component. Called by `.attr`.
*
* Options:
*
@@ -486,7 +503,7 @@ Crafty.fn = Crafty.prototype = {
* merging it. This is `false` by default, unless you are
* using dot notation `name.first`.
*
- * @example
+ * example
* ~~~
* person._attr_set('name', 'Foxxy', true);
* person._attr_set('name', 'Foxxy'); | Improve attr documentation
This commit fixes #<I>, it also adds new signatures and more
detailed explanation to the inner workings of attr. | craftyjs_Crafty | train |
15e37abfdeecbf49f61fab0c06003ce4237a1e42 | diff --git a/autopep8.py b/autopep8.py
index <HASH>..<HASH> 100755
--- a/autopep8.py
+++ b/autopep8.py
@@ -2032,39 +2032,39 @@ def fix_multiple_files(filenames, options, output=None):
def main():
"""Tool main."""
- options, args = parse_args(sys.argv[1:])
+ try:
+ options, args = parse_args(sys.argv[1:])
- if options.list_fixes:
- for code, description in supported_fixes():
- print('{code} - {description}'.format(
- code=code, description=description))
- return 0
+ if options.list_fixes:
+ for code, description in supported_fixes():
+ print('{code} - {description}'.format(
+ code=code, description=description))
+ return
- if options.in_place or options.diff:
- filenames = list(set(args))
- else:
- assert len(args) == 1
- assert not options.recursive
- if args == ['-']:
- assert not options.in_place
- temp = temporary_file()
- temp.write(sys.stdin.read())
- temp.flush()
- filenames = [temp.name]
+ if options.in_place or options.diff:
+ filenames = list(set(args))
else:
- filenames = args[:1]
+ assert len(args) == 1
+ assert not options.recursive
+ if args == ['-']:
+ assert not options.in_place
+ temp = temporary_file()
+ temp.write(sys.stdin.read())
+ temp.flush()
+ filenames = [temp.name]
+ else:
+ filenames = args[:1]
- output = codecs.getwriter('utf-8')(sys.stdout.buffer
- if sys.version_info[0] >= 3
- else sys.stdout)
+ output = codecs.getwriter('utf-8')(sys.stdout.buffer
+ if sys.version_info[0] >= 3
+ else sys.stdout)
- output = LineEndingWrapper(output)
+ output = LineEndingWrapper(output)
- fix_multiple_files(filenames, options, output)
+ fix_multiple_files(filenames, options, output)
+ except KeyboardInterrupt:
+ sys.exit(1)
if __name__ == '__main__':
- try:
- sys.exit(main())
- except KeyboardInterrupt:
- sys.exit(1)
+ main() | Move catching of KeyboardInterrupt
This necessary for when we use autopep8 via main entry point. | hhatto_autopep8 | train |
82ae4ee219c05fde09b2996992e2736f22396ca5 | diff --git a/lib/logger.js b/lib/logger.js
index <HASH>..<HASH> 100644
--- a/lib/logger.js
+++ b/lib/logger.js
@@ -243,7 +243,7 @@ var proto = {
dbug('%s filtered message [%s]', this._name, record.message);
}
- if (promises.length > 2) {
+ if (promises.length > 1) {
return Promise.all(promises);
} else if (promises[0]) {
return promises[0]; | fix promises if there were exactly 2 handlers | seanmonstar_intel | train |
81580efdccb2b8ced4200443baba21bc76a4b6c7 | diff --git a/spec/models/no_cms/blocks/i18n_blocks_spec.rb b/spec/models/no_cms/blocks/i18n_blocks_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/no_cms/blocks/i18n_blocks_spec.rb
+++ b/spec/models/no_cms/blocks/i18n_blocks_spec.rb
@@ -37,11 +37,14 @@ describe NoCms::Blocks::Block do
context "when we have some untranslated fields" do
let(:block_title) { Faker::Lorem.sentence }
+ let(:block_body_es) { Faker::Lorem.paragraph }
+ let(:block_body_en) { Faker::Lorem.paragraph }
+
let!(:block) { NoCms::Blocks::Block.create! title: block_title,
layout: 'title-long_text',
translations_attributes: [
- { locale: 'es', body: Faker::Lorem.paragraph },
- { locale: 'en', body: Faker::Lorem.paragraph }
+ { locale: 'es', body: block_body_es },
+ { locale: 'en', body: block_body_en }
]
}
@@ -61,10 +64,15 @@ describe NoCms::Blocks::Block do
subject { NoCms::Blocks::Block.find block.id }
- it "should retrieve the right text for each language" do
+ it "should retrieve the same unstranslated attribute for each language" do
I18n.with_locale(:es) { expect(subject.title).to eq block_title }
I18n.with_locale(:en) { expect(subject.title).to eq block_title }
end
+ it "should retrieve the right translated attribute for each language" do
+ I18n.with_locale(:es) { expect(subject.body).to eq block_body_es }
+ I18n.with_locale(:en) { expect(subject.body).to eq block_body_en }
+ end
+
end
end | Making sure we can have both translated and untranslated attributes | simplelogica_nocms-blocks | train |
3e56c4a5673663d43e7c321f12fe29d0e9c63f31 | diff --git a/lib/apple_tv_converter/media_converter_adapter.rb b/lib/apple_tv_converter/media_converter_adapter.rb
index <HASH>..<HASH> 100644
--- a/lib/apple_tv_converter/media_converter_adapter.rb
+++ b/lib/apple_tv_converter/media_converter_adapter.rb
@@ -163,6 +163,8 @@ module AppleTvConverter
end
def get_tv_show_db_info(media)
+ printf "* Getting info from TheTVDB"
+
media.tvdb_movie = TvDbFetcher.search(media)
if media.tvdb_movie
media.imdb_id = media.tvdb_movie[:show][:series]['IMDB_ID'] if media.tvdb_movie.has_key?(:show) && media.tvdb_movie[:show].has_key?(:series)
@@ -177,6 +179,10 @@ module AppleTvConverter
media.imdb_episode_id = media.imdb_episode_id.gsub(/\D+/, '') if media.imdb_episode_id
get_imdb_info(media) unless media.imdb_id.nil? || media.imdb_id.blank?
+
+ puts " [DONE]"
+ else
+ puts " [NOT FOUND]"
end
end
diff --git a/lib/apple_tv_converter/tv_db_fetcher.rb b/lib/apple_tv_converter/tv_db_fetcher.rb
index <HASH>..<HASH> 100644
--- a/lib/apple_tv_converter/tv_db_fetcher.rb
+++ b/lib/apple_tv_converter/tv_db_fetcher.rb
@@ -23,21 +23,23 @@ module AppleTvConverter
data[media.show] = if loaded_data.length > 1
choice = 0
+ puts "\n *"
while true
- puts "\n-- Several shows found, choose the intended one:"
+ puts %Q[ | Several shows found, choose the intended one:]
loaded_data.each_with_index do |item, index|
- puts "#{(index + 1).to_s.rjust(loaded_data.length.to_s.length)} - #{item['SeriesName']} (id: #{item['seriesid']})"
- puts "#{' '.rjust(loaded_data.length.to_s.length)} AKA: #{item['AliasNames']}" if item['AliasNames']
+ puts " | #{(index + 1).to_s.rjust(loaded_data.length.to_s.length)} - #{item['SeriesName']} (id: #{item['seriesid']})"
+ puts " | #{' '.rjust(loaded_data.length.to_s.length)} AKA: #{item['AliasNames']}" if item['AliasNames']
end
- printf "\nWhat's your choice (1..#{loaded_data.length})? "
+ printf " |\n *- What's your choice (1..#{loaded_data.length})? "
choice = STDIN.gets.chomp.to_i
break if choice.between?(1, loaded_data.length)
- puts "Invalid choice!"
+ puts " | Invalid choice!"
+ puts " |"
end
loaded_data[choice - 1]['seriesid'] | Updated the selection list outputs to be coherent | gokuu_apple-tv-converter | train |
05af179e8c728199a2ab1879ecece8b8328656e5 | diff --git a/resource_aws_db_instance.go b/resource_aws_db_instance.go
index <HASH>..<HASH> 100644
--- a/resource_aws_db_instance.go
+++ b/resource_aws_db_instance.go
@@ -49,7 +49,6 @@ func resourceAwsDbInstance() *schema.Resource {
"engine_version": &schema.Schema{
Type: schema.TypeString,
Required: true,
- ForceNew: true,
},
"storage_encrypted": &schema.Schema{
@@ -121,7 +120,6 @@ func resourceAwsDbInstance() *schema.Resource {
Type: schema.TypeBool,
Optional: true,
Computed: true,
- ForceNew: true,
},
"port": &schema.Schema{
@@ -189,6 +187,16 @@ func resourceAwsDbInstance() *schema.Resource {
Type: schema.TypeString,
Computed: true,
},
+
+ // apply_immediately is used to determine when the update modifications
+ // take place.
+ // See http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.DBInstance.Modifying.html
+ "apply_immediately": &schema.Schema{
+ Type: schema.TypeBool,
+ Optional: true,
+ Computed: true,
+ },
+
"tags": tagsSchema(),
},
}
@@ -423,6 +431,35 @@ func resourceAwsDbInstanceUpdate(d *schema.ResourceData, meta interface{}) error
conn := meta.(*AWSClient).rdsconn
d.Partial(true)
+ // Change is used to determine if a ModifyDBInstanceMessage request actually
+ // gets sent.
+ change := false
+
+ req := &rds.ModifyDBInstanceMessage{
+ ApplyImmediately: aws.Boolean(d.Get("apply_immediately").(bool)),
+ DBInstanceIdentifier: aws.String(d.Id()),
+ }
+
+ if d.HasChange("engine_version") {
+ change = true
+ d.SetPartial("engine_version")
+ req.EngineVersion = aws.String(d.Get("engine_version").(string))
+ }
+
+ if d.HasChange("multi_az") {
+ change = true
+ d.SetPartial("multi_az")
+ req.MultiAZ = aws.Boolean(d.Get("multi_az").(bool))
+ }
+
+ if change {
+ log.Printf("[DEBUG] DB Instance Modification request: %#v", req)
+ _, err := conn.ModifyDBInstance(req)
+ if err != nil {
+ return fmt.Errorf("Error mofigying DB Instance %s: %s", d.Id(), err)
+ }
+ }
+
if arn, err := buildRDSARN(d, meta); err == nil {
if err := setTagsRDS(conn, d, arn); err != nil {
return err | provider/aws: Add non-destructive updates to AWS RDS
This introduces non-destructive, in-place upgrades to MultiAZ and Engine Version
attributes of AWS RDS instances. | terraform-providers_terraform-provider-aws | train |
116a8b0f8689f6b14a3f509cca28950299ba74b3 | diff --git a/hystrix-core/src/test/java/com/netflix/hystrix/HystrixCollapserTest.java b/hystrix-core/src/test/java/com/netflix/hystrix/HystrixCollapserTest.java
index <HASH>..<HASH> 100644
--- a/hystrix-core/src/test/java/com/netflix/hystrix/HystrixCollapserTest.java
+++ b/hystrix-core/src/test/java/com/netflix/hystrix/HystrixCollapserTest.java
@@ -1086,7 +1086,7 @@ public class HystrixCollapserTest {
}
if (request.getArgument().equals("TIMEOUT")) {
try {
- Thread.sleep(200);
+ Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
} | Increased sleep time to make Timeout work as expected in HystrixCollapserTest | Netflix_Hystrix | train |
803bbbba7065dbe2cd23ac360156f65db5bd6c92 | diff --git a/galen-java-support/src/test/java/com/galenframework/junit/GalenJUnitTestBaseIT.java b/galen-java-support/src/test/java/com/galenframework/junit/GalenJUnitTestBaseIT.java
index <HASH>..<HASH> 100644
--- a/galen-java-support/src/test/java/com/galenframework/junit/GalenJUnitTestBaseIT.java
+++ b/galen-java-support/src/test/java/com/galenframework/junit/GalenJUnitTestBaseIT.java
@@ -40,7 +40,7 @@ public class GalenJUnitTestBaseIT extends GalenJUnitTestBase {
@Test
public void shouldConcatenateClassAndMethodNameForTestName() {
assertThat(getTestName(), is(equalTo(
- "com.galenframework.junit.GalenJUnitTestBaseTest#>shouldConcatenateClassAndMethodNameForTestName")));
+ "com.galenframework.junit.GalenJUnitTestBaseIT#>shouldConcatenateClassAndMethodNameForTestName")));
}
@Parameters | Fix test for test name.
The test name changed because the name of the test class changed in
<I>f4ec<I>a<I>a<I>bc9d<I>e9e<I>b9faafb0. | galenframework_galen | train |
55d4479ff6a78366b7fb887796b35144bb65c029 | diff --git a/lib/httparty/request.rb b/lib/httparty/request.rb
index <HASH>..<HASH> 100644
--- a/lib/httparty/request.rb
+++ b/lib/httparty/request.rb
@@ -71,6 +71,7 @@ module HTTParty
def perform(&block)
validate
setup_raw_request
+ chunked_body = nil
self.last_response = http.request(@raw_request) do |http_response|
if block
@@ -81,12 +82,12 @@ module HTTParty
block.call(fragment)
end
- http_response.body = chunks.join
+ chunked_body = chunks.join
end
end
handle_deflation
- handle_response
+ handle_response(chunked_body)
end
private
@@ -197,7 +198,7 @@ module HTTParty
query_string_parts.size > 0 ? query_string_parts.join('&') : nil
end
- def handle_response
+ def handle_response(body)
if response_redirects?
options[:limit] -= 1
self.path = last_response['location']
@@ -206,7 +207,8 @@ module HTTParty
capture_cookies(last_response)
perform
else
- Response.new(self, last_response, parse_response(last_response.body))
+ body = body || last_response.body
+ Response.new(self, last_response, parse_response(body), :body => body)
end
end
diff --git a/lib/httparty/response.rb b/lib/httparty/response.rb
index <HASH>..<HASH> 100644
--- a/lib/httparty/response.rb
+++ b/lib/httparty/response.rb
@@ -35,12 +35,12 @@ module HTTParty
attr_reader :request, :response, :parsed_response, :body, :headers
- def initialize(request, response, parsed_response)
- @request = request
- @response = response
- @body = response.body
+ def initialize(request, response, parsed_response, options={})
+ @request = request
+ @response = response
+ @body = response.body || options[:body]
@parsed_response = parsed_response
- @headers = Headers.new(response.to_hash)
+ @headers = Headers.new(response.to_hash)
end
def class
@@ -64,7 +64,7 @@ module HTTParty
klass === response
end
end
-
+
def respond_to?(name)
return true if [:request,:response,:parsed_response,:body,:headers].include?(name)
parsed_response.respond_to?(name) or response.respond_to?(name) | Horrible hack to fix chunked bodies on <I>. | jnunemaker_httparty | train |
d2c3fba430a0bacdec18f7c7084376957baf4a80 | diff --git a/jquery.isloading.js b/jquery.isloading.js
index <HASH>..<HASH> 100644
--- a/jquery.isloading.js
+++ b/jquery.isloading.js
@@ -140,7 +140,7 @@
if( "overlay" === this.options.position ) {
- $( ".isloading-overlay" ).remove();
+ $( this.element ).find( ".isloading-overlay" ).remove();
} else {
@@ -195,4 +195,4 @@
contruct();
-})( jQuery, window, document );
\ No newline at end of file
+})( jQuery, window, document ); | Allow hide for multiple elements seperately
Updated the hide function so it would make use of the queried element.
This is helpful in situations where you might be making use of multiple overlays on several elements. If you were using multiple elements, previously, and called $({query}).isLoading("hide"); all overlays would disappear at once since the overlay if was just looking for the common class. | hekigan_is-loading | train |
26ab084928c75f2cde335f229e644155de8d9fdd | diff --git a/web/src/main/java/uk/ac/ebi/atlas/transcript/TranscriptsContribution.java b/web/src/main/java/uk/ac/ebi/atlas/transcript/TranscriptsContribution.java
index <HASH>..<HASH> 100644
--- a/web/src/main/java/uk/ac/ebi/atlas/transcript/TranscriptsContribution.java
+++ b/web/src/main/java/uk/ac/ebi/atlas/transcript/TranscriptsContribution.java
@@ -8,7 +8,7 @@ import java.util.Map;
public class TranscriptsContribution {
- protected static final String OTHERS = "OTHERS";
+ protected static final String OTHERS = "Others";
private int totalTranscriptCount;
private LinkedHashMap<String, Double> transcriptExpressions = new LinkedHashMap<>();
diff --git a/web/src/main/webapp/resources/js/heatmapModule.js b/web/src/main/webapp/resources/js/heatmapModule.js
index <HASH>..<HASH> 100644
--- a/web/src/main/webapp/resources/js/heatmapModule.js
+++ b/web/src/main/webapp/resources/js/heatmapModule.js
@@ -119,7 +119,7 @@ var heatmapModule = (function($) {
radius: plotData.length === 1 ? 0 : 3/5,
show: true,
formatter: function(label, series){
- return series.data[0][1] + "%";},
+ return "<span style='display:none'>" + series.data[0][1] + "%</span>";},
background: {
opacity: 0.5
}
@@ -131,15 +131,19 @@ var heatmapModule = (function($) {
show: true,
labelFormatter: function(label){
return label === "Others" ? "Others" :
- "<a href='http://www.ensembl.org/" + species + "/Transcript/Summary?g=" + geneId + ";t=" + label + "' target='_blank'>" +
+ "<a href='http://www.ensembl.org/" + species + "/Transcript/Summary?g=" + geneId + ";t="
+ + label + "' target='_blank'" + "title='View transcript in Ensembl'" + ">" +
label + "</a>";
}
}
});
+ var s = '';
+ if (totalCount > 1) {s = 's'};
$('#transcript-breakdown-title').html("Expression Level Breakdown for " +
- "<a href='http://www.ensembl.org/" + species + "/Gene/Summary?g=" + geneId + "' target='_blank'>" +
- geneName + "</a>" + " (" + totalCount + " transcripts) on " + factorValue);
+ "<a href='http://www.ensembl.org/" + species + "/Gene/Summary?g=" + geneId +
+ "' target='_blank'" + "title='View gene in Ensembl'" + ">" +
+ geneName + "</a>" + " (" + totalCount + " transcript" + s + ") in " + factorValue);
$.fancybox({href : '#transcript-breakdown', | minor changes (from Robert's comments) | ebi-gene-expression-group_atlas | train |
937c8174f5a3aa416e8457f9fb9b7bbd205ed8cd | diff --git a/lib/Elastica/Query/Ids.php b/lib/Elastica/Query/Ids.php
index <HASH>..<HASH> 100644
--- a/lib/Elastica/Query/Ids.php
+++ b/lib/Elastica/Query/Ids.php
@@ -2,7 +2,7 @@
namespace Elastica\Query;
-use Elastica\Type;
+use Elastica\Type as ElasticaType;
/**
* Ids Query.
@@ -50,7 +50,7 @@ class Ids extends AbstractQuery
*/
public function addType($type)
{
- if ($type instanceof Type) {
+ if ($type instanceof ElasticaType) {
$type = $type->getName();
} elseif (empty($type) && !is_numeric($type)) {
// A type can be 0, but cannot be empty
@@ -71,7 +71,7 @@ class Ids extends AbstractQuery
*/
public function setType($type)
{
- if ($type instanceof Type) {
+ if ($type instanceof ElasticaType) {
$type = $type->getName();
} elseif (empty($type) && !is_numeric($type)) {
// A type can be 0, but cannot be empty
diff --git a/test/lib/Elastica/Test/Query/IdsTest.php b/test/lib/Elastica/Test/Query/IdsTest.php
index <HASH>..<HASH> 100644
--- a/test/lib/Elastica/Test/Query/IdsTest.php
+++ b/test/lib/Elastica/Test/Query/IdsTest.php
@@ -4,6 +4,7 @@ namespace Elastica\Test\Query;
use Elastica\Document;
use Elastica\Query\Ids;
+use Elastica\Query\Type;
use Elastica\Test\Base as BaseTest;
class IdsTest extends BaseTest
@@ -185,4 +186,17 @@ class IdsTest extends BaseTest
$this->assertEquals(1, $resultSet->count());
}
+
+ public function testQueryTypeAndTypeCollision()
+ {
+ // This test ensures that Elastica\Type and Elastica\Query\Type
+ // do not collide when used together, which at one point
+ // happened because of a use statement in Elastica\Query\Ids
+ // Test goal is to make sure a Fatal Error is not triggered
+ //
+ // adapted fix for Elastica\Filter\Type
+ // see https://github.com/ruflin/Elastica/pull/438
+ $queryType = new Type();
+ $filter = new Ids();
+ }
} | adapted Type namespace collision fix for Query\Ids, see PR #<I> | ruflin_Elastica | train |
5bd3c0d0c45740ff3a35aa0b86d70996310b0580 | diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -39,7 +39,7 @@ exports.plugin = {
const client = await MongoClient.connect(connectionOptions.url, connectionOptions.settings);
const db = await client.db();
const connectionOptionsToLog = Object.assign({}, connectionOptions, {
- url: connectionOptions.url.replace( /mongodb:\/\/([^/]+?):([^@]+)@/, 'mongodb://$1:******@')
+ url: connectionOptions.url.replace( /mongodb(?:\+srv)?:\/\/([^/]+?):([^@]+)@/, 'mongodb://$1:******@')
});
server.log(['hapi-mongodb', 'info'], 'MongoClient connection created for ' + JSON.stringify(connectionOptionsToLog));
diff --git a/test/connection.js b/test/connection.js
index <HASH>..<HASH> 100644
--- a/test/connection.js
+++ b/test/connection.js
@@ -138,6 +138,45 @@ describe('Hapi server', () => {
});
});
+ it('should log configuration upon successful connection, obscurifying DB password for the DNS Seed List Connection Format', async () => {
+
+ let logEntry;
+ server.events.once('log', (entry) => {
+
+ logEntry = entry;
+ });
+
+ const originalConnect = Mongodb.MongoClient.connect;
+ let connected = false;
+ Mongodb.MongoClient.connect = (url, options) => {
+
+ Mongodb.MongoClient.connect = originalConnect;
+ expect(url).to.equal('mongodb+srv://user:[email protected]/admin?replicaSet=api-shard-0&readPreference=primary&connectTimeoutMS=10000&authSource=admin&authMechanism=SCRAM-SHA-1');
+ expect(options).to.equal({ maxPoolSize: 11, useNewUrlParser: true });
+ connected = true;
+ return Promise.resolve({ db: () => 'test-db' });
+ };
+
+ await server.register({
+ plugin: require('../'),
+ options: {
+ url: 'mongodb+srv://user:[email protected]/admin?replicaSet=api-shard-0&readPreference=primary&connectTimeoutMS=10000&authSource=admin&authMechanism=SCRAM-SHA-1',
+ settings: {
+ maxPoolSize: 11,
+ useNewUrlParser: true
+ }
+ }
+ });
+
+ expect(connected).to.be.true();
+ expect(logEntry).to.equal({
+ channel: 'app',
+ timestamp: logEntry.timestamp,
+ tags: ['hapi-mongodb', 'info'],
+ data: 'MongoClient connection created for {"url":"mongodb://user:******@aasdcaasdf.mongodb.net/admin?replicaSet=api-shard-0&readPreference=primary&connectTimeoutMS=10000&authSource=admin&authMechanism=SCRAM-SHA-1","settings":{"maxPoolSize":11,"useNewUrlParser":true}}'
+ });
+ });
+
it('should handle other format of connection string', async () => {
let logEntry; | Adds obfuscation support for the DNS Seed List Connection Format (+srv) | Marsup_hapi-mongodb | train |
ab68086556b5949229fb04b74264e6b8b65af23a | diff --git a/play/speed_tb.py b/play/speed_tb.py
index <HASH>..<HASH> 100644
--- a/play/speed_tb.py
+++ b/play/speed_tb.py
@@ -4,5 +4,4 @@ import sys
b = typedbytes.PairedInput(sys.stdin)
c = typedbytes.PairedOutput(sys.stdout)
-for x in b:
- c.write(x)
+c.writes(b)
diff --git a/play/speed_tbc.py b/play/speed_tbc.py
index <HASH>..<HASH> 100644
--- a/play/speed_tbc.py
+++ b/play/speed_tbc.py
@@ -4,5 +4,4 @@ import sys
b = typedbytes.PairedInput(sys.stdin)
c = typedbytes.PairedOutput(sys.stdout)
-for x in b:
- c.write(x)
+c.writes(b)
diff --git a/play/speedtest.py b/play/speedtest.py
index <HASH>..<HASH> 100644
--- a/play/speedtest.py
+++ b/play/speedtest.py
@@ -12,6 +12,14 @@ def parse_tb(val):
yield x
+def time_script(script_name, data):
+ st = time.time()
+ p = subprocess.Popen(('python %s' % script_name).split(),
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+ o = p.communicate(data)[0]
+ return o, time.time() - st
+
+
def main():
out = []
print('+-----------------+---------+---------+---------+---------+---------+')
@@ -20,34 +28,12 @@ def main():
for fn in sorted(glob.glob('*.tb')):
with open(fn) as fp:
data = fp.read()
- st = time.time()
- p = subprocess.Popen('python speed_hadoopy.py'.split(),
- stdin=subprocess.PIPE, stdout=subprocess.PIPE)
- o0 = p.communicate(data)[0]
- t0 = time.time() - st
- st = time.time()
- p = subprocess.Popen('python speed_hadoopyfp.py'.split(),
- stdin=subprocess.PIPE, stdout=subprocess.PIPE)
- o1 = p.communicate(data)[0]
- t1 = time.time() - st
- st = time.time()
- p = subprocess.Popen('python speed_tb.py'.split(),
- stdin=subprocess.PIPE, stdout=subprocess.PIPE)
- o2 = p.communicate(data)[0]
- t2 = time.time() - st
- p = subprocess.Popen('python speed_tbc.py'.split(),
- stdin=subprocess.PIPE, stdout=subprocess.PIPE)
- o3 = p.communicate(data)[0]
- t3 = time.time() - st
- out.append((fn, t0, t1, t2, t3, min(t2, t3) / t1))
- #print('%s:\tHadoopy[%2.6f] Hadoopyfp[%2.6f] Typedbytes[%2.6f] cTypedbytes[%2.6f]: min(TypedBytes, cTypedBytes) / Hadoopyfp = %f' % (fn, t0, t1, t2, t3, min(t2, t3) / t1))
+ o0, t0 = time_script('speed_hadoopy.py', data)
+ o1, t1 = time_script('speed_hadoopyfp.py', data)
+ o2, t2 = time_script('speed_tb.py', data)
+ o3, t3 = time_script('speed_tbc.py', data)
+ out.append((fn, t0, t1, t2, t3, min([t2, t3]) / t1))
assert(o0 == o1 == o2 == o3)
- #for x, y, z in itertools.izip(parse_tb(o0), parse_tb(o1), parse_tb(o2)):
- # try:
- # assert(x == y == z)
- # except AssertionError, e:
- # print('x:%r\ny:%r\nz:%r' % (x, y, z))
- # raise e
out.sort(lambda x, y: cmp(x[-1], y[-1]), reverse=True)
for x in out:
print('|%17s|%9.6f|%9.6f|%9.6f|%9.6f|%9.6f|' % x) | Cleaned up speed test, updated TypedBytes examples with Klaas's suggestions, this requires my patched cTypedBytes | bwhite_hadoopy | train |
c9e48097ece2f2e3b16c6bb726218c7967af4e8c | diff --git a/gson/src/main/java/com/google/gson/JsonSerializationVisitor.java b/gson/src/main/java/com/google/gson/JsonSerializationVisitor.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/JsonSerializationVisitor.java
+++ b/gson/src/main/java/com/google/gson/JsonSerializationVisitor.java
@@ -142,7 +142,9 @@ final class JsonSerializationVisitor implements ObjectNavigator.Visitor {
Preconditions.checkState(root.isJsonObject());
Object obj = f.get(parent);
if (obj == null) {
- addChildAsElement(f, JsonNull.INSTANCE);
+ if (serializeNulls) {
+ addChildAsElement(f, JsonNull.INSTANCE);
+ }
return true;
}
JsonSerializer serializer = serializers.getHandlerFor(actualTypeOfField);
diff --git a/gson/src/test/java/com/google/gson/functional/NamingPolicyTest.java b/gson/src/test/java/com/google/gson/functional/NamingPolicyTest.java
index <HASH>..<HASH> 100644
--- a/gson/src/test/java/com/google/gson/functional/NamingPolicyTest.java
+++ b/gson/src/test/java/com/google/gson/functional/NamingPolicyTest.java
@@ -18,6 +18,7 @@ package com.google.gson.functional;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import com.google.gson.annotations.SerializedName;
import com.google.gson.common.TestTypes.ClassWithSerializedNameFields;
import com.google.gson.common.TestTypes.StringWrapper;
@@ -69,4 +70,22 @@ public class NamingPolicyTest extends TestCase {
gson.fromJson(expected.getExpectedJson(), ClassWithSerializedNameFields.class);
assertEquals(expected.f, actual.f);
}
+
+ public void testGsonDuplicateNameUsingSerializedNameFieldNamingPolicySerialization() {
+ Gson gson = builder.create();
+ ClassWithDuplicateFields target = new ClassWithDuplicateFields();
+ target.a = 10;
+ String actual = gson.toJson(target);
+ assertEquals("{\"a\":10}", actual);
+
+ target.a = null;
+ target.b = 3.0D;
+ actual = gson.toJson(target);
+ assertEquals("{\"a\":3.0}", actual);
+ }
+
+ private static class ClassWithDuplicateFields {
+ private Integer a;
+ @SerializedName("a") private Double b;
+ }
} | Do not overwrite a duplicate field value during seriailzation if one those fields is null. | google_gson | train |
fa0beb2593237c9ee1c776249d7aaeb0b118709e | diff --git a/tests/Adapters/WebDavConnectorTest.php b/tests/Adapters/WebDavConnectorTest.php
index <HASH>..<HASH> 100644
--- a/tests/Adapters/WebDavConnectorTest.php
+++ b/tests/Adapters/WebDavConnectorTest.php
@@ -33,10 +33,6 @@ class WebDavConnectorTest extends AbstractTestCase
{
public function testConnect()
{
- if (defined('HHVM_VERSION')) {
- return $this->markTestSkipped('WebDav is broken on this version of HHVM.');
- }
-
$connector = $this->getWebDavConnector();
$return = $connector->connect(array( | Allow all tests to run on hhvm | GrahamCampbell_Laravel-Flysystem | train |
6c81f9da0d7f85011e23dd4243ff7b5b6b00189f | diff --git a/agent/consul/config_endpoint.go b/agent/consul/config_endpoint.go
index <HASH>..<HASH> 100644
--- a/agent/consul/config_endpoint.go
+++ b/agent/consul/config_endpoint.go
@@ -256,11 +256,11 @@ func (c *ConfigEntry) ResolveServiceConfig(args *structs.ServiceConfigRequest, r
if !ok {
return fmt.Errorf("invalid proxy config type %T", proxyEntry)
}
+ // Apply the proxy defaults to the sidecar's proxy config
+ reply.ProxyConfig = proxyConf.Config
}
reply.Index = index
- // Apply the proxy defaults to the sidecar's proxy config
- reply.ProxyConfig = proxyConf.Config
if serviceConf != nil && serviceConf.Protocol != "" {
if reply.ProxyConfig == nil {
diff --git a/agent/consul/config_endpoint_test.go b/agent/consul/config_endpoint_test.go
index <HASH>..<HASH> 100644
--- a/agent/consul/config_endpoint_test.go
+++ b/agent/consul/config_endpoint_test.go
@@ -697,6 +697,45 @@ func TestConfigEntry_ResolveServiceConfig(t *testing.T) {
require.Equal(expected, out)
}
+func TestConfigEntry_ResolveServiceConfigNoConfig(t *testing.T) {
+ t.Parallel()
+
+ require := require.New(t)
+
+ dir1, s1 := testServer(t)
+ defer os.RemoveAll(dir1)
+ defer s1.Shutdown()
+ codec := rpcClient(t, s1)
+ defer codec.Close()
+
+ // Don't create any config and make sure we don't nil panic (spoiler alert -
+ // we did in first RC)
+ args := structs.ServiceConfigRequest{
+ Name: "foo",
+ Datacenter: s1.config.Datacenter,
+ Upstreams: []string{"bar", "baz"},
+ }
+ var out structs.ServiceConfigResponse
+ require.NoError(msgpackrpc.CallWithCodec(codec, "ConfigEntry.ResolveServiceConfig", &args, &out))
+ // Hack to fix up the string encoding in the map[string]interface{}.
+ // msgpackRPC's codec doesn't use RawToString.
+ var err error
+ out.ProxyConfig, err = lib.MapWalk(out.ProxyConfig)
+ require.NoError(err)
+ for k := range out.UpstreamConfigs {
+ out.UpstreamConfigs[k], err = lib.MapWalk(out.UpstreamConfigs[k])
+ require.NoError(err)
+ }
+
+ expected := structs.ServiceConfigResponse{
+ ProxyConfig: nil,
+ UpstreamConfigs: nil,
+ // Don't know what this is deterministically
+ QueryMeta: out.QueryMeta,
+ }
+ require.Equal(expected, out)
+}
+
func TestConfigEntry_ResolveServiceConfig_ACLDeny(t *testing.T) {
t.Parallel() | Fix panic in Resolving service config when proxy-defaults isn't defined yet (#<I>) | hashicorp_consul | train |
5c4dba04ab3f408f270c829613fdb0df923e4caf | diff --git a/src/fuzzysearch/levenshtein_ngram.py b/src/fuzzysearch/levenshtein_ngram.py
index <HASH>..<HASH> 100644
--- a/src/fuzzysearch/levenshtein_ngram.py
+++ b/src/fuzzysearch/levenshtein_ngram.py
@@ -11,27 +11,106 @@ def _expand(subsequence, sequence, max_l_dist):
if not subsequence:
return (0, 0)
- scores = list(range(max_l_dist + 1)) + [None] * (len(subsequence) + 1 - (max_l_dist + 1))
- new_scores = [None] * (len(subsequence) + 1)
+ # TODO: review the criterion used
+ if len(subsequence) > max(max_l_dist * 2, 10):
+ return _expand_long(subsequence, sequence, max_l_dist)
+ else:
+ return _expand_short(subsequence, sequence, max_l_dist)
+
+
+def _expand_short(subsequence, sequence, max_l_dist):
+ """Expand a partial match of a Levenstein search.
+
+ An expansion must begin at the beginning of the sequence, which makes
+ this much simpler than a full search, and allows for greater optimization.
+ """
+ subseq_len = len(subsequence)
+
+ scores = list(range(subseq_len + 1))
+ new_scores = [None] * (subseq_len + 1)
min_score = None
min_score_idx = None
for seq_index, char in enumerate(sequence):
new_scores[0] = scores[0] + 1
- for subseq_index in range(0, min(seq_index + max_l_dist, len(subsequence)-1)):
+ for subseq_index in range(0, min(seq_index + max_l_dist, subseq_len-1)):
new_scores[subseq_index + 1] = min(
scores[subseq_index] + (0 if char == subsequence[subseq_index] else 1),
scores[subseq_index + 1] + 1,
new_scores[subseq_index] + 1,
)
- subseq_index = min(seq_index + max_l_dist, len(subsequence) - 1)
+ subseq_index = min(seq_index + max_l_dist, subseq_len - 1)
new_scores[subseq_index + 1] = last_score = min(
scores[subseq_index] + (0 if char == subsequence[subseq_index] else 1),
new_scores[subseq_index] + 1,
)
- if subseq_index == len(subsequence) - 1 and (min_score is None or last_score <= min_score):
+ if subseq_index == subseq_len - 1 and (min_score is None or last_score <= min_score):
+ min_score = last_score
+ min_score_idx = seq_index
+
+ scores, new_scores = new_scores, scores
+
+ return (min_score, min_score_idx + 1) if min_score is not None and min_score <= max_l_dist else (None, None)
+
+
+def _expand_long(subsequence, sequence, max_l_dist):
+ subseq_len = len(subsequence)
+
+ scores = list(range(subseq_len + 1))
+ new_scores = [None] * (subseq_len + 1)
+
+ min_score = None
+ min_score_idx = None
+ max_good_score = max_l_dist
+ first_good_score_idx = 0
+ last_good_score_idx = subseq_len - 1
+
+ for seq_index, char in enumerate(sequence):
+ needle_idx_range = (
+ max(0, first_good_score_idx - 1),
+ min(subseq_len - 1, last_good_score_idx),
+ )
+
+ new_scores[0] = scores[0] + 1
+ if new_scores[0] <= max_good_score:
+ first_good_score_idx = 0
+ last_good_score_idx = 0
+ else:
+ first_good_score_idx = None
+ last_good_score_idx = -1
+
+ for subseq_index in range(*needle_idx_range):
+ score = new_scores[subseq_index + 1] = min(
+ scores[subseq_index] + (0 if char == subsequence[subseq_index] else 1),
+ scores[subseq_index + 1] + 1,
+ new_scores[subseq_index] + 1,
+ )
+ if score <= max_good_score:
+ if first_good_score_idx is None:
+ first_good_score_idx = subseq_index + 1
+ last_good_score_idx = max(
+ last_good_score_idx,
+ subseq_index + 1 + (max_good_score - score),
+ )
+
+ subseq_index = needle_idx_range[1]
+ new_scores[subseq_index + 1] = last_score = min(
+ scores[subseq_index] + (0 if char == subsequence[subseq_index] else 1),
+ new_scores[subseq_index] + 1,
+ )
+ if last_score <= max_good_score:
+ if first_good_score_idx is None:
+ first_good_score_idx = subseq_index + 1
+ last_good_score_idx = subseq_index + 1
+
+ if first_good_score_idx is None:
+ break
+
+ if subseq_index == subseq_len - 1 and (min_score is None or last_score <= min_score):
min_score = last_score
min_score_idx = seq_index
+ if min_score < max_good_score:
+ max_good_score = min_score
scores, new_scores = new_scores, scores | optimize Levenshtein _expand() for long subsequences | taleinat_fuzzysearch | train |
262c8dd61be2c1ca4e0e40e803cd11acc99429d8 | diff --git a/.scrutinizer.yml b/.scrutinizer.yml
index <HASH>..<HASH> 100644
--- a/.scrutinizer.yml
+++ b/.scrutinizer.yml
@@ -1,4 +1,8 @@
checks:
php:
excluded_dependencies:
- - atoum/atoum
\ No newline at end of file
+ - atoum/atoum
+
+tools:
+ php_cs_fixer:
+ config: { level: psr2 }
diff --git a/Tests/Units/EntityRepository.php b/Tests/Units/EntityRepository.php
index <HASH>..<HASH> 100644
--- a/Tests/Units/EntityRepository.php
+++ b/Tests/Units/EntityRepository.php
@@ -126,7 +126,6 @@ class EntityRepository extends atoum
/**
* testFindWithCache
*
- * @param mixed $method
* @access public
* @return void
*/
diff --git a/Tests/Units/Mapping.php b/Tests/Units/Mapping.php
index <HASH>..<HASH> 100644
--- a/Tests/Units/Mapping.php
+++ b/Tests/Units/Mapping.php
@@ -209,7 +209,7 @@ class Mapping extends atoum
* getMappingArray
*
* @access private
- * @return void
+ * @return ClassMetadata[]
*/
private function getMappingArray()
{
diff --git a/Tests/Units/Model/Serializer.php b/Tests/Units/Model/Serializer.php
index <HASH>..<HASH> 100644
--- a/Tests/Units/Model/Serializer.php
+++ b/Tests/Units/Model/Serializer.php
@@ -682,6 +682,9 @@ class Serializer extends atoum
return $mapping;
}
+ /**
+ * @param string $idKey
+ */
private function getProductMetadata($idKey)
{
$productMetadata = new ClassMetadata(
@@ -699,6 +702,9 @@ class Serializer extends atoum
return $productMetadata;
}
+ /**
+ * @param string $idKey
+ */
private function getCartItemDetailMetadata($idKey)
{
$cartItemDetailMetadata = new ClassMetadata(
@@ -719,6 +725,9 @@ class Serializer extends atoum
return $cartItemDetailMetadata;
}
+ /**
+ * @param string $idKey
+ */
private function getCartItemMetadata($idKey)
{
$cartItemMetadata = new ClassMetadata(
@@ -745,6 +754,9 @@ class Serializer extends atoum
return $cartItemMetadata;
}
+ /**
+ * @param string $idKey
+ */
private function getCartMetadata($idKey)
{
$cartMetadata = new ClassMetadata(
@@ -772,7 +784,7 @@ class Serializer extends atoum
* createNewCart
*
* @access private
- * @return AbstractModel
+ * @return \Mapado\RestClientSdk\Tests\Model\Cart
*/
private function createNewCart()
{
@@ -791,7 +803,7 @@ class Serializer extends atoum
* createCart
*
* @access private
- * @return void
+ * @return \Mapado\RestClientSdk\Tests\Model\Cart
*/
private function createCart()
{
@@ -805,7 +817,7 @@ class Serializer extends atoum
* createKnownCartItem
*
* @access private
- * @return AbstractModel
+ * @return \Mapado\RestClientSdk\Tests\Model\CartItem
*/
private function createKnownCartItem()
{
@@ -826,7 +838,7 @@ class Serializer extends atoum
* createNewCartItem
*
* @access private
- * @return AbstractModel
+ * @return \Mapado\RestClientSdk\Tests\Model\CartItem
*/
private function createNewCartItem($addKnownedProduct = true)
{
@@ -849,7 +861,7 @@ class Serializer extends atoum
* createNewProduct
*
* @access private
- * @return AbstractModel
+ * @return \Mapado\RestClientSdk\Tests\Model\Product
*/
private function createNewProduct()
{
@@ -866,7 +878,7 @@ class Serializer extends atoum
* createKnownedProduct
*
* @access private
- * @return AbstractModel
+ * @return \Mapado\RestClientSdk\Tests\Model\Product
*/
private function createKnownedProduct()
{
@@ -889,6 +901,7 @@ class Serializer extends atoum
* createNewInstance
*
* @access private
+ * @param Mapping $mapping
* @return void
*/
private function createNewInstance($mapping = null)
@@ -917,6 +930,9 @@ class Serializer extends atoum
$this->testedInstance->setSdk($sdk);
}
+ /**
+ * @param string $modelName
+ */
private function getCartRepositoryMock($sdk, $restClient, $modelName)
{
$repository = new \mock\Mapado\RestClientSdk\EntityRepository(
diff --git a/src/EntityRepository.php b/src/EntityRepository.php
index <HASH>..<HASH> 100644
--- a/src/EntityRepository.php
+++ b/src/EntityRepository.php
@@ -3,7 +3,6 @@
namespace Mapado\RestClientSdk;
use Mapado\RestClientSdk\Exception\SdkException;
-use Symfony\Component\Cache\CacheItem;
class EntityRepository
{ | PHP CS Fixer in scrutinizer (#<I>)
* PHP CS Fixer in scrutinizer
* Scrutinizer Auto-Fixes | mapado_rest-client-sdk | train |
ab79b2426370f0422e9428d5cd25ba33f3ebb47f | diff --git a/src/main/java/reactor/core/publisher/FluxFlattenIterable.java b/src/main/java/reactor/core/publisher/FluxFlattenIterable.java
index <HASH>..<HASH> 100644
--- a/src/main/java/reactor/core/publisher/FluxFlattenIterable.java
+++ b/src/main/java/reactor/core/publisher/FluxFlattenIterable.java
@@ -627,7 +627,7 @@ final class FluxFlattenIterable<T, R> extends FluxSource<T, R> implements Fuseab
public boolean isEmpty() {
Iterator<? extends R> it = current;
if (it != null) {
- return it.hasNext();
+ return !it.hasNext();
}
return queue.isEmpty(); // estimate
}
diff --git a/src/test/java/reactor/core/publisher/FluxFlattenIterableTest.java b/src/test/java/reactor/core/publisher/FluxFlattenIterableTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/reactor/core/publisher/FluxFlattenIterableTest.java
+++ b/src/test/java/reactor/core/publisher/FluxFlattenIterableTest.java
@@ -313,4 +313,18 @@ public class FluxFlattenIterableTest extends FluxOperatorTest<String, String> {
.verifyComplete();
}
+ /**
+ * See https://github.com/reactor/reactor-core/issues/508
+ */
+ @Test
+ public void testPublishingTwice() {
+ StepVerifier.create(Flux.just(Flux.range(0, 300).toIterable(), Flux.range(0, 300).toIterable())
+ .flatMapIterable(x -> x)
+ .share()
+ .share()
+ .count())
+ .expectNext(600L)
+ .verifyComplete();
+ }
+
} | Fix #<I> FlattenIterableSubscriber.isEmpty check (#<I>)
- returned true from isEmpty when iterator had more elements | reactor_reactor-core | train |
9f87fb9d998a448b0efa90e4c5f7379feaf8236f | diff --git a/modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/AbstractMessageContentBuilder.java b/modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/AbstractMessageContentBuilder.java
index <HASH>..<HASH> 100644
--- a/modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/AbstractMessageContentBuilder.java
+++ b/modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/AbstractMessageContentBuilder.java
@@ -62,16 +62,6 @@ public abstract class AbstractMessageContentBuilder implements MessageContentBui
private List<MessageConstructionInterceptor> messageInterceptors = new ArrayList<>();
/**
- * Constructs the control message without any specific direction inbound or outbound.
- * @param context
- * @param messageType
- * @return
- */
- public Message buildMessageContent(final TestContext context, final String messageType) {
- return buildMessageContent(context, messageType, MessageDirection.UNBOUND);
- }
-
- /**
* Constructs the control message with headers and payload coming from
* subclass implementation.
*/
diff --git a/modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/MessageContentBuilder.java b/modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/MessageContentBuilder.java
index <HASH>..<HASH> 100644
--- a/modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/MessageContentBuilder.java
+++ b/modules/citrus-core/src/main/java/com/consol/citrus/validation/builder/MessageContentBuilder.java
@@ -39,6 +39,18 @@ public interface MessageContentBuilder {
Message buildMessageContent(TestContext context, String messageType, MessageDirection direction);
/**
+ * Builds the control message.
+ * @param context the current test context.
+ * @param messageType the message type to build.
+ * @return the constructed message object.
+ * @deprecated in favor of using {@link #buildMessageContent(TestContext, String, MessageDirection)}.
+ */
+ @Deprecated
+ default Message buildMessageContent(TestContext context, String messageType){
+ return buildMessageContent(context, messageType, MessageDirection.UNBOUND);
+ }
+
+ /**
* Adds a message construction interceptor.
* @param interceptor
*/
diff --git a/modules/citrus-http/src/main/java/com/consol/citrus/http/message/HttpMessageContentBuilder.java b/modules/citrus-http/src/main/java/com/consol/citrus/http/message/HttpMessageContentBuilder.java
index <HASH>..<HASH> 100644
--- a/modules/citrus-http/src/main/java/com/consol/citrus/http/message/HttpMessageContentBuilder.java
+++ b/modules/citrus-http/src/main/java/com/consol/citrus/http/message/HttpMessageContentBuilder.java
@@ -44,11 +44,6 @@ public class HttpMessageContentBuilder extends AbstractMessageContentBuilder {
}
@Override
- public Message buildMessageContent(final TestContext context, final String messageType) {
- return buildMessageContent(context, messageType, MessageDirection.UNBOUND);
- }
-
- @Override
public Message buildMessageContent(final TestContext context, final String messageType, final MessageDirection direction) {
//Copy the initial message, so that it is not manipulated during the test.
final HttpMessage message = new HttpMessage(template);
diff --git a/src/manual/changes-new.adoc b/src/manual/changes-new.adoc
index <HASH>..<HASH> 100644
--- a/src/manual/changes-new.adoc
+++ b/src/manual/changes-new.adoc
@@ -19,6 +19,7 @@ with minor versions. Because of that, we've reviewed the public API from release
the removed/changed methods to ease the migration to newer Citrus versions. All methods that have been added back for
downwards compatibility are marked as `@Deprecated` and will be removed with the next major release.
+* https://github.com/citrusframework/citrus/issues/552[#552 - Breaking change in MessageContentBuilder.buildMessageContent() public API]
* https://github.com/citrusframework/citrus/issues/547[#547 - Breaking change in waitFor().http() public API]
* https://github.com/citrusframework/citrus/issues/551[#551 - Breaking change in selenium().browser().type() public API] | (#<I>) added back original method signature to prevent a breaking change | citrusframework_citrus | train |
47731a11662b471a8eeae358b4bf3d6d0d8ea868 | diff --git a/test/runner/runner.go b/test/runner/runner.go
index <HASH>..<HASH> 100644
--- a/test/runner/runner.go
+++ b/test/runner/runner.go
@@ -79,6 +79,9 @@ type Build struct {
}
func (b *Build) URL() string {
+ if listenPort != "" && listenPort != "443" {
+ return "https://ci.flynn.io:" + listenPort + "/builds/" + b.ID
+ }
return "https://ci.flynn.io/builds/" + b.ID
} | test: include custom port on CI links | flynn_flynn | train |
6b7f1717e94238206fe9a7557baed3590df572ed | diff --git a/admin/webservice/service_users.php b/admin/webservice/service_users.php
index <HASH>..<HASH> 100644
--- a/admin/webservice/service_users.php
+++ b/admin/webservice/service_users.php
@@ -98,7 +98,7 @@ $usersmissingcaps = $webservicemanager->get_missing_capabilities_by_users($allow
//add the missing capabilities to the allowed users object to be displayed by renderer
foreach ($allowedusers as &$alloweduser) {
if (!is_siteadmin($alloweduser->id) and key_exists($alloweduser->id, $usersmissingcaps)) {
- $alloweduser->missingcapabilities = implode(',', $usersmissingcaps[$alloweduser->id]);
+ $alloweduser->missingcapabilities = implode(', ', $usersmissingcaps[$alloweduser->id]);
}
}
diff --git a/lib/adminlib.php b/lib/adminlib.php
index <HASH>..<HASH> 100644
--- a/lib/adminlib.php
+++ b/lib/adminlib.php
@@ -7575,7 +7575,7 @@ class admin_setting_managewebservicetokens extends admin_setting {
if (!is_siteadmin($token->userid) and
key_exists($token->userid, $usermissingcaps)) {
- $missingcapabilities = implode(',',
+ $missingcapabilities = implode(', ',
$usermissingcaps[$token->userid]);
if (!empty($missingcapabilities)) {
$useratag .= html_writer::tag('div', | MDL-<I> Fix capabilities displayed without spaces causing text going out of the screen | moodle_moodle | train |
92a55eb686a116cdf423afc87f60bd3108b08b6b | diff --git a/java-translate/samples/snippets/src/test/java/com/example/translate/QuickstartSampleIT.java b/java-translate/samples/snippets/src/test/java/com/example/translate/QuickstartSampleIT.java
index <HASH>..<HASH> 100644
--- a/java-translate/samples/snippets/src/test/java/com/example/translate/QuickstartSampleIT.java
+++ b/java-translate/samples/snippets/src/test/java/com/example/translate/QuickstartSampleIT.java
@@ -59,4 +59,3 @@ public class QuickstartSampleIT {
assertThat(got).contains("Translation: ");
}
}
-// [END datastore_quickstart] | samples: Add NL quickstart sample. Fix some other quickstarts. (#<I>) | googleapis_google-cloud-java | train |
f08266080129568a2d1324d39ebe451ec2359483 | diff --git a/test/cmd/lfstest-gitserver.go b/test/cmd/lfstest-gitserver.go
index <HASH>..<HASH> 100644
--- a/test/cmd/lfstest-gitserver.go
+++ b/test/cmd/lfstest-gitserver.go
@@ -450,7 +450,7 @@ func storageHandler(w http.ResponseWriter, r *http.Request) {
if match != nil && len(match) > 1 {
statusCode = 206
resumeAt, _ = strconv.ParseInt(match[1], 10, 32)
- w.Header().Set("Content-Range", fmt.Sprintf("bytes=%d-%d", resumeAt, len(by)))
+ w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", resumeAt, len(by), resumeAt-int64(len(by))))
}
} else {
byteLimit = 10
diff --git a/transfer/basic_download.go b/transfer/basic_download.go
index <HASH>..<HASH> 100644
--- a/transfer/basic_download.go
+++ b/transfer/basic_download.go
@@ -126,7 +126,7 @@ func (a *basicDownloadAdapter) download(t *Transfer, cb TransferProgressCallback
if res.StatusCode == 206 {
// Probably a successful range request, check Content-Range
if rangeHdr := res.Header.Get("Content-Range"); rangeHdr != "" {
- regex := regexp.MustCompile(`bytes=(\d+)\-.*`)
+ regex := regexp.MustCompile(`bytes (\d+)\-.*`)
match := regex.FindStringSubmatch(rangeHdr)
if match != nil && len(match) > 1 {
contentStart, _ := strconv.ParseInt(match[1], 10, 32) | Fix Content-Range parsing, slightly different format to Range | git-lfs_git-lfs | train |
1273ffa1861d15eb7518b7bfab6003bb3d9ca347 | diff --git a/actionpack/lib/action_controller/abstract/layouts.rb b/actionpack/lib/action_controller/abstract/layouts.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/action_controller/abstract/layouts.rb
+++ b/actionpack/lib/action_controller/abstract/layouts.rb
@@ -6,6 +6,7 @@ module AbstractController
included do
extlib_inheritable_accessor(:_layout_conditions) { Hash.new }
+ _write_layout_method
end
module ClassMethods | Fix AbstractController::Layouts to work when included directly on a controller | rails_rails | train |
e58400683c9542af5031e49675fd5ac08031ddad | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -4,7 +4,7 @@ from os import path
from distutils.version import LooseVersion
from setuptools import find_packages, setup
-VERSION = '1.20.1'
+VERSION = '1.20.2'
# Import README.md into long_description
pwd = path.abspath(path.dirname(__file__)) | Bump package version to <I> | instana_python-sensor | train |
bb87c1436aa49724f8c9465c8756186067129b63 | diff --git a/UI/src/com/kotcrab/vis/ui/util/OsUtils.java b/UI/src/com/kotcrab/vis/ui/util/OsUtils.java
index <HASH>..<HASH> 100644
--- a/UI/src/com/kotcrab/vis/ui/util/OsUtils.java
+++ b/UI/src/com/kotcrab/vis/ui/util/OsUtils.java
@@ -72,24 +72,33 @@ public class OsUtils {
* Creates platform dependant shortcut text. Converts int keycodes to String text. Eg. Keys.CONTROL_LEFT,
* Keys.SHIFT_LEFT, Keys.F5 will be converted to Ctrl+Shift+F5 on Windows and Linux, and to ⌘⇧F5 on Mac.
* <p>
- * CONTROL_LEFT and CONTROL_RIGHT are mapped to Ctrl. The same goes for Alt (ALT_LEFT, ALT_RIGHT) and Shift (SHIFT_LEFT, SHIFT_RIGHT).
+ * CONTROL_LEFT and CONTROL_RIGHT and SYM are mapped to Ctrl. The same goes for Alt (ALT_LEFT, ALT_RIGHT) and Shift (SHIFT_LEFT, SHIFT_RIGHT).
+ * <p>
+ * Keycodes equal to {@link Integer#MIN_VALUE} will be ignored.
* @param keycodes keycodes from {@link Keys} that are used to create shortcut text
* @return the platform dependent shortcut text
*/
public static String getShortcutFor (int... keycodes) {
StringBuilder builder = new StringBuilder();
+
String separatorString = "+";
String ctrlKey = "Ctrl";
String altKey = "Alt";
String shiftKey = "Shift";
+
if (OsUtils.isMac()) {
separatorString = "";
ctrlKey = "\u2318";
altKey = "\u2325";
shiftKey = "\u21E7";
}
+
for (int i = 0; i < keycodes.length; i++) {
- if (keycodes[i] == Keys.CONTROL_LEFT || keycodes[i] == Keys.CONTROL_RIGHT) {
+ if (keycodes[i] == Integer.MIN_VALUE) {
+ continue;
+ }
+
+ if (keycodes[i] == Keys.CONTROL_LEFT || keycodes[i] == Keys.CONTROL_RIGHT || keycodes[i] == Keys.SYM) {
builder.append(ctrlKey);
} else if (keycodes[i] == Keys.SHIFT_LEFT || keycodes[i] == Keys.SHIFT_RIGHT) {
builder.append(shiftKey);
@@ -103,6 +112,7 @@ public class OsUtils {
builder.append(separatorString);
}
}
+
return builder.toString();
} | Add SYM to control mapping, ignore min_value keycodes | kotcrab_vis-ui | train |
70460a1cc6e433fe883bb0f74df67a3394b321d3 | diff --git a/api/app/util.go b/api/app/util.go
index <HASH>..<HASH> 100644
--- a/api/app/util.go
+++ b/api/app/util.go
@@ -2,6 +2,7 @@ package app
import (
"bytes"
+ "fmt"
"regexp"
)
@@ -39,3 +40,22 @@ func filterOutput(output []byte, filterFunc func([]byte) bool) []byte {
}
return bytes.Join(result, []byte{'\n'})
}
+
+// newUUID generates an uuid.
+func newUUID() (string, error) {
+ f, err := filesystem().Open("/dev/urandom")
+ if err != nil {
+ return "", err
+ }
+ b := make([]byte, 16)
+ _, err = f.Read(b)
+ if err != nil {
+ return "", err
+ }
+ err = f.Close()
+ if err != nil {
+ return "", err
+ }
+ uuid := fmt.Sprintf("%x", b)
+ return uuid, nil
+}
diff --git a/api/app/util_test.go b/api/app/util_test.go
index <HASH>..<HASH> 100644
--- a/api/app/util_test.go
+++ b/api/app/util_test.go
@@ -2,6 +2,7 @@ package app
import (
"bytes"
+ "github.com/timeredbull/tsuru/fs/testing"
. "launchpad.net/gocheck"
)
@@ -85,3 +86,15 @@ nameserver 192.168.1.1`)
got := filterOutput(output, f)
c.Assert(string(got), Equals, string(expected))
}
+
+func (s *S) TestnewUUID(c *C) {
+ rfs := &testing.RecordingFs{FileContent: string([]byte{16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31})}
+ fsystem = rfs
+ defer func() {
+ fsystem = s.rfs
+ }()
+ uuid, err := newUUID()
+ c.Assert(err, IsNil)
+ expected := "101112131415161718191a1b1c1d1e1f"
+ c.Assert(uuid, Equals, expected)
+} | added method to generate an uuid | tsuru_tsuru | train |
4f4a2f0469baa3cde12287d35a6a84f5145030d2 | diff --git a/lib/eye/application.rb b/lib/eye/application.rb
index <HASH>..<HASH> 100644
--- a/lib/eye/application.rb
+++ b/lib/eye/application.rb
@@ -32,4 +32,8 @@ class Eye::Application
end
end
+ def alive?
+ true # emulate celluloid actor method
+ end
+
end
\ No newline at end of file
diff --git a/lib/eye/controller/commands.rb b/lib/eye/controller/commands.rb
index <HASH>..<HASH> 100644
--- a/lib/eye/controller/commands.rb
+++ b/lib/eye/controller/commands.rb
@@ -28,6 +28,8 @@ module Eye::Controller::Commands
res = "[#{objs.map{|obj| obj.name }.join(", ")}]"
objs.each do |obj|
+ next unless obj.alive?
+
obj.send_command(command)
if command == :remove
diff --git a/spec/controller/intergration_spec.rb b/spec/controller/intergration_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/controller/intergration_spec.rb
+++ b/spec/controller/intergration_spec.rb
@@ -265,6 +265,31 @@ S
actors.should_not include(Eye::Application)
actors.should_not include(Eye::Checker::Memory)
end
+
+ it "remove by mask" do
+ @old_pid1 = @p1.pid
+ @old_pid2 = @p2.pid
+ @old_pid3 = @p3.pid
+
+ @c.send_command(:remove, "sam*").should == "[samples, sample1, sample2]"
+ sleep 7 # while
+
+ @c.all_processes.should == [@p3]
+ @c.all_groups.map(&:name).should == ['__default__']
+
+ Eye::System.pid_alive?(@old_pid1).should == true
+ Eye::System.pid_alive?(@old_pid2).should == true
+ Eye::System.pid_alive?(@old_pid3).should == true
+
+ Eye::System.send_signal(@old_pid1)
+ sleep 0.5
+ Eye::System.pid_alive?(@old_pid1).should == false
+
+ # noone up this
+ sleep 2
+ Eye::System.pid_alive?(@old_pid1).should == false
+ end
+
end
end
\ No newline at end of file | # fix remove subojects, which was already died | kostya_eye | train |
0b132bcb42f2e5ca5da1769e51a7eba01820c83d | diff --git a/tests/test_examples.py b/tests/test_examples.py
index <HASH>..<HASH> 100755
--- a/tests/test_examples.py
+++ b/tests/test_examples.py
@@ -38,7 +38,8 @@ class TestExamples(unittest.TestCase):
self.assertTrue(os.path.isfile('cookiecutter-pypackage/alotofeffort/README.rst'))
def tearDown(self):
- shutil.rmtree('cookiecutter-pypackage')
+ if os.path.isdir('cookiecutter-pypackage'):
+ shutil.rmtree('cookiecutter-pypackage')
if __name__ == '__main__':
unittest.main()
diff --git a/tests/test_find.py b/tests/test_find.py
index <HASH>..<HASH> 100755
--- a/tests/test_find.py
+++ b/tests/test_find.py
@@ -23,7 +23,9 @@ class TestFind(unittest.TestCase):
self.assertEqual(template, '{{project.repo_name}}')
self.assertNotEqual(template, '{{project.repo_name }}')
self.assertNotEqual(template, '{{ project.repo_name }}')
- shutil.rmtree('cookiecutter-pypackage')
+
+ if os.path.isdir('cookiecutter-pypackage'):
+ shutil.rmtree('cookiecutter-pypackage')
if __name__ == '__main__':
unittest.main()
diff --git a/tests/test_vcs.py b/tests/test_vcs.py
index <HASH>..<HASH> 100755
--- a/tests/test_vcs.py
+++ b/tests/test_vcs.py
@@ -20,7 +20,8 @@ class TestVCS(unittest.TestCase):
def test_git_clone(self):
vcs.git_clone('https://github.com/audreyr/cookiecutter-pypackage.git')
self.assertTrue(os.path.isfile('cookiecutter-pypackage/README.rst'))
- shutil.rmtree('cookiecutter-pypackage')
+ if os.path.isdir('cookiecutter-pypackage'):
+ shutil.rmtree('cookiecutter-pypackage')
if __name__ == '__main__':
unittest.main() | Safer rmtree - check with isdir first. | audreyr_cookiecutter | train |
9613703b8f4d0b96d87f9af0c213b805a0c4cace | diff --git a/lxd/daemon.go b/lxd/daemon.go
index <HASH>..<HASH> 100644
--- a/lxd/daemon.go
+++ b/lxd/daemon.go
@@ -14,9 +14,9 @@ import (
"strconv"
"strings"
- "github.com/coreos/go-systemd/activation"
"github.com/gorilla/mux"
_ "github.com/mattn/go-sqlite3"
+ "github.com/stgraber/lxd-go-systemd/activation"
"gopkg.in/tomb.v2"
"github.com/lxc/lxd" | Update to use Go <I>-compatible fork of go-systemd
The unsetEnv feature of the activation code in go-systemd requires
os.Unsetenv which doesn't exist until Go <I>.
As we're currently relying on Go <I>, I made a fork of go-systemd in
stgraber/lxd-go-systemd which has that codepath commented out (we don't
use it) and changed to print a message if someone was to use it. | lxc_lxd | train |
ab5d407a03192bd8ab63a1bfc891db9c04330265 | diff --git a/tests/test_asyncio/test_timeseries.py b/tests/test_asyncio/test_timeseries.py
index <HASH>..<HASH> 100644
--- a/tests/test_asyncio/test_timeseries.py
+++ b/tests/test_asyncio/test_timeseries.py
@@ -240,6 +240,9 @@ async def test_range_advanced(modclient: redis.Redis):
assert [(0, 5.0), (5, 6.0)] == await modclient.ts().range(
1, 0, 10, aggregation_type="count", bucket_size_msec=10, align=5
)
+ assert [(0, 2.5500000000000003), (10, 3.0)] == await modclient.ts().range(
+ 1, 0, 10, aggregation_type="twa", bucket_size_msec=10
+ )
@pytest.mark.redismod
diff --git a/tests/test_timeseries.py b/tests/test_timeseries.py
index <HASH>..<HASH> 100644
--- a/tests/test_timeseries.py
+++ b/tests/test_timeseries.py
@@ -233,7 +233,7 @@ def test_range_advanced(client):
assert [(0, 5.0), (5, 6.0)] == client.ts().range(
1, 0, 10, aggregation_type="count", bucket_size_msec=10, align=5
)
- assert [(0, 2.5500000000000003), (10, 3.95)] == client.ts().range(
+ assert [(0, 2.5500000000000003), (10, 3.0)] == client.ts().range(
1, 0, 10, aggregation_type="twa", bucket_size_msec=10
) | fix test (#<I>) | andymccurdy_redis-py | train |
6dbcfa78d84fb51f46ebe0d50bf4d18beebb9931 | diff --git a/build_tools/build_binaries_windows.py b/build_tools/build_binaries_windows.py
index <HASH>..<HASH> 100644
--- a/build_tools/build_binaries_windows.py
+++ b/build_tools/build_binaries_windows.py
@@ -116,17 +116,17 @@ miniconda32_envs = os.getenv('MINICONDA32_ENVS', r'C:\tools\Miniconda32\envs')
miniconda64_envs = os.getenv('MINICONDA64_ENVS', r'C:\tools\Miniconda\envs')
python_installations = [
- r'%s\py27_32\Scripts\python.exe' % miniconda32_envs,
- r'%s\py34_32\Scripts\python.exe' % miniconda32_envs,
- r'%s\py35_32\Scripts\python.exe' % miniconda32_envs,
- r'%s\py36_32\Scripts\python.exe' % miniconda32_envs,
- r'%s\py37_32\Scripts\python.exe' % miniconda32_envs,
-
- r'%s\py27_64\Scripts\python.exe' % miniconda64_envs,
- r'%s\py34_64\Scripts\python.exe' % miniconda64_envs,
- r'%s\py35_64\Scripts\python.exe' % miniconda64_envs,
- r'%s\py36_64\Scripts\python.exe' % miniconda64_envs,
- r'%s\py37_64\Scripts\python.exe' % miniconda64_envs,
+ r'%s\py27_32\python.exe' % miniconda32_envs,
+ r'%s\py34_32\python.exe' % miniconda32_envs,
+ r'%s\py35_32\python.exe' % miniconda32_envs,
+ r'%s\py36_32\python.exe' % miniconda32_envs,
+ r'%s\py37_32\python.exe' % miniconda32_envs,
+
+ r'%s\py27_64\python.exe' % miniconda64_envs,
+ r'%s\py34_64\python.exe' % miniconda64_envs,
+ r'%s\py35_64\python.exe' % miniconda64_envs,
+ r'%s\py36_64\python.exe' % miniconda64_envs,
+ r'%s\py37_64\python.exe' % miniconda64_envs,
]
root_dir = os.path.dirname(os.path.dirname(__file__))
@@ -139,7 +139,7 @@ def list_binaries():
def extract_version(python_install):
- return python_install.split('\\')[-3][2:]
+ return python_install.split('\\')[-2][2:]
def main(): | Use proper path for conda envs. | fabioz_PyDev.Debugger | train |
87e5fe39bd7f9ec7145bd1376668b396aa708189 | diff --git a/build/jspicl.js b/build/jspicl.js
index <HASH>..<HASH> 100644
--- a/build/jspicl.js
+++ b/build/jspicl.js
@@ -283,9 +283,12 @@ const generalPolyfills = {
const arrayPolyfills = {
forEach: (context, args) => `foreach(${context}, ${args})`,
push: (context, args) => `add(${context}, ${args})`,
- join: (context, args) => `join(${context}, ${args})`
+ join: (context, args) => `join(${context}, ${args})`,
+ map: (context, args) => `map(${context}, ${args})`,
+ includes: (context, arg) => `includes(${context}, ${arg})`
};
+// TODO: The polyfills should have a prefix to avoid name clashing
const polyfills = `
function merge(sources)
local target = sources[1]
@@ -310,6 +313,15 @@ function join(table, separator)
return result
end
+
+function includes(arr, value)
+ for i = 1, #arr do
+ if arr[i] == value then
+ return true
+ end
+ end
+ return false
+end
`;
function transpile (node, { arraySeparator = "\n" } = {}) {
diff --git a/package-lock.json b/package-lock.json
index <HASH>..<HASH> 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,6 +1,6 @@
{
"name": "jspicl",
- "version": "0.4.1",
+ "version": "0.4.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
diff --git a/src/constants.js b/src/constants.js
index <HASH>..<HASH> 100644
--- a/src/constants.js
+++ b/src/constants.js
@@ -20,9 +20,11 @@ export const arrayPolyfills = {
forEach: (context, args) => `foreach(${context}, ${args})`,
push: (context, args) => `add(${context}, ${args})`,
join: (context, args) => `join(${context}, ${args})`,
- map: (context, args) => `map(${context}, ${args})`
+ map: (context, args) => `map(${context}, ${args})`,
+ includes: (context, arg) => `includes(${context}, ${arg})`
};
+// TODO: The polyfills should have a prefix to avoid name clashing
export const polyfills = `
function merge(sources)
local target = sources[1]
@@ -47,6 +49,14 @@ function join(table, separator)
return result
end
+function includes(arr, value)
+ for i = 1, #arr do
+ if arr[i] == value then
+ return true
+ end
+ end
+ return false
+end
function map(table, args)
local result = {}
for value in all(table) do | Add polyfill for Array.includes
* Add polyfill for Array.includes
Fixes #<I> | AgronKabashi_jspicl | train |
a5585434208ee9effec0579f4f42d8949a34765b | diff --git a/rootpy/stats/histfactory/histfactory.py b/rootpy/stats/histfactory/histfactory.py
index <HASH>..<HASH> 100644
--- a/rootpy/stats/histfactory/histfactory.py
+++ b/rootpy/stats/histfactory/histfactory.py
@@ -222,6 +222,26 @@ class Sample(_SampleBase, QROOT.RooStats.HistFactory.Sample):
hsys = self.GetHistoSys(name)
yield name, osys, hsys
+ def sys_hist(self, name):
+ """
+ Return the effective low and high histogram for a given systematic.
+ If this sample does not contain the named systematic then return
+ the nominal histogram for both low and high variations.
+ """
+ osys = self.GetOverallSys(name)
+ hsys = self.GetHistoSys(name)
+ if osys is None:
+ osys_high, osys_low = 1., 1.
+ else:
+ osys_high, osys_low = osys.high, osys.low
+ if hsys is None:
+ hsys_high = self.hist.Clone(shallow=True)
+ hsys_low = self.hist.Clone(shallow=True)
+ else:
+ hsys_high = hsys.high.Clone(shallow=True)
+ hsys_low = hsys.low.Clone(shallow=True)
+ return hsys_low * osys_low, hsys_high * osys_high
+
###########################
# HistoSys
###########################
@@ -694,6 +714,18 @@ class Channel(_Named, QROOT.RooStats.HistFactory.Channel):
"unsupported operand type(s) for +: '{0}' and '{1}'".format(
other.__class__.__name__, self.__class__.__name__))
+ def sys_names():
+ """
+ Return a list of unique systematic names from OverallSys and HistoSys
+ """
+ names = {}
+ for sample in self.samples:
+ for osys in sample.overall_sys:
+ names[osys.name] = None
+ for hsys in sample.histo_sys:
+ names[hsys.name] = None
+ return names.keys()
+
def SetData(self, data):
super(Channel, self).SetData(data)
if isinstance(data, ROOT.TH1): | histfactory: add sys_names for Channel and add sys_hist for Sample | rootpy_rootpy | train |
07b61c575f047c4bcb19fd5bb6ae1a5bacf7a67f | diff --git a/pythonforandroid/toolchain.py b/pythonforandroid/toolchain.py
index <HASH>..<HASH> 100755
--- a/pythonforandroid/toolchain.py
+++ b/pythonforandroid/toolchain.py
@@ -1564,15 +1564,30 @@ class Recipe(object):
# print("Unrecognized extension for {}".format(filename))
# raise Exception()
- def apply_patch(self, filename):
+ def apply_patch(self, filename, arch='armeabi'):
"""
Apply a patch from the current recipe directory into the current
build directory.
"""
info("Applying patch {}".format(filename))
filename = join(self.recipe_dir, filename)
- # AND: get_build_dir shouldn't need to hardcode armeabi
- sh.patch("-t", "-d", self.get_build_dir('armeabi'), "-p1", "-i", filename)
+ shprint(sh.patch, "-t", "-d", self.get_build_dir(arch), "-p1",
+ "-i", filename, _tail=10)
+
+ def apply_all_patches(self, wildcard=join('patches','*.patch'), arch='armeabi'):
+ patches = glob.glob(join(self.recipe_dir, wildcard))
+ if not patches:
+ warning('requested patches {} not found for {}'.format(wildcard, self.name))
+ for filename in sorted(patches):
+ name = splitext(basename(filename))[0]
+ patched_flag = join(self.get_build_container_dir(arch), name + '.patched')
+ if exists(patched_flag):
+ info('patch {} already applied to {}, skipping'.format(name, self.name))
+ else:
+ self.apply_patch(filename, arch=arch)
+ sh.touch(patched_flag)
+ return len(patches)
+
def copy_file(self, filename, dest):
info("Copy {} to {}".format(filename, dest)) | toolchain: improved functions to apply recipe patches | kivy_python-for-android | train |
0f04a8a95bd13f84e198cf62f58476ead7187ffa | diff --git a/marshmallow_sqlalchemy/convert.py b/marshmallow_sqlalchemy/convert.py
index <HASH>..<HASH> 100644
--- a/marshmallow_sqlalchemy/convert.py
+++ b/marshmallow_sqlalchemy/convert.py
@@ -4,7 +4,7 @@ import functools
import marshmallow as ma
from marshmallow import validate, fields
-from sqlalchemy.dialects import postgresql, mysql
+from sqlalchemy.dialects import postgresql, mysql, mssql
import sqlalchemy as sa
from .exceptions import ModelConversionError
@@ -50,6 +50,8 @@ class ModelConverter(object):
mysql.YEAR: fields.Integer,
mysql.SET: fields.List,
mysql.ENUM: fields.Field,
+
+ mysql.BIT: fields.Integer,
}
DIRECTION_MAPPING = { | Include mssql dilect BIT field support. | marshmallow-code_marshmallow-sqlalchemy | train |
460782e64d8744b23b3c39347c8be0d1cff889fe | diff --git a/src/Model/Behavior/EncryptedFieldsBehavior.php b/src/Model/Behavior/EncryptedFieldsBehavior.php
index <HASH>..<HASH> 100644
--- a/src/Model/Behavior/EncryptedFieldsBehavior.php
+++ b/src/Model/Behavior/EncryptedFieldsBehavior.php
@@ -243,20 +243,22 @@ class EncryptedFieldsBehavior extends Behavior
$encryptionKey = $this->getConfig('encryptionKey');
$base64 = $this->getConfig('base64');
$encoded = $entity->get($field);
- if (!empty($encoded) && $encoded !== false) {
- if ($base64 === true) {
- $encoded = base64_decode($encoded, true);
- if ($encoded === false) {
- return null;
- }
- }
- $decrypted = Security::decrypt($encoded, $encryptionKey);
- if ($decrypted === false) {
- throw new RuntimeException("Unable to decypher `{$field}`. Check your enryption key.");
- }
+ if (empty($encoded) || $encoded === false) {
+ return null;
+ }
- return $decrypted;
+ if ($base64 === true) {
+ $encoded = base64_decode($encoded, true);
+ if ($encoded === false) {
+ return null;
+ }
+ }
+ $decrypted = Security::decrypt($encoded, $encryptionKey);
+ if ($decrypted === false) {
+ throw new RuntimeException("Unable to decypher `{$field}`. Check your enryption key.");
}
+
+ return $decrypted;
}
return null;
diff --git a/tests/TestCase/Model/Behavior/EncryptedFieldsBehaviorTest.php b/tests/TestCase/Model/Behavior/EncryptedFieldsBehaviorTest.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase/Model/Behavior/EncryptedFieldsBehaviorTest.php
+++ b/tests/TestCase/Model/Behavior/EncryptedFieldsBehaviorTest.php
@@ -398,4 +398,19 @@ class EncryptedFieldsBehaviorTest extends TestCase
$this->assertTrue($actualEntity->isDirty('name'));
$this->assertNotEquals($name, $actualEntity->get('name'));
}
+
+ /**
+ * Test custom finder method when decryption is disabled.
+ *
+ * @return void
+ */
+ public function testDecryptWithEmptyFieldReturnsNull(): void
+ {
+ $name = 'foobar';
+ $entity = $this->Users->newEntity([
+ 'name' => '',
+ ]);
+ $actual = $this->EncryptedFields->decryptEntityField($entity, 'name');
+ $this->assertNull($actual);
+ }
} | Decrease if nesting and add extra test (task #<I>) | QoboLtd_cakephp-utils | train |
ed7bd3a2bd8948f8a3745582233f50d14ba86720 | diff --git a/tornado/testing.py b/tornado/testing.py
index <HASH>..<HASH> 100644
--- a/tornado/testing.py
+++ b/tornado/testing.py
@@ -114,8 +114,8 @@ class _TestMethodWrapper(object):
def __init__(self, orig_method):
self.orig_method = orig_method
- def __call__(self):
- result = self.orig_method()
+ def __call__(self, *args, **kwargs):
+ result = self.orig_method(*args, **kwargs)
if isinstance(result, types.GeneratorType):
raise TypeError("Generator test methods should be decorated with "
"tornado.testing.gen_test") | Fixed support for test generators
This fixes the problem that AsyncTestCase no longer seemed to work with test generators (as supported by Nose, <URL>). | tornadoweb_tornado | train |
361aa401f23f31256388c94a506162a6fb52b3fb | diff --git a/structurizr-spring/src/com/structurizr/componentfinder/SpringComponentFinderStrategy.java b/structurizr-spring/src/com/structurizr/componentfinder/SpringComponentFinderStrategy.java
index <HASH>..<HASH> 100644
--- a/structurizr-spring/src/com/structurizr/componentfinder/SpringComponentFinderStrategy.java
+++ b/structurizr-spring/src/com/structurizr/componentfinder/SpringComponentFinderStrategy.java
@@ -13,7 +13,7 @@ public class SpringComponentFinderStrategy extends AbstractReflectionsComponentF
public Collection<Component> findComponents() throws Exception {
Collection<Component> componentsFound = new LinkedList<>();
- componentsFound.addAll(findClassesAnnotated(org.springframework.stereotype.Controller.class, "Spring Controller"));
+ componentsFound.addAll(findClassesAnnotated(org.springframework.stereotype.Controller.class, "Spring MVC Controller"));
componentsFound.addAll(findImplementationClassesAnnotated(org.springframework.stereotype.Service.class, "Spring Service"));
componentsFound.addAll(findImplementationClassesAnnotated(org.springframework.stereotype.Repository.class, "Spring Repository"));
componentsFound.addAll(findImplementationClassesAnnotated(org.springframework.stereotype.Component.class, "Spring Component")); | "Spring MVC controller" seems a bit more accurate. | structurizr_java | train |
2cbf9377d1d0c5b92d09a22cc1bd314fe6dbdca7 | diff --git a/src/correosESTracker.js b/src/correosESTracker.js
index <HASH>..<HASH> 100644
--- a/src/correosESTracker.js
+++ b/src/correosESTracker.js
@@ -72,10 +72,10 @@ function createCorreosEsEntity(id, html) {
if(_class === 'txtDescripcionTabla'){
state['date'] = moment(_child.children[0].data.trim(), "DD/MM/YYYY").format()
} else if (_class === 'txtContenidoTabla' || _class === 'txtContenidoTablaOff'){
- state['title'] = _child.children[1].children[0].data.trim()
+ state['state'] = _child.children[1].children[0].data.trim()
if (_child.children[1].attribs !== undefined && _child.children[1].attribs !== undefined
&& _child.children[1].attribs.title) {
- state['info'] = _child.children[1].attribs.title.trim()
+ state['title'] = _child.children[1].attribs.title.trim()
}
}
}
@@ -89,7 +89,7 @@ function createCorreosEsEntity(id, html) {
return new CorreosESInfo({
'id': id,
- 'state': states[states.length-1].title,
+ 'state': states[states.length-1].state,
'states': states.reverse()
})
}
diff --git a/test/correosESTest.js b/test/correosESTest.js
index <HASH>..<HASH> 100644
--- a/test/correosESTest.js
+++ b/test/correosESTest.js
@@ -16,15 +16,15 @@ describe('Correos ES', function() {
assert.equal(info.id, 'PQ4F6P0703673180181750T')
assert.equal(info.state, 'Entregado')
assert.equal(info.states.length, 5)
- assert.equal(info.states[0].title, 'Entregado')
+ assert.equal(info.states[0].state, 'Entregado')
assert.equal(moment(info.states[0].date).format("DD/MM/YYYY"), '20/01/2017')
- assert.equal(info.states[1].title, 'En proceso de entrega')
+ assert.equal(info.states[1].state, 'En proceso de entrega')
assert.equal(moment(info.states[1].date).format("DD/MM/YYYY"), '20/01/2017')
- assert.equal(info.states[2].title, 'En tránsito')
+ assert.equal(info.states[2].state, 'En tránsito')
assert.equal(moment(info.states[2].date).format("DD/MM/YYYY"), '19/01/2017')
- assert.equal(info.states[3].title, 'Admitido')
+ assert.equal(info.states[3].state, 'Admitido')
assert.equal(moment(info.states[3].date).format("DD/MM/YYYY"), '17/01/2017')
- assert.equal(info.states[4].title, 'Pre-registrado')
+ assert.equal(info.states[4].state, 'Pre-registrado')
assert.equal(moment(info.states[4].date).format("DD/MM/YYYY"), '01/01/2017')
console.log(id + ' attempts: ' + info.retries) | updated correosES to match the new convention { id, state, states: [ { date, state, title, area } ] } | hdnpt_geartrack | train |
f92f4b006e7e832269c4c6d402e2c676d54bcf04 | diff --git a/BimServer/src/org/bimserver/database/actions/StreamingCheckinDatabaseAction.java b/BimServer/src/org/bimserver/database/actions/StreamingCheckinDatabaseAction.java
index <HASH>..<HASH> 100644
--- a/BimServer/src/org/bimserver/database/actions/StreamingCheckinDatabaseAction.java
+++ b/BimServer/src/org/bimserver/database/actions/StreamingCheckinDatabaseAction.java
@@ -404,13 +404,6 @@ public class StreamingCheckinDatabaseAction extends GenericCheckinDatabaseAction
LOGGER.error("", e1);
}
- // Read the rest of the inputstream
- try {
- IOUtils.copy(inputStream, new NullOutputStream());
- } catch (IOException e1) {
- e1.printStackTrace();
- }
-
if (e instanceof BimserverDatabaseException) {
throw (BimserverDatabaseException) e;
}
@@ -449,7 +442,7 @@ public class StreamingCheckinDatabaseAction extends GenericCheckinDatabaseAction
Buffer buffer = getDatabaseSession().create(Buffer.class);
buffer.setData(verticesQuantized.array());
- next.set(GeometryPackage.eINSTANCE.getGeometryData_VerticesQuantized(), buffer);
+ next.setReference(GeometryPackage.eINSTANCE.getGeometryData_VerticesQuantized(), buffer.getOid(), -1);
next.saveOverwrite();
next = objectProvider.next();
diff --git a/BimServer/src/org/bimserver/servlets/TriggerOnCloseInputStream.java b/BimServer/src/org/bimserver/servlets/TriggerOnCloseInputStream.java
index <HASH>..<HASH> 100644
--- a/BimServer/src/org/bimserver/servlets/TriggerOnCloseInputStream.java
+++ b/BimServer/src/org/bimserver/servlets/TriggerOnCloseInputStream.java
@@ -3,13 +3,21 @@ package org.bimserver.servlets;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.atomic.AtomicInteger;
-public class TriggerOnCloseInputStream extends InputStream {
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.io.output.NullOutputStream;
+import org.slf4j.LoggerFactory;
+public class TriggerOnCloseInputStream extends InputStream {
+ private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(TriggerOnCloseInputStream.class);
+ private int id;
+ private static AtomicInteger COUNTER = new AtomicInteger();
private final CountDownLatch latch = new CountDownLatch(1);
private InputStream inputStream;
public TriggerOnCloseInputStream(InputStream inputStream) {
+ this.id = COUNTER.incrementAndGet();
this.inputStream = inputStream;
}
@@ -24,15 +32,19 @@ public class TriggerOnCloseInputStream extends InputStream {
@Override
public int read(byte[] b, int off, int len) throws IOException {
- int read = inputStream.read(b, off, len);
- if (read == -1) {
- latch.countDown();
+ if (latch.getCount() == 0) {
+ throw new IOException("Stream closed " + id);
}
+ int read = inputStream.read(b, off, len);
return read;
}
@Override
public void close() throws IOException {
+// LOGGER.error("Closing " + id, new Exception());
+
+ // Read the rest of the inputstream
+ IOUtils.copy(inputStream, new NullOutputStream());
latch.countDown();
inputStream.close();
} | Moved code that finishes reading the InputStream on error to a safer
place (TriggerOnCloseInputStream) | opensourceBIM_BIMserver | train |
e1baf12641455bad4b2651c06c39f0d8d4631c68 | diff --git a/bcbio/pipeline/shared.py b/bcbio/pipeline/shared.py
index <HASH>..<HASH> 100644
--- a/bcbio/pipeline/shared.py
+++ b/bcbio/pipeline/shared.py
@@ -210,9 +210,11 @@ def remove_highdepth_regions(in_file, items):
all_file = "%s-all.bed" % utils.splitext_plus(tx_out_file)[0]
if len(highdepth_beds) > 0:
with open(all_file, "w") as out_handle:
- for line in fileinput.input(highdepth_beds):
- parts = line.split("\t")
- out_handle.write("\t".join(parts[:4]).rstrip() + "\n")
+ for highdepth_bed in highdepth_beds:
+ with utils.open_gzipsafe(highdepth_bed) as in_handle:
+ for line in in_handle:
+ parts = line.split("\t")
+ out_handle.write("\t".join(parts[:4]).rstrip() + "\n")
if utils.file_exists(all_file):
to_remove = bedutils.sort_merge(all_file, items[0])
cmd = "bedtools subtract -nonamecheck -a {in_file} -b {to_remove} > {tx_out_file}" | highdepth: handle bgzipped input files
Some installed highdepth BED files are now bgzipped, so be sure
we handle these correctly and avoid writing binary output. #<I> | bcbio_bcbio-nextgen | train |
c5874ddf0195f8eb49c42b320bfe685dab5c2a7c | diff --git a/python/mxnet/autograd.py b/python/mxnet/autograd.py
index <HASH>..<HASH> 100644
--- a/python/mxnet/autograd.py
+++ b/python/mxnet/autograd.py
@@ -493,6 +493,7 @@ class Function(object):
POINTER(CFUNCTYPE(c_int))),
cast(c_array(c_void_p, [None]*len(callbacks)),
POINTER(c_void_p)))
+ Function._registry.ref_holder[key] = context
check_call(_LIB.MXCustomFunctionRecord(
c_int(len(inputs)),
c_handle_array(inputs),
@@ -500,8 +501,6 @@ class Function(object):
c_handle_array(outputs),
ctypes.byref(context)))
- Function._registry.ref_holder[key] = context
-
return ret_outputs
def forward(self, *inputs):
diff --git a/tests/python/unittest/test_autograd.py b/tests/python/unittest/test_autograd.py
index <HASH>..<HASH> 100644
--- a/tests/python/unittest/test_autograd.py
+++ b/tests/python/unittest/test_autograd.py
@@ -379,6 +379,27 @@ def test_function():
@with_seed()
+def test_function1():
+ class Foo(mx.autograd.Function):
+ def __init__(self):
+ super(Foo, self).__init__()
+
+ def forward(self, X):
+ return X + 1;
+
+ def backward(self, dY):
+ return dY
+
+ with mx.autograd.record():
+ X = mx.nd.zeros((3, 4))
+ #X.attach_grad() # uncommenting this line works
+ for i in range(5):
+ f = Foo()
+ X = f(X)
+ X.wait_to_read()
+
+
+@with_seed()
def test_get_symbol():
x = mx.nd.ones((1,))
x.attach_grad() | [BUGFIX] Fix a bug in Auto Function. (#<I>)
* add test.
* fix.
* update test. | apache_incubator-mxnet | train |
33702f7c5db567f43af64c0c5038905a70287e66 | diff --git a/src/Generator/Analyzer/Steps/AnalyzeModels.php b/src/Generator/Analyzer/Steps/AnalyzeModels.php
index <HASH>..<HASH> 100644
--- a/src/Generator/Analyzer/Steps/AnalyzeModels.php
+++ b/src/Generator/Analyzer/Steps/AnalyzeModels.php
@@ -72,16 +72,19 @@ class AnalyzeModels extends AbstractProcessStep
'cached' => config('pxlcms.generator.models.enable_rememberable_cache'),
'is_translated' => false,
'is_listified' => $listified, // makes no sense for single-entry only
+ 'timestamps' => null,
+ // attributes
'normal_fillable' => [],
'translated_fillable' => [],
'hidden' => $overrideHidden,
'casts' => $overrideCasts,
'dates' => [],
- 'relations_config' => [],
'normal_attributes' => [],
'translated_attributes' => [],
- 'timestamps' => null,
-
+ // categories
+ 'has_categories' => (bool) array_get($moduleData, 'client_cat_control'),
+ // relationships
+ 'relations_config' => [],
'relationships' => [
'normal' => [],
'reverse' => [],
diff --git a/src/Generator/Analyzer/Steps/LoadRawData.php b/src/Generator/Analyzer/Steps/LoadRawData.php
index <HASH>..<HASH> 100644
--- a/src/Generator/Analyzer/Steps/LoadRawData.php
+++ b/src/Generator/Analyzer/Steps/LoadRawData.php
@@ -57,9 +57,14 @@ class LoadRawData extends AbstractProcessStep
$this->data->rawData['modules'][ $moduleId ] = [];
$this->data->rawData['modules'][ $moduleId ]['prefixed_name'] = null;
+ // note that we do not need 'simulate_categories_for', since this
+ // is strictly a CMS-feature -- the reference used for it is already
+ // accounted for in the model
+
foreach ([ 'name', 'max_entries', 'is_custom',
'allow_create', 'allow_update', 'allow_delete',
- 'simulate_categories_for', 'section_id',
+ 'client_cat_control', 'max_cat_depth',
+ 'section_id',
'override_table_name',
] as $key
) {
diff --git a/src/Generator/ModelWriter.php b/src/Generator/ModelWriter.php
index <HASH>..<HASH> 100644
--- a/src/Generator/ModelWriter.php
+++ b/src/Generator/ModelWriter.php
@@ -159,25 +159,25 @@ class ModelWriter
protected function makeTranslatedDataFromModelData(array $model)
{
return [
- 'module' => $model['module'],
- 'name' => $model['name'] . config('pxlcms.generator.models.translation_model_postfix'),
- 'table' => ! empty($model['table'])
+ 'module' => $model['module'],
+ 'name' => $model['name'] . config('pxlcms.generator.models.translation_model_postfix'),
+ 'table' => ! empty($model['table'])
? $model['table'] . snake_case(config('pxlcms.tables.translation_postfix', '_ml'))
: null,
- 'cached' => $model['cached'],
- 'is_translated' => false,
- 'is_listified' => false,
- 'normal_fillable' => $model['translated_attributes'],
- 'translated_fillable' => [],
- 'hidden' => [],
- 'casts' => [],
- 'dates' => [],
- 'relations_config' => [],
- 'normal_attributes' => [],
- 'translated_attributes' => [],
- 'timestamps' => null,
-
- 'relationships' => [
+ 'cached' => $model['cached'],
+ 'is_translated' => false,
+ 'is_listified' => false,
+ 'normal_fillable' => $model['translated_attributes'],
+ 'translated_fillable' => [],
+ 'hidden' => [],
+ 'casts' => [],
+ 'dates' => [],
+ 'normal_attributes' => [],
+ 'translated_attributes' => [],
+ 'timestamps' => null,
+ 'categories_module' => null,
+ 'relations_config' => [],
+ 'relationships' => [
'normal' => [],
'reverse' => [],
'image' => [],
diff --git a/src/config/pxlcms.php b/src/config/pxlcms.php
index <HASH>..<HASH> 100644
--- a/src/config/pxlcms.php
+++ b/src/config/pxlcms.php
@@ -180,11 +180,12 @@ return [
],
- // the FQN's for the standard CMS models for special relationships
+ // the FQN's for the standard CMS models for special relationships (and CMS categories)
'standard_models' => [
- 'image' => 'Czim\\PxlCms\\Models\\Image',
+ 'category' => 'Czim\\PxlCms\\Models\\Category',
'checkbox' => 'Czim\\PxlCms\\Models\\Checkbox',
'file' => 'Czim\\PxlCms\\Models\\File',
+ 'image' => 'Czim\\PxlCms\\Models\\Image',
],
/* | analyzer + config prepared for modules with (real) categories | czim_laravel-pxlcms | train |
b5f1631bcb0fe543ca0c921fb05fe35992421627 | diff --git a/src/Common/Console/Command/Database/Migrate.php b/src/Common/Console/Command/Database/Migrate.php
index <HASH>..<HASH> 100644
--- a/src/Common/Console/Command/Database/Migrate.php
+++ b/src/Common/Console/Command/Database/Migrate.php
@@ -336,12 +336,14 @@ class Migrate extends Base
$aOut = array_values($aOut);
// Shift the app migrations onto the end so they are executed last
- $oFirst = reset($aOut);
- if ($oFirst->name === Components::$oAppSlug) {
- $oApp = array_shift($aOut);
- $aOut = array_merge($aOut, [$oApp]);
- $aOut = array_filter($aOut);
- $aOut = array_values($aOut);
+ if (!empty($aOut)) {
+ $oFirst = reset($aOut);
+ if ($oFirst->name === Components::$oAppSlug) {
+ $oApp = array_shift($aOut);
+ $aOut = array_merge($aOut, [$oApp]);
+ $aOut = array_filter($aOut);
+ $aOut = array_values($aOut);
+ }
}
return $aOut; | Further fix for DB migrations when there are _no_migrations | nails_common | train |
a9962c73481fc192b5c9eda29126fade7557755f | diff --git a/tests/specs/events.js b/tests/specs/events.js
index <HASH>..<HASH> 100644
--- a/tests/specs/events.js
+++ b/tests/specs/events.js
@@ -34,6 +34,42 @@ var assert = chai.assert,
dp.selectDate(date);
+ });
+
+ it('should receive array of dates when "multipleDates" set to true', function () {
+ var date = new Date(2016,0,22),
+ date2 = new Date(2016,0,23),
+ dates = [];
+
+ dp = $input.datepicker({
+ multipleDates: true,
+ onSelect: function (fd, d, inst) {
+ dates = d;
+ }
+ }).data('datepicker');
+
+ dp.selectDate(date);
+ dp.selectDate(date2);
+
+ expect(dates).to.have.length(2)
+
+ })
+ it('should receive array of dates when "range" set to true', function () {
+ var date = new Date(2016,0,22),
+ date2 = new Date(2016,0,23),
+ dates = [];
+
+ dp = $input.datepicker({
+ range: true,
+ onSelect: function (fd, d, inst) {
+ dates = d;
+ }
+ }).data('datepicker');
+
+ dp.selectDate(date);
+ dp.selectDate(date2);
+
+ expect(dates).to.have.length(2)
})
}); | add tests for "onSelect" event | t1m0n_air-datepicker | train |
280b47d737ce60337293a8f38e33111e0a71e512 | diff --git a/bundles/org.eclipse.orion.client.editor/web/orion/editor/editor.js b/bundles/org.eclipse.orion.client.editor/web/orion/editor/editor.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.editor/web/orion/editor/editor.js
+++ b/bundles/org.eclipse.orion.client.editor/web/orion/editor/editor.js
@@ -161,7 +161,14 @@ define("orion/editor/editor", ['i18n!orion/editor/nls/messages', 'orion/keyBindi
getTitle: function() {
return this._title;
},
-
+ /**
+ * Returns the editor undo stack.
+ *
+ * @returns {orion.editor.UndoStack} the editor undo stack.
+ */
+ getUndoStack: function() {
+ return this._undoStack;
+ },
/**
* Returns the editor's key modes.
* | Add API to return undo stack from editor | eclipse_orion.client | train |
81249eb110d3acaad149b3dfac78b2a3752329af | diff --git a/ddlgenerator/console.py b/ddlgenerator/console.py
index <HASH>..<HASH> 100644
--- a/ddlgenerator/console.py
+++ b/ddlgenerator/console.py
@@ -48,7 +48,7 @@ def set_logging(args):
is_sqlalchemy_url = re.compile("^%s" % "|".join(dialect_names))
-def generate_one(tbl, args, table_name=None):
+def generate_one(tbl, args, table_name=None, file=None):
"""
Prints code (SQL, SQLAlchemy, etc.) to define a table.
"""
@@ -58,23 +58,24 @@ def generate_one(tbl, args, table_name=None):
loglevel=args.log, limit=args.limit)
if args.dialect.startswith('sqla'):
if not args.no_creates:
- print(table.sqlalchemy())
+ print(table.sqlalchemy(), file=file)
if args.inserts:
- print("\n".join(table.inserts(dialect=args.dialect)))
+ print("\n".join(table.inserts(dialect=args.dialect)), file=file)
elif args.dialect.startswith('dj'):
table.django_models()
else:
print(table.sql(dialect=args.dialect, inserts=args.inserts,
creates=(not args.no_creates), drops=args.drops,
- metadata_source=args.use_metadata_from))
+ metadata_source=args.use_metadata_from), file=file)
return table
-def generate(args=None, namespace=None):
+def generate(args=None, namespace=None, file=None):
"""
Genereate DDL from data sources named.
:args: String or list of strings to be parsed for arguments
:namespace: Namespace to extract arguments from
+ :file: Write to this open file object (default stdout)
"""
if hasattr(args, 'split'):
args = args.split()
@@ -91,22 +92,22 @@ def generate(args=None, namespace=None):
if args.dialect not in dialect_names:
raise NotImplementedError('First arg must be one of: %s' % ", ".join(dialect_names))
if args.dialect == 'sqlalchemy':
- print(sqla_head)
+ print(sqla_head, file=file)
for datafile in args.datafile:
if is_sqlalchemy_url.search(datafile):
table_names_for_insert = []
for tbl in sqlalchemy_table_sources(datafile):
- t = generate_one(tbl, args, table_name=tbl.generator.name)
+ t = generate_one(tbl, args, table_name=tbl.generator.name, file=file)
if t.data:
table_names_for_insert.append(tbl.generator.name)
if args.inserts and args.dialect == 'sqlalchemy':
- print(sqla_inserter_call(table_names_for_insert))
+ print(sqla_inserter_call(table_names_for_insert), file=file)
if t and args.inserts:
for seq_update in emit_db_sequence_updates(t.source.db_engine):
if args.dialect == 'sqlalchemy':
- print(' conn.execute("%s")' % seq_update)
+ print(' conn.execute("%s")' % seq_update, file=file)
elif args.dialect == 'postgresql':
- print(seq_update)
+ print(seq_update, file=file)
else:
- generate_one(datafile, args)
+ generate_one(datafile, args, file=file) | capture output in file when calling programmatically | catherinedevlin_ddl-generator | train |
df7c60f1e506f3dae012643202c74ecd191ef45f | diff --git a/limpyd/contrib/related.py b/limpyd/contrib/related.py
index <HASH>..<HASH> 100644
--- a/limpyd/contrib/related.py
+++ b/limpyd/contrib/related.py
@@ -69,24 +69,25 @@ class RelatedCollection(object):
a simple one, or remove the instance from the field if it's a set/list/
sorted_set)
"""
- related_pks = self()
- for pk in related_pks:
-
- # get the real related field
- related_instance = self.related_field._model(pk)
- related_field = getattr(related_instance, self.related_field.name)
-
- # check if we have a dedicated remove method
- remover = getattr(related_field, '_related_remover', None)
-
- # then remove the instance from the related field
- if remover is not None:
- # if we have a remover method, it wants the instance as argument
- # (the related field may be a set/list/sorted_set)
- getattr(related_field, remover)(self.instance._pk)
- else:
- # no remover method, simple delete the field
- related_field.delete()
+ with fields.FieldLock(self.related_field):
+ related_pks = self()
+ for pk in related_pks:
+
+ # get the real related field
+ related_instance = self.related_field._model(pk)
+ related_field = getattr(related_instance, self.related_field.name)
+
+ # check if we have a dedicated remove method
+ remover = getattr(related_field, '_related_remover', None)
+
+ # then remove the instance from the related field
+ if remover is not None:
+ # if we have a remover method, it wants the instance as argument
+ # (the related field may be a set/list/sorted_set)
+ getattr(related_field, remover)(self.instance._pk)
+ else:
+ # no remover method, simple delete the field
+ related_field.delete()
class RelatedModel(model.RedisModel): | Use lock when rm instance from RelatedCollection
We use a FieldLock when removing an instance from a lot a others objets so this
process is now protected | limpyd_redis-limpyd | train |
7441ec74f3d251bd3d2119169f75f7bb8a384a53 | diff --git a/src/js.cookie.js b/src/js.cookie.js
index <HASH>..<HASH> 100644
--- a/src/js.cookie.js
+++ b/src/js.cookie.js
@@ -66,12 +66,10 @@
}
} catch (e) {}
- if (!converter.write) {
- value = encodeURIComponent(String(value))
+ value = converter.write ?
+ converter.write(value, key) :
+ encodeURIComponent(String(value))
.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
- } else {
- value = converter.write(value, key);
- }
key = encodeURIComponent(String(key))
.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent) | Make use of ternary operator instead of if/else
This way value + key appear together, visually. | js-cookie_js-cookie | train |
2187e986dea4bea403f9efedb36555ea9ed28cc3 | diff --git a/src/select.js b/src/select.js
index <HASH>..<HASH> 100644
--- a/src/select.js
+++ b/src/select.js
@@ -410,7 +410,8 @@
item = ctrl.tagging.fct(ctrl.search);
// if item type is 'string', apply the tagging label
} else if ( typeof item === 'string' ) {
- item = item.replace(ctrl.taggingLabel,'');
+ // trim the trailing space
+ item = item.replace(ctrl.taggingLabel,'').trim();
}
}
} | Trim the trailing space left by a new tag's label. | angular-ui_ui-select | train |
4c435f09006c3c9ab9b951ecebbd1ac0374d4dc5 | diff --git a/agent/agent.go b/agent/agent.go
index <HASH>..<HASH> 100644
--- a/agent/agent.go
+++ b/agent/agent.go
@@ -159,6 +159,7 @@ func (a *Agent) run(ctx context.Context) {
a.err = err
return // fatal?
}
+ defer a.worker.Close()
// setup a reliable reporter to call back to us.
reporter := newStatusReporter(ctx, a)
diff --git a/agent/worker.go b/agent/worker.go
index <HASH>..<HASH> 100644
--- a/agent/worker.go
+++ b/agent/worker.go
@@ -5,10 +5,10 @@ import (
"github.com/Sirupsen/logrus"
"github.com/boltdb/bolt"
- "github.com/docker/go-events"
"github.com/docker/swarmkit/agent/exec"
"github.com/docker/swarmkit/api"
"github.com/docker/swarmkit/log"
+ "github.com/docker/swarmkit/watch"
"golang.org/x/net/context"
)
@@ -18,6 +18,11 @@ type Worker interface {
// Init prepares the worker for task assignment.
Init(ctx context.Context) error
+ // Close performs worker cleanup when no longer needed.
+ //
+ // It is not safe to call any worker function after that.
+ Close()
+
// Assign assigns a complete set of tasks and secrets to a worker. Any task or secrets not included in
// this set will be removed.
Assign(ctx context.Context, assignments []*api.AssignmentChange) error
@@ -33,6 +38,7 @@ type Worker interface {
// The listener will be removed if the context is cancelled.
Listen(ctx context.Context, reporter StatusReporter)
+ // Subscribe to log messages matching the subscription.
Subscribe(ctx context.Context, subscription *api.SubscriptionMessage) error
}
@@ -46,7 +52,7 @@ type worker struct {
executor exec.Executor
publisher exec.LogPublisher
listeners map[*statusReporterKey]struct{}
- taskevents *events.Broadcaster
+ taskevents *watch.Queue
publisherProvider exec.LogPublisherProvider
taskManagers map[string]*taskManager
@@ -58,7 +64,7 @@ func newWorker(db *bolt.DB, executor exec.Executor, publisherProvider exec.LogPu
db: db,
executor: executor,
publisherProvider: publisherProvider,
- taskevents: events.NewBroadcaster(),
+ taskevents: watch.NewQueue(),
listeners: make(map[*statusReporterKey]struct{}),
taskManagers: make(map[string]*taskManager),
}
@@ -98,6 +104,11 @@ func (w *worker) Init(ctx context.Context) error {
})
}
+// Close performs worker cleanup when no longer needed.
+func (w *worker) Close() {
+ w.taskevents.Close()
+}
+
// Assign assigns a full set of tasks and secrets to the worker.
// Any tasks not previously known will be started. Any tasks that are in the task set
// and already running will be updated, if possible. Any tasks currently running on
@@ -327,7 +338,7 @@ func (w *worker) Listen(ctx context.Context, reporter StatusReporter) {
}
func (w *worker) startTask(ctx context.Context, tx *bolt.Tx, task *api.Task) error {
- w.taskevents.Write(task.Copy())
+ w.taskevents.Publish(task.Copy())
_, err := w.taskManager(ctx, tx, task) // side-effect taskManager creation.
if err != nil {
@@ -391,6 +402,7 @@ func (w *worker) updateTaskStatus(ctx context.Context, tx *bolt.Tx, taskID strin
return nil
}
+// Subscribe to log messages matching the subscription.
func (w *worker) Subscribe(ctx context.Context, subscription *api.SubscriptionMessage) error {
log.G(ctx).Debugf("Received subscription %s (selector: %v)", subscription.ID, subscription.Selector)
@@ -421,14 +433,8 @@ func (w *worker) Subscribe(ctx context.Context, subscription *api.SubscriptionMe
return false
}
- ch := events.NewChannel(1000)
- q := events.NewQueue(ch)
- w.taskevents.Add(q)
- defer func() {
- w.taskevents.Remove(q)
- q.Close()
- ch.Close()
- }()
+ ch, cancel := w.taskevents.Watch()
+ defer cancel()
w.mu.Lock()
for _, tm := range w.taskManagers {
@@ -440,7 +446,7 @@ func (w *worker) Subscribe(ctx context.Context, subscription *api.SubscriptionMe
for {
select {
- case v := <-ch.C:
+ case v := <-ch:
w.mu.Lock()
task := v.(*api.Task)
if match(task) { | agent: Release worker resources on shutdown. | docker_swarmkit | train |
9284c595a727ca70b845ad7ec4792cc549db7fa7 | diff --git a/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/metadata/database/ShardingSphereDatabasesFactory.java b/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/metadata/database/ShardingSphereDatabasesFactory.java
index <HASH>..<HASH> 100644
--- a/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/metadata/database/ShardingSphereDatabasesFactory.java
+++ b/shardingsphere-infra/shardingsphere-infra-common/src/main/java/org/apache/shardingsphere/infra/metadata/database/ShardingSphereDatabasesFactory.java
@@ -77,7 +77,7 @@ public final class ShardingSphereDatabasesFactory {
for (Entry<String, DatabaseConfiguration> entry : databaseConfigMap.entrySet()) {
String databaseName = entry.getKey();
if (!entry.getValue().getDataSources().isEmpty() || !protocolType.getSystemSchemas().contains(databaseName)) {
- result.put(databaseName, ShardingSphereDatabase.create(databaseName, protocolType, storageType, entry.getValue(), props, instanceContext));
+ result.put(databaseName.toLowerCase(), ShardingSphereDatabase.create(databaseName, protocolType, storageType, entry.getValue(), props, instanceContext));
}
}
return result;
@@ -87,7 +87,7 @@ public final class ShardingSphereDatabasesFactory {
Map<String, ShardingSphereDatabase> result = new HashMap<>(protocolType.getSystemDatabaseSchemaMap().size(), 1);
for (String each : protocolType.getSystemDatabaseSchemaMap().keySet()) {
if (!databaseConfigMap.containsKey(each) || databaseConfigMap.get(each).getDataSources().isEmpty()) {
- result.put(each, ShardingSphereDatabase.create(each, protocolType));
+ result.put(each.toLowerCase(), ShardingSphereDatabase.create(each, protocolType));
}
}
return result;
diff --git a/shardingsphere-infra/shardingsphere-infra-common/src/test/java/org/apache/shardingsphere/infra/metadata/database/ShardingSphereDatabasesFactoryTest.java b/shardingsphere-infra/shardingsphere-infra-common/src/test/java/org/apache/shardingsphere/infra/metadata/database/ShardingSphereDatabasesFactoryTest.java
index <HASH>..<HASH> 100644
--- a/shardingsphere-infra/shardingsphere-infra-common/src/test/java/org/apache/shardingsphere/infra/metadata/database/ShardingSphereDatabasesFactoryTest.java
+++ b/shardingsphere-infra/shardingsphere-infra-common/src/test/java/org/apache/shardingsphere/infra/metadata/database/ShardingSphereDatabasesFactoryTest.java
@@ -59,4 +59,15 @@ public final class ShardingSphereDatabasesFactoryTest {
assertThat(rules.iterator().next(), instanceOf(FixtureDatabaseRule.class));
assertTrue(actual.get("foo_db").getResource().getDataSources().isEmpty());
}
+
+ @Test
+ public void assertCreateDatabaseMapWhenConfigUppercaseDatabaseName() throws SQLException {
+ DatabaseConfiguration databaseConfig = new DataSourceProvidedDatabaseConfiguration(Collections.emptyMap(), Collections.singleton(new FixtureRuleConfiguration()));
+ Map<String, ShardingSphereDatabase> actual = ShardingSphereDatabasesFactory.create(
+ Collections.singletonMap("FOO_DB", databaseConfig), new ConfigurationProperties(new Properties()), mock(InstanceContext.class));
+ Collection<ShardingSphereRule> rules = actual.get("foo_db").getRuleMetaData().getRules();
+ assertThat(rules.size(), is(1));
+ assertThat(rules.iterator().next(), instanceOf(FixtureDatabaseRule.class));
+ assertTrue(actual.get("foo_db").getResource().getDataSources().isEmpty());
+ }
} | Fix show tables wrong result when execute drop sharding table rule (#<I>) | apache_incubator-shardingsphere | train |
fdfc65689a63f659b2fc828b89efd8ea717a4ff0 | diff --git a/cli/lib/kontena/errors.rb b/cli/lib/kontena/errors.rb
index <HASH>..<HASH> 100644
--- a/cli/lib/kontena/errors.rb
+++ b/cli/lib/kontena/errors.rb
@@ -24,6 +24,7 @@ module Kontena
# Render as indented YAML
def errors_message(indent: "\t")
+ require 'yaml'
@errors.to_yaml.lines[1..-1].map{|line| "#{indent}#{line}" }.join
end | Add yaml loading to error handling (#<I>) | kontena_kontena | train |
68573629b7463f7884668ec08395afc8aa4ff564 | diff --git a/pycbc/fft/mkl.py b/pycbc/fft/mkl.py
index <HASH>..<HASH> 100644
--- a/pycbc/fft/mkl.py
+++ b/pycbc/fft/mkl.py
@@ -1,6 +1,18 @@
-import ctypes
+import ctypes, functools
from pycbc.types import zeros
+def memoize(obj):
+ cache = obj.cache = {}
+
+ @functools.wraps(obj)
+ def memoizer(*args, **kwargs):
+ key = str(args) + str(kwargs)
+ if key not in cache:
+ cache[key] = obj(*args, **kwargs)
+ return cache[key]
+ return memoizer
+
+
lib_name = 'libmkl_rt.so'
lib = ctypes.cdll.LoadLibrary(lib_name)
@@ -69,7 +81,8 @@ def check_status(status):
msg = lib.DftiErrorMessage(status)
msg = ctypes.c_char_p(msg).value
raise RuntimeError(msg)
-
+
+@memoize
def create_descriptor(size, idtype, odtype):
invec = zeros(1, dtype=idtype)
outvec = zeros(1, dtype=odtype)
@@ -90,14 +103,14 @@ def create_descriptor(size, idtype, odtype):
return desc
def fft(invec, outvec, prec, itype, otype):
- descr = create_descriptor(max(len(invec), len(outvec)), itype, otype)
+ descr = create_descriptor(max(len(invec), len(outvec)), invec.dtype, outvec.dtype)
f = lib.DftiComputeForward
f.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
status = f(descr, invec.ptr, outvec.ptr)
check_status(status)
-def fft(invec, outvec, prec, itype, otype):
- descr = create_descriptor(max(len(invec), len(outvec)), itype, otype)
+def ifft(invec, outvec, prec, itype, otype):
+ descr = create_descriptor(max(len(invec), len(outvec)), invec.dtype, invec.dtype)
f = lib.DftiComputeBackward
f.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
status = f(descr, invec.ptr, outvec.ptr) | mkl prototype can now be run (not tested for correctness) | gwastro_pycbc | train |
57b9c75df61d1ec6edb5430e75a7e3a80cae76b5 | diff --git a/test/test_failover_integration.py b/test/test_failover_integration.py
index <HASH>..<HASH> 100644
--- a/test/test_failover_integration.py
+++ b/test/test_failover_integration.py
@@ -23,10 +23,10 @@ class TestFailover(KafkaIntegrationTestCase):
return
zk_chroot = random_string(10)
- replicas = 2
- partitions = 2
+ replicas = 3
+ partitions = 3
- # mini zookeeper, 2 kafka brokers
+ # mini zookeeper, 3 kafka brokers
self.zk = ZookeeperFixture.instance()
kk_args = [self.zk.host, self.zk.port, zk_chroot, replicas, partitions]
self.brokers = [KafkaFixture.instance(i, *kk_args) for i in range(replicas)] | Test failover integration with 3-brokers / replicas / partitions | dpkp_kafka-python | train |
6b7664f642da9537a793775ee7b99e9a55355ee3 | diff --git a/tools/interop_matrix/client_matrix.py b/tools/interop_matrix/client_matrix.py
index <HASH>..<HASH> 100644
--- a/tools/interop_matrix/client_matrix.py
+++ b/tools/interop_matrix/client_matrix.py
@@ -142,8 +142,8 @@ LANG_RELEASE_MATRIX = {
('v1.19.0',
ReleaseInfo(runtimes=['go1.11'], testcases_file='go__v1.0.5')),
('v1.20.0', ReleaseInfo(runtimes=['go1.11'])),
- ('v1.21.0', ReleaseInfo(runtimes=['go1.11'])),
- ('v1.22.0', ReleaseInfo(runtimes=['go1.11'])),
+ ('v1.21.2', ReleaseInfo(runtimes=['go1.11'])),
+ ('v1.22.1', ReleaseInfo(runtimes=['go1.11'])),
]),
'java':
OrderedDict([ | Add <I> and <I> of grpc-go to interop matrix | grpc_grpc | train |
6691f9ec09fde8420347b7b7bca4f3cf23e56431 | diff --git a/src/Http/Controllers/BaseController.php b/src/Http/Controllers/BaseController.php
index <HASH>..<HASH> 100644
--- a/src/Http/Controllers/BaseController.php
+++ b/src/Http/Controllers/BaseController.php
@@ -56,6 +56,22 @@ class BaseController extends Controller
return false;
}
+ public function canModerate()
+ {
+ $user = $this->getUser();
+
+ if ($user->name == 'Guest' && $user->email == '[email protected]') {
+ return false;
+ }
+
+ if (method_exists($user, 'can')) {
+ return $user->can('forum-moderate');
+ }
+
+ // If no method of authorizing return false;
+ return false;
+ }
+
/**
* Retrieve a user model or object for the Guest user.
* @return object | Add forum-moderate permission and canModerate controller method. | taskforcedev_laravel-forum | train |
cd1204f6a263523046636dfc4ff2b28bca65b971 | diff --git a/src/php/wp-cli/class-wp-cli.php b/src/php/wp-cli/class-wp-cli.php
index <HASH>..<HASH> 100644
--- a/src/php/wp-cli/class-wp-cli.php
+++ b/src/php/wp-cli/class-wp-cli.php
@@ -25,7 +25,7 @@ class WP_CLI {
* @param string $message
*/
static function out( $message ) {
- if ( defined( 'WP_CLI_SILENT' ) && WP_CLI_SILENT ) return;
+ if ( WP_CLI_SILENT ) return;
\cli\out($message);
}
@@ -35,7 +35,7 @@ class WP_CLI {
* @param string $message
*/
static function line( $message = '' ) {
- if ( defined( 'WP_CLI_SILENT' ) && WP_CLI_SILENT ) return;
+ if ( WP_CLI_SILENT ) return;
\cli\line($message);
}
@@ -57,7 +57,7 @@ class WP_CLI {
* @param string $label
*/
static function success( $message, $label = 'Success' ) {
- if ( defined( 'WP_CLI_SILENT' ) && WP_CLI_SILENT ) return;
+ if ( WP_CLI_SILENT ) return;
\cli\line( '%G' . $label . ': %n' . $message );
}
@@ -68,7 +68,7 @@ class WP_CLI {
* @param string $label
*/
static function warning( $message, $label = 'Warning' ) {
- if ( defined( 'WP_CLI_SILENT' ) && WP_CLI_SILENT ) return;
+ if ( WP_CLI_SILENT ) return;
\cli\line( '%C' . $label . ': %n' . $message );
}
diff --git a/src/php/wp-cli/wp-cli.php b/src/php/wp-cli/wp-cli.php
index <HASH>..<HASH> 100755
--- a/src/php/wp-cli/wp-cli.php
+++ b/src/php/wp-cli/wp-cli.php
@@ -74,11 +74,7 @@ if ( array( 'core', 'config' ) == $arguments ) {
WP_CLI::_set_url();
// Implement --silent flag
-if ( isset( $assoc_args['silent'] ) ) {
- define('WP_CLI_SILENT', true);
-} else {
- define('WP_CLI_SILENT', false);
-}
+define( 'WP_CLI_SILENT', isset( $assoc_args['silent'] ) );
// Set installer flag before loading any WP files
if ( count( $arguments ) >= 2 && $arguments[0] == 'core' && $arguments[1] == 'install' ) { | WP_CLI_SILENT is always defined | wp-cli_extension-command | train |
30765937f4f3ef956cfffe148cdc43b664857a4c | diff --git a/src/java/com/github/rainmanwy/robotframework/sikulilib/keywords/ScreenKeywords.java b/src/java/com/github/rainmanwy/robotframework/sikulilib/keywords/ScreenKeywords.java
index <HASH>..<HASH> 100644
--- a/src/java/com/github/rainmanwy/robotframework/sikulilib/keywords/ScreenKeywords.java
+++ b/src/java/com/github/rainmanwy/robotframework/sikulilib/keywords/ScreenKeywords.java
@@ -150,6 +150,20 @@ public class ScreenKeywords {
}
}
+ @RobotKeyword("Paste text. Image could be empty")
+ @ArgumentNames({"image", "text"})
+ public void pasteText(String image, String text) throws Exception {
+ System.out.println("Paste Text:");
+ System.out.println(text);
+ if ( !"".equals(image) ) {
+ this.click(image);
+ }
+ int result = screen.paste(text);
+ if (result == 0) {
+ throw new ScreenOperationException("Paste text failed");
+ }
+ }
+
@RobotKeyword("Click in. \nClick target image in area image.")
@ArgumentNames({"areaImage", "targetImage"})
public void clickIn(String areaImage, String targetImage) throws Exception { | add paste operation, it could fix unicode problem for input text, for example chinese language input | rainmanwy_robotframework-SikuliLibrary | train |
fb7f3231cbbdf15acca721b2af283b3e2b76691b | diff --git a/tap/adapter.py b/tap/adapter.py
index <HASH>..<HASH> 100644
--- a/tap/adapter.py
+++ b/tap/adapter.py
@@ -32,12 +32,20 @@ class Adapter(object):
# TODO: Pass in a fake test case that has all the internal APIs.
"""Handle a test result line."""
if line.skip:
- result.addSkip(None, line.directive.reason)
+ try:
+ result.addSkip(None, line.directive.reason)
+ except AttributeError:
+ # Python 2.6 does not support skipping.
+ result.addSuccess(None)
return
if line.todo:
if line.ok:
- result.addUnexpectedSuccess(None)
+ try:
+ result.addUnexpectedSuccess(None)
+ except AttributeError:
+ # TODO: Set as addFailure with full directive text.
+ pass
else:
# TODO: make it work
pass
diff --git a/tap/tests/test_adapter.py b/tap/tests/test_adapter.py
index <HASH>..<HASH> 100644
--- a/tap/tests/test_adapter.py
+++ b/tap/tests/test_adapter.py
@@ -1,6 +1,7 @@
# Copyright (c) 2014, Matt Layman
import inspect
+import sys
import tempfile
import mock
@@ -52,6 +53,10 @@ class TestAdapter(TestCase):
def test_handles_skip_test_line(self):
"""Add a skip when a test line contains a skip directive."""
+ # Don't test on Python 2.6.
+ if sys.version_info[0] == 2 and sys.version_info[1] == 6:
+ return
+
adapter = Adapter(None)
result = self.factory.make_test_result()
skip_line = self.factory.make_ok(
@@ -64,6 +69,10 @@ class TestAdapter(TestCase):
def test_handles_ok_todo_test_line(self):
"""Add an unexpected success for an ok todo test line."""
+ # Don't test on Python 2.6.
+ if sys.version_info[0] == 2 and sys.version_info[1] == 6:
+ return
+
adapter = Adapter(None)
result = self.factory.make_test_result()
todo_line = self.factory.make_ok( | Handle Python <I> lack of support for unittest features. | python-tap_tappy | train |
01b82ce0dd6e95c05069f1616d74a74428cae2a8 | diff --git a/test/integration_test_helper.rb b/test/integration_test_helper.rb
index <HASH>..<HASH> 100644
--- a/test/integration_test_helper.rb
+++ b/test/integration_test_helper.rb
@@ -6,5 +6,6 @@ class ActionController::IntegrationTest
include Capybara::DSL
Capybara.default_driver = :selenium
+ Capybara.default_wait_time = 10
end
\ No newline at end of file | increase default wait time for failing tests. | ample_ample_assets | train |
ade13e8003574451c1c511760bee760e50788d05 | diff --git a/index.ios.js b/index.ios.js
index <HASH>..<HASH> 100644
--- a/index.ios.js
+++ b/index.ios.js
@@ -24,7 +24,8 @@ class CalendarSwiper extends React.Component {
super(props);
this.state = {
calendarDates: [moment().format()],
- selectedDate: null
+ selectedDate: null,
+ currentMonth: moment().format()
}
}
@@ -43,7 +44,7 @@ class CalendarSwiper extends React.Component {
<Text>Prev</Text>
</TouchableOpacity>
<Text style={styles.title}>
- {moment(date).format('MMMM YYYY')}
+ {moment(this.state.currentMonth).format('MMMM YYYY')}
</Text>
<TouchableOpacity style={styles.controls} onPress={this._onNext.bind(this)}>
<Text>Next</Text>
@@ -156,6 +157,7 @@ class CalendarSwiper extends React.Component {
console.log('Same Page - Returning false');
return false;
}
+ this.setState({ currentMonth: this.state.calendarDates[_currentMonthIndex]});
}
render() { | set current month as state parameter which will get updated after each action | christopherdro_react-native-calendar | train |
066ef5556cadd228c9d6126e4042178ec7546953 | diff --git a/aeron-driver/src/main/java/io/aeron/driver/media/UdpChannel.java b/aeron-driver/src/main/java/io/aeron/driver/media/UdpChannel.java
index <HASH>..<HASH> 100644
--- a/aeron-driver/src/main/java/io/aeron/driver/media/UdpChannel.java
+++ b/aeron-driver/src/main/java/io/aeron/driver/media/UdpChannel.java
@@ -40,6 +40,8 @@ import static java.net.InetAddress.getByAddress;
public final class UdpChannel
{
private static final AtomicInteger UNIQUE_CANONICAL_FORM_VALUE = new AtomicInteger();
+ private static final InetSocketAddress ANY_IPV4 = new InetSocketAddress("0.0.0.0", 0);
+ private static final InetSocketAddress ANY_IPV6 = new InetSocketAddress("::", 0);
private final boolean isManualControlMode;
private final boolean isDynamicControlMode;
@@ -153,7 +155,14 @@ public final class UdpChannel
if (null == endpointAddress)
{
hasExplicitEndpoint = false;
- endpointAddress = new InetSocketAddress("0.0.0.0", 0);
+ if (null != explicitControlAddress && explicitControlAddress.getAddress() instanceof Inet6Address)
+ {
+ endpointAddress = ANY_IPV6;
+ }
+ else
+ {
+ endpointAddress = ANY_IPV4;
+ }
}
final Context context = new Context()
@@ -171,7 +180,6 @@ public final class UdpChannel
if (endpointAddress.getAddress().isMulticastAddress())
{
- final InetSocketAddress controlAddress = getMulticastControlAddress(endpointAddress);
final InterfaceSearchAddress searchAddress = getInterfaceSearchAddress(channelUri);
final NetworkInterface localInterface = findInterface(searchAddress);
final InetSocketAddress resolvedAddress = resolveToAddressOfInterface(localInterface, searchAddress);
@@ -179,7 +187,7 @@ public final class UdpChannel
context
.isMulticast(true)
.localControlAddress(resolvedAddress)
- .remoteControlAddress(controlAddress)
+ .remoteControlAddress(getMulticastControlAddress(endpointAddress))
.localDataAddress(resolvedAddress)
.remoteDataAddress(endpointAddress)
.localInterface(localInterface)
@@ -218,7 +226,6 @@ public final class UdpChannel
else
{
final InterfaceSearchAddress searchAddress = getInterfaceSearchAddress(channelUri);
-
final InetSocketAddress localAddress = searchAddress.getInetAddress().isAnyLocalAddress() ?
searchAddress.getAddress() :
resolveToAddressOfInterface(findInterface(searchAddress), searchAddress);
diff --git a/aeron-driver/src/test/java/io/aeron/driver/UdpChannelTest.java b/aeron-driver/src/test/java/io/aeron/driver/UdpChannelTest.java
index <HASH>..<HASH> 100644
--- a/aeron-driver/src/test/java/io/aeron/driver/UdpChannelTest.java
+++ b/aeron-driver/src/test/java/io/aeron/driver/UdpChannelTest.java
@@ -54,6 +54,31 @@ public class UdpChannelTest
}
@Test
+ public void shouldHandleExplicitLocalControlAddressAndPortFormatIPv4()
+ {
+ final UdpChannel udpChannel = UdpChannel.parse("aeron:udp?control=localhost:40124|control-mode=dynamic");
+
+ assertThat(udpChannel.localData(), is(new InetSocketAddress("localhost", 40124)));
+ assertThat(udpChannel.localControl(), is(new InetSocketAddress("localhost", 40124)));
+ assertThat(udpChannel.remoteData(), is(new InetSocketAddress("0.0.0.0", 0)));
+ assertThat(udpChannel.remoteControl(), is(new InetSocketAddress("0.0.0.0", 0)));
+ }
+
+ @Test
+ public void shouldHandleExplicitLocalControlAddressAndPortFormatIPv6()
+ {
+ assumeTrue(System.getProperty("java.net.preferIPv4Stack") == null);
+
+ final UdpChannel udpChannel = UdpChannel.parse(
+ "aeron:udp?control=[fe80::5246:5dff:fe73:df06]:40124|control-mode=dynamic");
+
+ assertThat(udpChannel.localData(), is(new InetSocketAddress("fe80::5246:5dff:fe73:df06", 40124)));
+ assertThat(udpChannel.localControl(), is(new InetSocketAddress("fe80::5246:5dff:fe73:df06", 40124)));
+ assertThat(udpChannel.remoteData(), is(new InetSocketAddress("::", 0)));
+ assertThat(udpChannel.remoteControl(), is(new InetSocketAddress("::", 0)));
+ }
+
+ @Test
public void shouldNotAllowDynamicControlModeWithoutExplicitControl()
{
try
@@ -139,8 +164,7 @@ public class UdpChannelTest
@ParameterizedTest
@CsvSource("endpoint,interface")
- public void shouldParseValidMulticastAddressWithAeronUri(
- final String endpointKey, final String interfaceKey)
+ public void shouldParseValidMulticastAddressWithAeronUri(final String endpointKey, final String interfaceKey)
throws IOException
{
final UdpChannel udpChannel = UdpChannel.parse(
@@ -174,8 +198,7 @@ public class UdpChannelTest
@ParameterizedTest
@CsvSource("endpoint,interface")
- public void shouldHandleImpliedLocalPortFormatWithAeronUri(
- final String endpointKey, final String interfaceKey)
+ public void shouldHandleImpliedLocalPortFormatWithAeronUri(final String endpointKey, final String interfaceKey)
{
final UdpChannel udpChannel = UdpChannel.parse(
uri(endpointKey, "localhost:40124", interfaceKey, "localhost")); | [Java] Set ANY address for endpoint based on protocol family used for control address. Issue #<I>. | real-logic_aeron | train |
26d5d404a093152dec1f1225226206533375f7d0 | diff --git a/Helper/Config.php b/Helper/Config.php
index <HASH>..<HASH> 100755
--- a/Helper/Config.php
+++ b/Helper/Config.php
@@ -209,7 +209,7 @@ class Config extends \Magento\Framework\App\Helper\AbstractHelper
* ROI SECTION.
*/
const XML_PATH_CONNECTOR_ROI_TRACKING_ENABLED = 'connector_configuration/tracking/roi_enabled';
- const XML_PATH_CONNECTOR_PAGE_TRACKING_ENABLED = 'connector_roi_tracking/tracking/page_enabled';
+ const XML_PATH_CONNECTOR_PAGE_TRACKING_ENABLED = 'connector_configuration/tracking/page_enabled';
/**
* OAUTH | page tracking config path is wrong #<I> | dotmailer_dotmailer-magento2-extension | train |
ceffc5b5590e5cc518e09f898ac3500d2c49cbb3 | diff --git a/lib/active_mocker/ruby_parse.rb b/lib/active_mocker/ruby_parse.rb
index <HASH>..<HASH> 100644
--- a/lib/active_mocker/ruby_parse.rb
+++ b/lib/active_mocker/ruby_parse.rb
@@ -13,11 +13,11 @@ module ActiveMocker
end
def class_name
- Unparser.unparse(ast.to_a[0])
+ Unparser.unparse(find_class.to_a[0])
end
def parent_class_name
- Unparser.unparse(ast.to_a[1])
+ Unparser.unparse(find_class.to_a[1])
end
def has_parent_class?
@@ -44,6 +44,11 @@ module ActiveMocker
Unparser.unparse(new_ast)
end
+ def find_class
+ return ast if ast.type == :class
+ ast.to_a.select {|n| n.type == :class}.first
+ end
+
def ast
@ast ||= Parser::CurrentRuby.parse(source)
end
diff --git a/spec/lib/active_mocker/ruby_parse_spec.rb b/spec/lib/active_mocker/ruby_parse_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/active_mocker/ruby_parse_spec.rb
+++ b/spec/lib/active_mocker/ruby_parse_spec.rb
@@ -9,6 +9,7 @@ describe ActiveMocker::RubyParse do
it 'returns the parent class as a symbol' do
subject = described_class.new <<-RUBY
+ require 'uri-open'
class A < B
def method
end
@@ -23,6 +24,7 @@ describe ActiveMocker::RubyParse do
it 'returns the parent class as a symbol' do
subject = described_class.new <<-RUBY
+ require 'uri-open'
class A < B
def method
end | Add case where parsing class file when the class is not the first thing in the file. | zeisler_active_mocker | train |
88fe37646186b4b7e9b6546ef3f667165a8991aa | diff --git a/parseNitroApi.js b/parseNitroApi.js
index <HASH>..<HASH> 100644
--- a/parseNitroApi.js
+++ b/parseNitroApi.js
@@ -468,6 +468,39 @@ function processFeed(feed) {
path.get.description = feed.title;
path.get.tags = ['feeds'];
path.get.summary = feed.title;
+
+ // a long time ago, in a galaxy far, far away, the API had longer descriptions
+ if (feed.name == 'Programmes') {
+ path.get.description = 'Fetch metadata about Programmes (brands, series, episodes, clips). By applying different filter restrictions this feed can be used in many ways, for example to retrieve all series belonging to a brand, all the episodes and/or clips for a specific series, or any TLEO objects for a masterbrand. Other filters permit restricting to specific formats and/or genres, and you can request specific versions (for example Signed or Audio-Described). Parameters may be combined in any way suitable for your application.';
+ }
+ else if (feed.name == 'Broadcasts') {
+ path.get.description = 'Fetch metadata about linear Broadcasts and Services, allowing the generation of Television and Radio schedules and other datasets for broadcast items.';
+ }
+ else if (feed.name == 'Schedules') {
+ path.get.description = 'Dates, Times, Schedules: when and where are programmes being shown?';
+ }
+ else if (feed.name == 'Versions') {
+ path.get.description = 'Helps you handle the editorial "versions" of episodes (eg signed, cut for language, regional variations, etc)';
+ }
+ else if (feed.name == 'Services') {
+ path.get.description = 'Exposes both live and historical BBC services, across TV and Radio.';
+ }
+ else if (feed.name == 'People') {
+ path.get.description = 'Find the People PIPs knows about: casts, crews, contributors, guests, artists, singers, bands ...';
+ }
+ else if (feed.name == 'Availabilities') {
+ path.get.description = 'For advanced users only: get specific details around when programmes and clips are available to play';
+ }
+ else if (feed.name == 'Images') {
+ path.get.description = 'Find images, particularly those in galleries';
+ }
+ else if (feed.name == 'Promotions') {
+ path.get.description = 'Details of short-term editorially curated "promotions", for instance those programmes featured on iPlayer today';
+ }
+ else if (feed.name == 'Groups') {
+ path.get.description = 'Long-lived collections of programmes and more, including Collections, Seasons and Galleries';
+ }
+
path.get.operationId = 'list'+feed.name;
params = path.get.parameters = [];
@@ -478,6 +511,10 @@ function processFeed(feed) {
path.get.responses.default.description = 'Unexpected error';
path.get.responses.default.schema = {};
path.get.responses.default.schema['$ref'] = '#/definitions/ErrorModel';
+
+ if (feed.release_status == 'deprecated') {
+ path.get.deprecated = true;
+ }
if (feed.sorts) {
feed.sorts.sort = toArray(feed.sorts.sort); // only necessary if json api converted from xml | Add some more hard-coded path descriptions | MikeRalphson_bbcparse | train |
08b92545a8ed61861b53d59c6e5cb1755048232a | diff --git a/modules/layers/src/solid-polygon-layer/solid-polygon-layer.js b/modules/layers/src/solid-polygon-layer/solid-polygon-layer.js
index <HASH>..<HASH> 100644
--- a/modules/layers/src/solid-polygon-layer/solid-polygon-layer.js
+++ b/modules/layers/src/solid-polygon-layer/solid-polygon-layer.js
@@ -204,7 +204,7 @@ export default class SolidPolygonLayer extends Layer {
props.fp64 !== oldProps.fp64
) {
this.state.polygonTesselator.updatePositions({
- fp64: props.fp64,
+ fp64: this.use64bitPositions(),
extruded: props.extruded
});
} | Fix solid-polygon-layer to work with new coordinate mode (#<I>) | uber_deck.gl | train |
6a038c4729f0aa89f591c2c4a2545a319d5d3238 | diff --git a/src/mako/http/Request.php b/src/mako/http/Request.php
index <HASH>..<HASH> 100644
--- a/src/mako/http/Request.php
+++ b/src/mako/http/Request.php
@@ -111,6 +111,13 @@ class Request
protected $path;
/**
+ * Was this a "clean" request?
+ *
+ * @var string
+ */
+ protected $isClean = true;
+
+ /**
* Request language.
*
* @var array
@@ -239,6 +246,8 @@ class Request
if(stripos($path, '/index.php') === 0)
{
$path = mb_substr($path, 10);
+
+ $this->isClean = false;
}
$path = rawurldecode($path);
@@ -719,6 +728,16 @@ class Request
}
/**
+ * Returns true if the resource was requested with a "clean" URL and false if not.
+ *
+ * @return bool
+ */
+ public function isClean(): bool
+ {
+ return $this->isClean;
+ }
+
+ /**
* Returns the request language.
*
* @return array|null
diff --git a/src/mako/http/routing/Router.php b/src/mako/http/routing/Router.php
index <HASH>..<HASH> 100644
--- a/src/mako/http/routing/Router.php
+++ b/src/mako/http/routing/Router.php
@@ -49,7 +49,7 @@ class Router
{
return new Route([], '', function(Request $request) use ($requestPath)
{
- $url = $request->baseURL() . rtrim('/' . $request->languagePrefix(), '/') . $requestPath . '/';
+ $url = $request->baseURL() . ($request->isClean() ? '' : '/index.php') . rtrim('/' . $request->languagePrefix(), '/') . $requestPath . '/';
$get = $request->query->all();
diff --git a/tests/unit/http/routing/RouterTest.php b/tests/unit/http/routing/RouterTest.php
index <HASH>..<HASH> 100644
--- a/tests/unit/http/routing/RouterTest.php
+++ b/tests/unit/http/routing/RouterTest.php
@@ -131,6 +131,8 @@ class RouterTest extends PHPUnit_Framework_TestCase
$request->shouldReceive('path')->andReturn('/foo');
+ $request->shouldReceive('isClean')->andReturn(true);
+
$routed = $router->route($request);
$this->assertInstanceOf('\mako\http\routing\Route', $routed[0]);
@@ -177,6 +179,72 @@ class RouterTest extends PHPUnit_Framework_TestCase
/**
*
*/
+ public function testRedirectWithDirtyUrl()
+ {
+ $route = Mockery::mock('\mako\http\routing\Route');
+
+ $route->shouldReceive('getRegex')->andReturn('#^/foo$#s');
+
+ $route->shouldReceive('allows')->andReturn(true);
+
+ $route->shouldReceive('hasTrailingSlash')->andReturn(true);
+
+ $router = $this->getRouter([$route]);
+
+ $request = $this->getRequest();
+
+ $request->shouldReceive('method')->andReturn('GET');
+
+ $request->shouldReceive('path')->andReturn('/foo');
+
+ $request->shouldReceive('isClean')->andReturn(false);
+
+ $routed = $router->route($request);
+
+ $this->assertInstanceOf('\mako\http\routing\Route', $routed[0]);
+
+ $this->assertInstanceOf('Closure', $routed[0]->getAction());
+
+ $this->assertSame([], $routed[1]);
+
+ $this->assertEmpty($routed[0]->getRoute());
+
+ $this->assertEmpty($routed[0]->getMethods());
+
+ //
+
+ $closure = $routed[0]->getAction();
+
+ $request->shouldReceive('baseURL')->once()->andReturn('http://example.org');
+
+ $request->shouldReceive('languagePrefix')->once()->andReturn('en');
+
+ $query = Mockery::mock('mako\http\request\Parameters');
+
+ $query->shouldReceive('all')->once()->andReturn(['foo' => 'bar']);
+
+ $request->query = $query;
+
+ $returnValue = $closure($request);
+
+ $this->assertInstanceOf('mako\http\response\senders\Redirect', $returnValue);
+
+ //
+
+ $response = Mockery::mock('mako\http\Response');
+
+ $response->shouldReceive('status')->once()->with(301);
+
+ $response->shouldReceive('header')->once()->with('Location', 'http://example.org/index.php/en/foo/?foo=bar');
+
+ $response->shouldReceive('sendHeaders')->once();
+
+ $returnValue->send($request, $response);
+ }
+
+ /**
+ *
+ */
public function testOptionsRequest()
{
$route = Mockery::mock('\mako\http\routing\Route'); | Trailing slash redirects now also work with "dirty" URLs | mako-framework_framework | train |
a9d685675d1191032b19ec7aa86176812eacc3b9 | diff --git a/app/scripts/directives/info-window.js b/app/scripts/directives/info-window.js
index <HASH>..<HASH> 100644
--- a/app/scripts/directives/info-window.js
+++ b/app/scripts/directives/info-window.js
@@ -93,16 +93,15 @@
return template;
};
- infoWindow.__open = function(scope, anchor) {
- var _this = this;
+ infoWindow.__open = function(map, scope, anchor) {
$timeout(function() {
var tempTemplate = infoWindow.__template; // set template in a temporary variable
- infoWindow.__template = infoWindow.__eval.apply(_this);
+ anchor && (infoWindow.__template = infoWindow.__eval.apply(anchor));
infoWindow.__compile(scope);
if (anchor && anchor.getPosition) {
- infoWindow.open(infoWindow.map, anchor);
+ infoWindow.open(map, anchor);
} else {
- infoWindow.open(infoWindow.map);
+ infoWindow.open(map);
}
infoWindow.__template = tempTemplate; // reset template to the object
});
@@ -127,7 +126,7 @@
if (address) {
mapController.getGeoLocation(address).then(function(latlng) {
infoWindow.setPosition(latlng);
- infoWindow.__open(scope, latlng);
+ infoWindow.__open(mapController.map, scope, latlng);
var geoCallback = attrs.geoCallback;
geoCallback && $parse(geoCallback)(scope);
});
@@ -140,24 +139,22 @@
});
scope.$on('mapInitialized', function(evt, map) {
- infoWindow.map = map;
- infoWindow.visible && infoWindow.__open(scope);
+ infoWindow.visible && infoWindow.__open(map, scope);
if (infoWindow.visibleOnMarker) {
var markerId = infoWindow.visibleOnMarker;
- infoWindow.__open(scope, map.markers[markerId]);
+ infoWindow.__open(map, scope, map.markers[markerId]);
}
});
/**
* provide showInfoWindow method to scope
*/
- scope.showInfoWindow = scope.showInfoWindow ||
- function(event, id, marker) {
- var infoWindow = mapController.map.infoWindows[id];
- var anchor = marker ? marker :
- this.getPosition ? this : null;
- infoWindow.__open.apply(this, [scope, anchor]);
- };
+
+ scope.showInfoWindow = function(e, id, marker) {
+ var infoWindow = mapController.map.infoWindows[id];
+ var anchor = marker ? marker : (this.getPosition ? this : null);
+ infoWindow.__open(mapController.map, scope, anchor);
+ };
/**
* provide hideInfoWindow method to scope | issue #<I>, issue #<I>, fixed infowindow not setting map correctly. infoWindow.close() is setting infoWindow.map to null, so the next open is not possible because it tries to open on infoWindow.map | allenhwkim_angularjs-google-maps | train |
48fad2a214086d7dbe5b98ab4a8cd2e6f3cda1be | diff --git a/source/rafcon/gui/helpers/state.py b/source/rafcon/gui/helpers/state.py
index <HASH>..<HASH> 100644
--- a/source/rafcon/gui/helpers/state.py
+++ b/source/rafcon/gui/helpers/state.py
@@ -20,7 +20,7 @@ from rafcon.core.constants import UNIQUE_DECIDER_STATE_ID
from rafcon.gui import singleton as gui_singletons
import rafcon.gui.helpers.meta_data as gui_helper_meta_data
-from rafcon.gui.models import ContainerStateModel, AbstractStateModel, StateModel
+from rafcon.gui.models import ContainerStateModel, AbstractStateModel, StateModel, StateMachineModel
from rafcon.gui.models.signals import ActionSignalMsg
from rafcon.utils.vividict import Vividict
from rafcon.utils import log
@@ -231,10 +231,9 @@ def change_state_type(state_m, target_class):
if is_root_state:
state_machine_m = gui_singletons.state_machine_manager_model.get_state_machine_model(old_state_m)
+ assert isinstance(state_machine_m, StateMachineModel)
assert state_machine_m.root_state is old_state_m
-
-
# print "\n\nEMIT-BEFORE OLDSTATE\n\n"
old_state_m.action_signal.emit(ActionSignalMsg(action='change_root_state_type', origin='model',
action_parent_m=state_machine_m,
diff --git a/source/rafcon/gui/models/state_machine.py b/source/rafcon/gui/models/state_machine.py
index <HASH>..<HASH> 100644
--- a/source/rafcon/gui/models/state_machine.py
+++ b/source/rafcon/gui/models/state_machine.py
@@ -27,7 +27,7 @@ from rafcon.core.storage import storage
from rafcon.gui.config import global_gui_config
from rafcon.gui.models import ContainerStateModel, StateModel
from rafcon.gui.models.selection import Selection
-from rafcon.gui.models.signals import MetaSignalMsg, StateTypeChangeSignalMsg, ActionSignalMsg
+from rafcon.gui.models.signals import MetaSignalMsg
from rafcon.utils import log
from rafcon.utils import storage_utils
from rafcon.utils.hashable import Hashable
diff --git a/source/rafcon/gui/models/state_machine_manager.py b/source/rafcon/gui/models/state_machine_manager.py
index <HASH>..<HASH> 100644
--- a/source/rafcon/gui/models/state_machine_manager.py
+++ b/source/rafcon/gui/models/state_machine_manager.py
@@ -117,9 +117,20 @@ class StateMachineManagerModel(ModelMT, Observable):
sm_m.selection.clear()
def get_state_machine_model(self, state_m):
+ """ Get respective state machine model for handed state model
+
+ :param state_m: State model for which the state machine model should be found
+ :return: state machine model
+ :rtype: rafcon.gui.models.state_machine.StateMachineModel
+ """
return self.state_machines[state_m.state.get_state_machine().state_machine_id]
def get_selected_state_machine_model(self):
+ """ Get selected state machine model
+
+ :return: state machine model
+ :rtype: rafcon.gui.models.state_machine.StateMachineModel
+ """
if self.selected_state_machine_id is None:
return None
@@ -127,7 +138,9 @@ class StateMachineManagerModel(ModelMT, Observable):
@property
def selected_state_machine_id(self):
- """Property for the _selected_state_machine_id field"""
+ """Property for the _selected_state_machine_id field
+ :rtype: int
+ """
return self._selected_state_machine_id
@selected_state_machine_id.setter | clean signal imports and add docstrings in state machine manager model | DLR-RM_RAFCON | train |
9e532f2f9dbc21873a2d182c34908844f2e3913f | diff --git a/decoda/filters/EmailFilter.php b/decoda/filters/EmailFilter.php
index <HASH>..<HASH> 100644
--- a/decoda/filters/EmailFilter.php
+++ b/decoda/filters/EmailFilter.php
@@ -18,6 +18,16 @@ class EmailFilter extends DecodaFilter {
const EMAIL_PATTERN = '/(^|\n|\s)([-a-z0-9\.\+!]{1,64}+)@([-a-z0-9]+\.[a-z\.]+)/is';
/**
+ * Configuration.
+ *
+ * @access protected
+ * @var array
+ */
+ protected $_config = array(
+ 'encrypt' => true
+ );
+
+ /**
* Supported tags.
*
* @access protected
@@ -62,14 +72,19 @@ class EmailFilter extends DecodaFilter {
$email = $tag['attributes']['default'];
$default = true;
}
-
+
$encrypted = '';
- $length = strlen($email);
+
+ if ($this->_config['encrypt']) {
+ $length = strlen($email);
- if ($length > 0) {
- for ($i = 0; $i < $length; ++$i) {
- $encrypted .= '&#' . ord(substr($email, $i, 1)) . ';';
+ if ($length > 0) {
+ for ($i = 0; $i < $length; ++$i) {
+ $encrypted .= '&#' . ord(substr($email, $i, 1)) . ';';
+ }
}
+ } else {
+ $encrypted = $email;
}
$tag['attributes']['href'] = 'mailto:'. $encrypted; | Adding an encrypt config to the EmailFilter. | milesj_decoda | train |
21a3a4481874e3f6941ff8ec391d05900d54f7b3 | diff --git a/lib/dataElementListener.js b/lib/dataElementListener.js
index <HASH>..<HASH> 100644
--- a/lib/dataElementListener.js
+++ b/lib/dataElementListener.js
@@ -28,17 +28,15 @@ class DataElementImporter extends SHRDataElementParserListener {
this._currentGrammarVersion = '';
// The relative path to the current file
this._currentFile = '';
- // The index of the current definition in the file
- this._currentIndex = 0;
// The currently active definition (DataElement)
this._currentDef = null;
}
get specifications() { return this._specs; }
- importFile(file) {
- // Set current file;
- this._currentFile = file;
+ importFile(file, filePath) {
+ // Set current file, removing excess file path
+ this._currentFile = file.replace(filePath, '');
// Setup a child logger to associate logs with the current file
const lastLogger = logger;
@@ -103,11 +101,7 @@ class DataElementImporter extends SHRDataElementParserListener {
enterElementDef(ctx) {
const id = new Identifier(this._currentNs, ctx.elementHeader().simpleName().getText());
- this._currentDef = new DataElement(id, false, ctx.elementHeader().KW_ABSTRACT() != null)
- .withGrammarVersion(this._currentGrammarVersion)
- .withFilePath(this._currentFile)
- .withOrderIndex(this._currentIndex);
- this._currentIndex++;
+ this._currentDef = new DataElement(id, false, ctx.elementHeader().KW_ABSTRACT() != null).withGrammarVersion(this._currentGrammarVersion);
// Setup a child logger to associate logs with the current element
const lastLogger = logger;
@@ -129,11 +123,7 @@ class DataElementImporter extends SHRDataElementParserListener {
enterEntryDef(ctx) {
const id = new Identifier(this._currentNs, ctx.entryHeader().simpleName().getText());
- this._currentDef = new DataElement(id, true)
- .withGrammarVersion(this._currentGrammarVersion)
- .withFilePath(this._currentFile)
- .withOrderIndex(this._currentIndex);
- this._currentIndex++;
+ this._currentDef = new DataElement(id, true).withGrammarVersion(this._currentGrammarVersion);
if (ctx.entryHeader().simpleName().LOWER_WORD()) { logger.error('Entry Element name "%s" should begin with a capital letter. ERROR_CODE:11002', ctx.entryHeader().simpleName().getText()); }
}
@@ -556,8 +546,7 @@ class DataElementImporter extends SHRDataElementParserListener {
if (this._specs.dataElements.findByIdentifier(this._currentDef.identifier) != null) {
logger.error('Name "%s" already exists. ERROR_CODE:11033', this._currentDef.identifier.name);
}
- this._specs.dataElements.add(this._currentDef);
- this._currentDef = null;
+ this._specs.dataElements.add(this._currentDef, this._currentFile);
}
}
diff --git a/lib/import.js b/lib/import.js
index <HASH>..<HASH> 100644
--- a/lib/import.js
+++ b/lib/import.js
@@ -31,7 +31,7 @@ function importFromFilePath(filePath, configuration=[], specifications = new Spe
}
const importer = new DataElementImporter(preprocessor.data, specifications);
for (const file of filesByType.dataElement) {
- importer.importFile(file);
+ importer.importFile(file, filePath);
}
const mappingImporter = new MappingImporter(specifications);
for (const file of filesByType.map) { | Trim file path, refactor data element additions | standardhealth_shr-text-import | train |
7ef7c18c15696271721450d5922dbe84598a283e | diff --git a/sperment/observers.py b/sperment/observers.py
index <HASH>..<HASH> 100644
--- a/sperment/observers.py
+++ b/sperment/observers.py
@@ -105,4 +105,12 @@ class MongoDBReporter(ExperimentObserver):
self.experiment_entry['stop_time'] = fail_time
self.experiment_entry['info'] = info
self.experiment_entry['status'] = 'FAILED'
- self.save()
\ No newline at end of file
+ self.save()
+
+ def __eq__(self, other):
+ if not isinstance(other, MongoDBReporter):
+ return False
+ return self.collection == other.collection
+
+ def __ne__(self, other):
+ return not self.__eq__(other) | made MongoDBObservers comparable for equality | IDSIA_sacred | train |
7d91d054e95cce57dcb5222945e4b683aac0fc15 | diff --git a/request-callback/src/main/java/org/talend/esb/mep/requestcallback/impl/RequestCallbackInInterceptor.java b/request-callback/src/main/java/org/talend/esb/mep/requestcallback/impl/RequestCallbackInInterceptor.java
index <HASH>..<HASH> 100644
--- a/request-callback/src/main/java/org/talend/esb/mep/requestcallback/impl/RequestCallbackInInterceptor.java
+++ b/request-callback/src/main/java/org/talend/esb/mep/requestcallback/impl/RequestCallbackInInterceptor.java
@@ -147,7 +147,8 @@ public class RequestCallbackInInterceptor extends AbstractPhaseInterceptor<SoapM
BindingInfo bi = message.getExchange().getBinding().getBindingInfo();
callContext.setBindingId(bi == null
? "http://schemas.xmlsoap.org/wsdl/soap/" : bi.getBindingId());
- final Object wsdlLoc = message.getExchange().getEndpoint().get(Message.WSDL_DESCRIPTION);
+ //final Object wsdlLoc = message.getExchange().getEndpoint().get(Message.WSDL_DESCRIPTION);
+ final Object wsdlLoc = message.getContextualProperty("javax.xml.ws.wsdl.description");
if (wsdlLoc != null) {
try {
if (wsdlLoc instanceof URL) { | Reverted changes from previous commit to fix the build | Talend_tesb-rt-se | train |
c614a20e02cb8fd5531bce1adcb34a1210f79ac6 | diff --git a/lib/Doctrine/Common/ClassLoader.php b/lib/Doctrine/Common/ClassLoader.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/Common/ClassLoader.php
+++ b/lib/Doctrine/Common/ClassLoader.php
@@ -33,10 +33,25 @@ namespace Doctrine\Common;
*/
class ClassLoader
{
- private $fileExtension = '.php';
- private $namespace;
- private $includePath;
- private $namespaceSeparator = '\\';
+ /**
+ * @var string PHP file extension
+ */
+ protected $fileExtension = '.php';
+
+ /**
+ * @var string Current namespace
+ */
+ protected $namespace;
+
+ /**
+ * @var string Current include path
+ */
+ protected $includePath;
+
+ /**
+ * @var string PHP namespace separator
+ */
+ protected $namespaceSeparator = '\\';
/**
* Creates a new <tt>ClassLoader</tt> that loads classes of the | [DCOM-<I>] Increased visibility of members in ClassLoader in order to simplify extensibility through methods' override. | doctrine_common | train |
f540b0f4d8811c1c37b709b01c2216bb1184792e | diff --git a/lib/deploy.rb b/lib/deploy.rb
index <HASH>..<HASH> 100644
--- a/lib/deploy.rb
+++ b/lib/deploy.rb
@@ -122,10 +122,7 @@ module Deploy
end
def configuration
- return @configuration if @configuration
- @configuration = if fetch_eb
- S3::Configuration.new(settings['elasticbeanstalk_bucket_name'])
- else
+ @configuration ||=
S3::Configuration.new(config_bucket_name)
end
@@ -159,11 +156,7 @@ module Deploy
end
def deployment_target
- if fetch_eb
- select_app_name(eb_env_list(select_app_name(apps_list)))
- else
- select_app_name(apps_list)
- end
+ select_app_name(apps_list)
end
def eb_env_list(app) | Don't use the EB bucket as it is hacky and slow | sealink_deploy_aws | train |
af1fdfa680d953e7fe8b4ecd60e265d3f17632e2 | diff --git a/src/Model/Form.php b/src/Model/Form.php
index <HASH>..<HASH> 100644
--- a/src/Model/Form.php
+++ b/src/Model/Form.php
@@ -156,4 +156,110 @@ class Form extends Base
return false;
}
}
+
+ // --------------------------------------------------------------------------
+
+ /**
+ * Creates a new copy of an existing form
+ * @param integer $iFormId The ID of the form to duplicate
+ * @param boolean $bReturnObject Whether to return the entire new form object, or just the ID
+ * @param array $aReturnData An array to pass to the getById() call when $bReturnObject is true
+ * @return mixed
+ */
+ public function copy($iFormId, $bReturnObject = false, $aReturnData = array())
+ {
+ try {
+
+ // Begin the transaction
+ $oDb = Factory::service('Database');
+ $oDb->trans_begin();
+
+ // Check form exists
+ $oForm = $this->getById($iFormId, array('includeAll' => true));
+
+ if (empty($oForm)) {
+ throw new \Exception('Not a valid form ID.', 1);
+ }
+
+ // Duplicate the form, fields and options
+ $oFormFieldModel = Factory::model('FormField', 'nailsapp/module-form-builder');
+ $oFormFieldOptionModel = Factory::model('FormFieldOption', 'nailsapp/module-form-builder');
+
+ $sTableForm = $this->getTableName();
+ $sTableFields = $oFormFieldModel->getTableName();
+ $sTableOptions = $oFormFieldOptionModel->getTableName();
+
+ $oNow = Factory::factory('DateTime');
+ $sNow = $oNow->format('Y-m-d H:i:s');
+
+ // Form
+ $oDb->where('id', $oForm->id);
+ $oFormRow = $oDb->get($sTableForm)->row();
+
+ unset($oFormRow->id);
+ $oFormRow->created = $sNow;
+ $oFormRow->created_by = activeUser('id') ?: null;
+ $oFormRow->modified = $sNow;
+ $oFormRow->modified_by = activeUser('id') ?: null;
+
+ $oDb->set($oFormRow);
+ if (!$oDb->insert($sTableForm)) {
+ throw new \Exception('Failed to copy parent form record.', 1);
+ }
+
+ $iNewFormId = $oDb->insert_id();
+
+ // Fields
+ $oDb->where_in('form_id', $oForm->id);
+ $aFormFieldRows = $oDb->get($sTableFields)->result();
+ $aFormFieldIds = array();
+ foreach ($aFormFieldRows as $oRow) {
+
+ $iOldFieldId = $oRow->id;
+ unset($oRow->id);
+ $oRow->form_id = $iNewFormId;
+ $oRow->created = $sNow;
+ $oRow->created_by = activeUser('id') ?: null;
+ $oRow->modified = $sNow;
+ $oRow->modified_by = activeUser('id') ?: null;
+
+ $oDb->set($oRow);
+ if (!$oDb->insert($sTableFields)) {
+ throw new \Exception('Failed to copy form field record.', 1);
+ }
+
+ $iNewFieldId = $oDb->insert_id();
+
+ // Options
+ $oDb->where('form_field_id', $iOldFieldId);
+ $aFormOptionRows = $oDb->get($sTableOptions)->result_array();
+ if (!empty($aFormOptionRows)) {
+ foreach ($aFormOptionRows as &$aRow) {
+ unset($aRow['id']);
+ $aRow['form_field_id'] = $iNewFieldId;
+ $aRow['created'] = $sNow;
+ $aRow['created_by'] = activeUser('id') ?: null;
+ $aRow['modified'] = $sNow;
+ $aRow['modified_by'] = activeUser('id') ?: null;
+ }
+ unset($aRow);
+ if (!$oDb->insert_batch($sTableOptions, $aFormOptionRows)) {
+ throw new \Exception('Failed to copy form field option records.', 1);
+ }
+ }
+ }
+
+ // All done
+ $oDb->trans_commit();
+
+ // Return the new form's ID or object
+ return $bReturnObject ? $this->getById($iNewFormId, $aReturnData) : $iNewFormId;
+
+ } catch (\Exception $e) {
+
+ $oDb->trans_rollback();
+ $this->setError($e->getMessage());
+ return false;
+ }
+ }
} | Added `copy()` method | nails_module-form-builder | train |
91f8347500bf203d4cf06606d20dc9d141abf433 | diff --git a/internal/uidriver/glfw/ui.go b/internal/uidriver/glfw/ui.go
index <HASH>..<HASH> 100644
--- a/internal/uidriver/glfw/ui.go
+++ b/internal/uidriver/glfw/ui.go
@@ -1229,6 +1229,7 @@ func (u *UserInterface) setWindowSize(width, height int, fullscreen bool) {
case <-t.C:
break event
default:
+ time.Sleep(time.Millisecond)
}
}
u.window.SetFramebufferSizeCallback(nil) | internal/uidriver/glfw: Avoid busy loop by sleeping
Updates #<I> | hajimehoshi_ebiten | train |
9a4418da19feaa00bdfb1e8375d64c2170dadf14 | diff --git a/publify_textfilter_code/spec/lib/publify_app/textfilter_code_spec.rb b/publify_textfilter_code/spec/lib/publify_app/textfilter_code_spec.rb
index <HASH>..<HASH> 100644
--- a/publify_textfilter_code/spec/lib/publify_app/textfilter_code_spec.rb
+++ b/publify_textfilter_code/spec/lib/publify_app/textfilter_code_spec.rb
@@ -1,7 +1,6 @@
# frozen_string_literal: true
require "rails_helper"
-# require 'text_filter_textile'
require "publify_textfilter_markdown"
RSpec.describe "With the list of available filters", type: :model do
@@ -94,22 +93,8 @@ RSpec.describe "With the list of available filters", type: :model do
<p><em>footer text here</em></p>
HTML
- expects_textile = <<-HTML.strip_heredoc
- <p><strong>header text here</strong></p>
- <div class=\"CodeRay\"><pre><span class=\"CodeRay\"><span class=\"keyword\">class</span> <span class=\"class\">test</span>
- <span class=\"keyword\">def</span> <span class=\"function\">method</span>
- <span class=\"string\"><span class=\"delimiter\">"</span><span class=\"content\">foo</span><span class=\"delimiter\">"</span></span>
- <span class=\"keyword\">end</span>
- <span class=\"keyword\">end</span></span></pre></div>
- <p><em>footer text here</em></p>
- HTML
-
assert_equal expects_markdown.strip, filter_text(text,
[:macropre, :markdown, :macropost])
- ActiveSupport::Deprecation.silence do
- assert_equal expects_textile.strip, filter_text(text,
- [:macropre, :textile, :macropost])
- end
end
end
end
diff --git a/spec/models/text_filter_spec.rb b/spec/models/text_filter_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/text_filter_spec.rb
+++ b/spec/models/text_filter_spec.rb
@@ -198,23 +198,6 @@ RSpec.describe "With the list of available filters", type: :model do
"Ruby's creator</p></div></p>"
end
end
-
- describe "with textile" do
- it "correctly interprets the macro" do
- result = ActiveSupport::Deprecation.silence do
- filter_text(
- '<publify:flickr img="31366117" size="Square" style="float:left"/>',
- [:macropre, :textile, :macropost])
- end
- expect(result).to eq \
- '<div style="float:left" class="flickrplugin">' \
- '<a href="http://www.flickr.com/users/scottlaird/31366117">' \
- '<img src="//photos23.flickr.com/31366117_b1a791d68e_s.jpg"' \
- ' width="75" height="75" alt="Matz" title="Matz"/></a>' \
- "<p class=\"caption\" style=\"width:75px\">This is Matz, " \
- "Ruby's creator</p></div>"
- end
- end
end
end
end
diff --git a/spec/views/comments/html_sanitization_spec.rb b/spec/views/comments/html_sanitization_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/views/comments/html_sanitization_spec.rb
+++ b/spec/views/comments/html_sanitization_spec.rb
@@ -34,7 +34,7 @@ RSpec.describe "comments/_comment.html.erb", type: :view do
blog.theme = theme
end
- ["", "markdown", "textile", "smartypants", "markdown smartypants"].each do |value|
+ ["", "markdown", "smartypants", "markdown smartypants"].each do |value|
it "sanitizes content rendered with the #{value} textfilter" do
blog.comment_text_filter = value
@@ -167,7 +167,7 @@ RSpec.describe "comments/_comment.html.erb", type: :view do
blog.theme = theme
end
- ["", "markdown", "textile", "smartypants", "markdown smartypants"].each do |value|
+ ["", "markdown", "smartypants", "markdown smartypants"].each do |value|
it "sanitizes content rendered with the #{value} textfilter" do
blog.comment_text_filter = value | Remove specs that test behavior with textile filter | publify_publify | train |
33d649075a041bedbce65eec919c0014eec4e5ad | diff --git a/lib/providers/json-file.provider.js b/lib/providers/json-file.provider.js
index <HASH>..<HASH> 100644
--- a/lib/providers/json-file.provider.js
+++ b/lib/providers/json-file.provider.js
@@ -13,6 +13,7 @@ class JSONfileProvider extends Provider {
}
readFile(filePath) {
+ if(!filePath) { return; }
this.config = require(filePath);
}
diff --git a/package-lock.json b/package-lock.json
index <HASH>..<HASH> 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,6 +1,6 @@
{
"name": "muchconf",
- "version": "3.2.0",
+ "version": "3.3.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
diff --git a/tests/providers/json-file.provider.spec.js b/tests/providers/json-file.provider.spec.js
index <HASH>..<HASH> 100644
--- a/tests/providers/json-file.provider.spec.js
+++ b/tests/providers/json-file.provider.spec.js
@@ -36,4 +36,13 @@ test('should import config form js file', async (t) => {
active: true,
number: 44
});
+});
+
+test('should not import config if filepath is not provided', async (t) => {
+ const configProvider = new JSONfileProvider();
+
+ configProvider.init();
+ const config = await configProvider.load();
+
+ t.deepEqual(config, {});
});
\ No newline at end of file | json file provider should not import files if file path is empty | kmoskwiak_muchconf | train |
17c5a79c5c2391917553177da3d2839e7a8e5f26 | diff --git a/languagetool-language-modules/de/src/main/java/org/languagetool/language/German.java b/languagetool-language-modules/de/src/main/java/org/languagetool/language/German.java
index <HASH>..<HASH> 100644
--- a/languagetool-language-modules/de/src/main/java/org/languagetool/language/German.java
+++ b/languagetool-language-modules/de/src/main/java/org/languagetool/language/German.java
@@ -62,6 +62,14 @@ public class German extends Language implements AutoCloseable {
private GermanCompoundTokenizer strictCompoundTokenizer;
private LanguageModel languageModel;
+ /**
+ * @deprecated use {@link GermanyGerman}, {@link AustrianGerman}, or {@link SwissGerman} instead -
+ * they have rules for spell checking, this class doesn't (deprecated since 3.2)
+ */
+ @Deprecated
+ public German() {
+ }
+
@Override
public Language getDefaultLanguageVariant() {
return GERMANY_GERMAN;
diff --git a/languagetool-language-modules/en/src/main/java/org/languagetool/language/English.java b/languagetool-language-modules/en/src/main/java/org/languagetool/language/English.java
index <HASH>..<HASH> 100644
--- a/languagetool-language-modules/en/src/main/java/org/languagetool/language/English.java
+++ b/languagetool-language-modules/en/src/main/java/org/languagetool/language/English.java
@@ -60,6 +60,14 @@ public class English extends Language implements AutoCloseable {
private WordTokenizer wordTokenizer;
private LuceneLanguageModel languageModel;
+ /**
+ * @deprecated use {@link AmericanEnglish} or {@link BritishEnglish} etc. instead -
+ * they have rules for spell checking, this class doesn't (deprecated since 3.2)
+ */
+ @Deprecated
+ public English() {
+ }
+
@Override
public Language getDefaultLanguageVariant() {
return AMERICAN_ENGLISH; | [en] [de] deprecate the constructors that create a language object without spell checking rules - this regularly confused users | languagetool-org_languagetool | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.