hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
8c6e7ea4bf9da1606c77581d088a9d68a5facf06
|
diff --git a/cumulusci/tasks/bulkdata.py b/cumulusci/tasks/bulkdata.py
index <HASH>..<HASH> 100644
--- a/cumulusci/tasks/bulkdata.py
+++ b/cumulusci/tasks/bulkdata.py
@@ -227,8 +227,23 @@ class LoadData(BulkJobTaskMixin, BaseSalesforceApiTask):
"description": "If specified, skip steps before this one in the mapping",
"required": False,
},
+ "sqlite_load": {
+ "description": "If specified, an in memory sqlite database will be used and loaded from a sql script at the provided path",
+ }
}
+ def _init_options(self, kwargs):
+ super(LoadData, self)._init_options(kwargs)
+ if self.options.get("sqlite_load"):
+ if not self.options["database_url"].startswith("sqlite:"):
+ raise TaskOptionsError("The sqlite_load option can only be run against sqlite databases")
+ if os.sep != "/":
+ self.options["sqlite_load"] = self.options["sqlite_load"].replace("/", os.sep)
+ if not os.path.isfile(self.options["sqlite_load"]):
+ raise TaskOptionsError("File {} does not exist".format(self.options["sqlite_load"]))
+ self.logger.info("Using in-memory sqlite database")
+ self.options["database_url"] = "sqlite://"
+
def _run_task(self):
self._init_mapping()
self._init_db()
@@ -249,6 +264,10 @@ class LoadData(BulkJobTaskMixin, BaseSalesforceApiTask):
def _load_mapping(self, mapping):
"""Load data for a single step."""
+ if mapping["fields"].get("Id"):
+ mapping["oid_as_pk"] = True
+ else:
+ mapping["oid_as_pk"] = False
job_id, local_ids_for_batch = self._create_job(mapping)
result = self._wait_for_job(job_id)
# We store inserted ids even if some batches failed
@@ -355,7 +374,8 @@ class LoadData(BulkJobTaskMixin, BaseSalesforceApiTask):
# Use primary key instead of the field mapped to SF Id
fields = mapping["fields"].copy()
- del fields["Id"]
+ if mapping["oid_as_pk"]:
+ del fields["Id"]
id_column = model.__table__.primary_key.columns.keys()[0]
columns = [getattr(model, id_column)]
@@ -470,10 +490,26 @@ class LoadData(BulkJobTaskMixin, BaseSalesforceApiTask):
data_file = IteratorBytesIO(produce_csv())
self._sql_bulk_insert_from_csv(conn, id_table_name, columns, data_file)
+ def _sqlite_load(self):
+ conn = self.session.connection()
+ cursor = conn.connection.cursor()
+ with open(self.options["sqlite_load"], "r") as f:
+ try:
+ cursor.executescript(f.read())
+ finally:
+ cursor.close()
+ #self.session.flush()
+
def _init_db(self):
# initialize the DB engine
self.engine = create_engine(self.options["database_url"])
+ # initialize the DB session
+ self.session = Session(self.engine)
+
+ if self.options.get("sqlite_load"):
+ self._sqlite_load()
+
# initialize DB metadata
self.metadata = MetaData()
self.metadata.bind = self.engine
@@ -488,13 +524,6 @@ class LoadData(BulkJobTaskMixin, BaseSalesforceApiTask):
if "table" in mapping and mapping["table"] not in self.models:
self.models[mapping["table"]] = self.base.classes[mapping["table"]]
- # initialize the DB session
- self.session = Session(self.engine)
-
- import pdb
-
- pdb.set_trace()
-
def _init_mapping(self):
with open(self.options["mapping"], "r") as f:
self.mapping = ordered_yaml_load(f)
|
- Add `sqlite_load` option on LoadData which uses an in-memory sqlite
database populated from a SQL script at the path provided
|
SFDO-Tooling_CumulusCI
|
train
|
b8bdf486e8c6b2bd61980007660d2785986fb8f4
|
diff --git a/lib/Verifiers/Dns01.php b/lib/Verifiers/Dns01.php
index <HASH>..<HASH> 100644
--- a/lib/Verifiers/Dns01.php
+++ b/lib/Verifiers/Dns01.php
@@ -26,6 +26,11 @@ class Dns01 {
/** @var Resolver */
private $resolver;
+ /**
+ * Dns01 constructor.
+ *
+ * @param Resolver|null $resolver DNS resolver, otherwise a default resolver will be used
+ */
public function __construct(Resolver $resolver = null) {
$this->resolver = $resolver ?: \Amp\Dns\resolver();
}
diff --git a/lib/Verifiers/Http01.php b/lib/Verifiers/Http01.php
index <HASH>..<HASH> 100644
--- a/lib/Verifiers/Http01.php
+++ b/lib/Verifiers/Http01.php
@@ -11,6 +11,7 @@ namespace Kelunik\Acme\Verifiers;
use Amp\Artax\Client;
use Amp\Artax\Cookie\NullCookieJar;
+use Amp\Artax\HttpClient;
use Amp\Artax\Response;
use InvalidArgumentException;
use Kelunik\Acme\AcmeException;
@@ -23,7 +24,12 @@ use Kelunik\Acme\AcmeException;
class Http01 {
private $client;
- public function __construct(Client $client = null) {
+ /**
+ * Http01 constructor.
+ *
+ * @param HttpClient|null $client HTTP client to use, otherwise a default client will be used
+ */
+ public function __construct(HttpClient $client = null) {
$this->client = $client ?: new Client(new NullCookieJar);
}
|
Add missing constructor docblocks to verifiers
|
kelunik_acme
|
train
|
38e911ede43452b08c0fc775f3d965c950c67688
|
diff --git a/core/src/main/java/io/undertow/predicate/PredicateParser.java b/core/src/main/java/io/undertow/predicate/PredicateParser.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/io/undertow/predicate/PredicateParser.java
+++ b/core/src/main/java/io/undertow/predicate/PredicateParser.java
@@ -193,7 +193,8 @@ public class PredicateParser {
} else {
PredicateBuilder builder = builders.get(token.token);
if (builder == null) {
- throw error(string, token.position, "no predicate named " + token.token);
+
+ throw error(string, token.position, "no predicate named " + token.token + " known predicates: " + builders.keySet());
}
Token next = tokens.peek();
if (next.token.equals("[")) {
|
If wrong predicate name is used print a list of all known predicates
|
undertow-io_undertow
|
train
|
d31dede0c3b2dc3eb7983c44b168144761137a84
|
diff --git a/src/ParameterParser/ParameterClosure.php b/src/ParameterParser/ParameterClosure.php
index <HASH>..<HASH> 100644
--- a/src/ParameterParser/ParameterClosure.php
+++ b/src/ParameterParser/ParameterClosure.php
@@ -47,8 +47,24 @@ class ParameterClosure
$this->parameterClosure = $parameterClosure;
}
+ /**
+ * Add an alias and associate it with a prefix.
+ *
+ * @param string $prefix
+ * @param string $parameterName
+ */
public function addAlias($prefix, $parameterName)
{
$this->aliases[$prefix] = $parameterName;
}
+
+ /**
+ * Return true if this object is a Parent ParameterClosure.
+ *
+ * @return bool
+ */
+ public function isParent()
+ {
+ return $this->parent != null;
+ }
}
|
Added isParent function to ParameterClosure
|
nathan-fiscaletti_parameterparser
|
train
|
c43d79644075ab69d4d7cdcb57acb42a83406b6b
|
diff --git a/lib/rfunk/version.rb b/lib/rfunk/version.rb
index <HASH>..<HASH> 100644
--- a/lib/rfunk/version.rb
+++ b/lib/rfunk/version.rb
@@ -1,3 +1,3 @@
module RFunk
- VERSION = '0.8.0'
+ VERSION = '0.9.0'
end
|
Bumped version to <I>
|
alexfalkowski_rfunk
|
train
|
9f95e0a49cf47989daa93ce60cd12b1b9138764c
|
diff --git a/test/test_cheddargetter_client_ruby.rb b/test/test_cheddargetter_client_ruby.rb
index <HASH>..<HASH> 100644
--- a/test/test_cheddargetter_client_ruby.rb
+++ b/test/test_cheddargetter_client_ruby.rb
@@ -131,14 +131,14 @@ class TestCheddargetterClientRuby < Test::Unit::TestCase
assert_raises(CheddarGetter::ResponseException){ result.customer }
assert_equal true, result.valid?
- result = CG.get_plan(:id => "fe96b9e6-53a2-102e-b098-40402145ee8b")
+ result = CG.get_plan(:id => "a6a816c8-6d14-11e0-bcd4-40406799fa1e")
assert_equal 1, result.plans.size
assert_equal "Free Plan Test", result.plan("FREE_PLAN_TEST")[:name]
assert_equal true, result.valid?
result = CG.get_plan(:code => "NOT_A_PLAN")
assert_equal false, result.valid?
- assert_equal ["Plan not found for code=NOT_A_PLAN within productCode=GEM_TEST"], result.error_messages
+ assert_equal ["Plan not found for code=NOT_A_PLAN within productCode=RUBYGEM"], result.error_messages
end
should "create a single free customer at cheddar getter" do
|
Fixing the plan data to work with testing account.
|
expectedbehavior_cheddargetter_client_ruby
|
train
|
c03c315890db9d24ceaac640e5a819b37fa7bf16
|
diff --git a/lib/reda/importers/eit_fzj.py b/lib/reda/importers/eit_fzj.py
index <HASH>..<HASH> 100644
--- a/lib/reda/importers/eit_fzj.py
+++ b/lib/reda/importers/eit_fzj.py
@@ -482,18 +482,34 @@ def compute_data_errors(
ts_n = obj.data[index][row['n'] - 1, :]
ts_diff = (ts_m - ts_m.mean()) - (ts_n - ts_n.mean())
+ fdata = obj.frequency_data.iloc[index]
+ fs = fdata['sampling_frequency'] / fdata['oversampling']
+
fft, u_peaks, noise_level = obj._get_noise_level_from_fft(
- ts_diff
+ ts_diff,
+ fs=fs,
)
# now analyze the channels separately
level1 = obj.fft_analysis_one_channel(
index,
row['m'],
+ remove_excitation_frequency=kwargs.get(
+ 'remove_excitation_frequency', False
+ ),
+ remove_noise_harmonics=kwargs.get(
+ 'remove_noise_harmonics', False
+ ),
)[0]
level2 = obj.fft_analysis_one_channel(
index,
row['n'],
+ remove_excitation_frequency=kwargs.get(
+ 'remove_excitation_frequency', False
+ ),
+ remove_noise_harmonics=kwargs.get(
+ 'remove_noise_harmonics', False
+ ),
)[0]
# noise level of difference of both time series
@@ -519,7 +535,8 @@ def compute_data_errors(
ts_current = obj.data[index][41, :]
fft, u_peaks, noise_level_current = obj._get_noise_level_from_fft(
- ts_current - ts_current.mean()
+ ts_current - ts_current.mean(),
+ fs=fs,
)
noise_levels.append(noise_level_current / 1000)
|
[eit fzj] more noise characterization work
|
geophysics-ubonn_reda
|
train
|
e66f6d5820e663ad5d082b6565313b455c3928e5
|
diff --git a/modules/backend/ServiceProvider.php b/modules/backend/ServiceProvider.php
index <HASH>..<HASH> 100644
--- a/modules/backend/ServiceProvider.php
+++ b/modules/backend/ServiceProvider.php
@@ -24,7 +24,7 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register widgets
*/
- WidgetManager::instance()->registerFormWidgets(function($manager){
+ WidgetManager::instance()->registerFormWidgets(function ($manager) {
$manager->registerFormWidget('Backend\FormWidgets\CodeEditor', [
'label' => 'Code editor',
'alias' => 'codeeditor'
@@ -59,7 +59,7 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register navigation
*/
- BackendMenu::registerCallback(function($manager) {
+ BackendMenu::registerCallback(function ($manager) {
$manager->registerMenuItems('October.Backend', [
'dashboard' => [
'label' => 'backend::lang.dashboard.menu_label',
@@ -74,7 +74,7 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register settings
*/
- SettingsManager::instance()->registerCallback(function($manager){
+ SettingsManager::instance()->registerCallback(function ($manager) {
$manager->registerSettingItems('October.Backend', [
'editor' => [
'label' => 'backend::lang.editor.menu_label',
@@ -119,17 +119,23 @@ class ServiceProvider extends ModuleServiceProvider
/*
* Register permissions
*/
- BackendAuth::registerCallback(function($manager) {
+ BackendAuth::registerCallback(function ($manager) {
$manager->registerPermissions('October.Backend', [
- 'backend.access_dashboard' => ['label' => 'system::lang.permissions.view_the_dashboard', 'tab' => 'System'],
- 'backend.manage_users' => ['label' => 'system::lang.permissions.manage_other_administrators', 'tab' => 'System'],
+ 'backend.access_dashboard' => [
+ 'label' => 'system::lang.permissions.view_the_dashboard',
+ 'tab' => 'System'
+ ],
+ 'backend.manage_users' => [
+ 'label' => 'system::lang.permissions.manage_other_administrators',
+ 'tab' => 'System'
+ ],
]);
});
/*
* Register mail templates
*/
- MailTemplate::registerCallback(function($template){
+ MailTemplate::registerCallback(function ($template) {
$template->registerMailTemplates([
'backend::mail.invite' => 'Invitation for newly created administrators.',
'backend::mail.restore' => 'Password reset instructions for backend-end administrators.',
@@ -146,5 +152,4 @@ class ServiceProvider extends ModuleServiceProvider
{
parent::boot('backend');
}
-
}
diff --git a/modules/backend/routes.php b/modules/backend/routes.php
index <HASH>..<HASH> 100644
--- a/modules/backend/routes.php
+++ b/modules/backend/routes.php
@@ -3,12 +3,12 @@
/*
* Register Backend routes before all user routes.
*/
-App::before(function($request) {
+App::before(function ($request) {
/*
* Other pages
*/
- Route::group(['prefix' => Config::get('cms.backendUri', 'backend')], function() {
+ Route::group(['prefix' => Config::get('cms.backendUri', 'backend')], function () {
Route::any('{slug}', 'Backend\Classes\BackendController@run')->where('slug', '(.*)?');
});
|
Updating single files in backend
|
octobercms_october
|
train
|
d932896450c214e5aea77b42409a24102a6df579
|
diff --git a/aws/data_source_aws_vpc_ids.go b/aws/data_source_aws_vpc_ids.go
index <HASH>..<HASH> 100644
--- a/aws/data_source_aws_vpc_ids.go
+++ b/aws/data_source_aws_vpc_ids.go
@@ -3,6 +3,7 @@ package aws
import (
"fmt"
"log"
+ "time"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/hashicorp/terraform/helper/schema"
@@ -54,7 +55,7 @@ func dataSourceAwsVpcIDsRead(d *schema.ResourceData, meta interface{}) error {
vpcs = append(vpcs, *vpc.VpcId)
}
- d.SetId(vpcs[0])
+ d.SetId(time.Now().UTC().String())
d.Set("ids", vpcs)
return nil
|
issue <I> fix the state id
|
terraform-providers_terraform-provider-aws
|
train
|
59468c535ec098b7b20bc1f05b427462a61bbe81
|
diff --git a/addon/mixins/registration-actions.js b/addon/mixins/registration-actions.js
index <HASH>..<HASH> 100644
--- a/addon/mixins/registration-actions.js
+++ b/addon/mixins/registration-actions.js
@@ -8,19 +8,19 @@ export default Ember.Mixin.create({
_draft: Ember.computed.or('draft', 'model'),
/** Updates current registration metadata with new responses to questions.
**/
- _updateMetadata(d, u) {
- var map = new Map(Object.entries(u));
+ _updateMetadata(currentMetadata, newMetadata) {
+ var map = new Map(Object.entries(newMetadata));
for (let items of map.entries()) {
var key = items[0];
var value = items [1];
if (typeof (value) === 'object') {
- var r = this._updateMetadata(d[key] || {}, value);
- d[key] = r;
+ var newValue = this._updateMetadata(currentMetadata[key] || {}, value);
+ currentMetadata[key] = newValue;
} else {
- d[key] = u[key];
+ currentMetadata[key] = newMetadata[key];
}
}
- return d;
+ return currentMetadata;
},
_generateRegistrationPayload(draft, registrationChoice, liftEmbargo) {
var registrationPayload = {
|
Replace single letter variables with more descriptive names.
|
CenterForOpenScience_ember-osf
|
train
|
91e01d0225aae181fbc5bba0a424038c7a703f75
|
diff --git a/doc-src/SASS_CHANGELOG.md b/doc-src/SASS_CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/doc-src/SASS_CHANGELOG.md
+++ b/doc-src/SASS_CHANGELOG.md
@@ -10,6 +10,9 @@
* Compatibility with listen 3.
+* Parse a minus operator with no surrounding whitespace (e.g. 20px-10px) the
+ same regardless of whether it's being used in a static property.
+
## 3.4.15 (22 June 2015)
* Further improve rounding for various numeric operations.
diff --git a/lib/sass/scss/rx.rb b/lib/sass/scss/rx.rb
index <HASH>..<HASH> 100644
--- a/lib/sass/scss/rx.rb
+++ b/lib/sass/scss/rx.rb
@@ -96,8 +96,13 @@ module Sass
IMPORTANT = /!#{W}important/i
+ # A unit is like an IDENT, but disallows a hyphen followed by a digit.
+ # This allows "1px-2px" to be interpreted as subtraction rather than "1"
+ # with the unit "px-2px". It also allows "%".
+ UNIT = /-?#{NMSTART}(?:[a-zA-Z0-9_]|#{NONASCII}|#{ESCAPE}|-(?!\d))*|%/
+
UNITLESS_NUMBER = /(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?\d+)?/
- NUMBER = /#{UNITLESS_NUMBER}(?:#{IDENT}|%)?/
+ NUMBER = /#{UNITLESS_NUMBER}(?:#{UNIT})?/
PERCENTAGE = /#{UNITLESS_NUMBER}%/
URI = /url\(#{W}(?:#{STRING}|#{URL})#{W}\)/i
@@ -123,11 +128,6 @@ module Sass
OPTIONAL = /!#{W}optional/i
IDENT_START = /-|#{NMSTART}/
- # A unit is like an IDENT, but disallows a hyphen followed by a digit.
- # This allows "1px-2px" to be interpreted as subtraction rather than "1"
- # with the unit "px-2px". It also allows "%".
- UNIT = /-?#{NMSTART}(?:[a-zA-Z0-9_]|#{NONASCII}|#{ESCAPE}|-(?!\d))*|%/
-
IDENT_HYPHEN_INTERP = /-(#\{)/
STRING1_NOINTERP = /\"((?:[^\n\r\f\\"#]|#(?!\{)|#{ESCAPE})*)\"/
STRING2_NOINTERP = /\'((?:[^\n\r\f\\'#]|#(?!\{)|#{ESCAPE})*)\'/
diff --git a/test/sass/scss/rx_test.rb b/test/sass/scss/rx_test.rb
index <HASH>..<HASH> 100755
--- a/test/sass/scss/rx_test.rb
+++ b/test/sass/scss/rx_test.rb
@@ -141,6 +141,10 @@ class ScssRxTest < MiniTest::Test
assert_equal "foo\\00007fbar", Sass::SCSS::RX.escape_ident("foo\177bar")
end
+ def test_no_static_hyphenated_units
+ assert_no_match STATIC_VALUE, "20px-20px"
+ end
+
private
def assert_match(rx, str)
diff --git a/test/sass/scss/scss_test.rb b/test/sass/scss/scss_test.rb
index <HASH>..<HASH> 100755
--- a/test/sass/scss/scss_test.rb
+++ b/test/sass/scss/scss_test.rb
@@ -457,6 +457,15 @@ foo {a: 1 + // flang }
SCSS
end
+ def test_static_hyphenated_unit
+ assert_equal <<CSS, render(<<SCSS)
+foo {
+ a: 0px; }
+CSS
+foo {a: 10px-10px }
+SCSS
+ end
+
## Nested Rules
def test_nested_rules
|
Fix minus/hyphen ambiguity again.
Although in most places we disallowed hyphenated units, they were still
included in static value parsing. This meant that a property with no
other SassScript could still have <I>px-<I>px interpreted incorrectly.
See #<I> and #<I>.
|
sass_ruby-sass
|
train
|
131d3dd6b1fe616de971a472cdf89988c6d2c061
|
diff --git a/lib/kamerling/task_repo.rb b/lib/kamerling/task_repo.rb
index <HASH>..<HASH> 100644
--- a/lib/kamerling/task_repo.rb
+++ b/lib/kamerling/task_repo.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
require_relative 'new_repo'
+require_relative 'task'
module Kamerling
class TaskRepo < NewRepo
@@ -8,5 +9,9 @@ module Kamerling
@klass = Task
@table = db[:tasks]
end
+
+ def for_project(project_uuid)
+ table.where(project_uuid: project_uuid).all.map(&Task.method(:new))
+ end
end
end
diff --git a/test/kamerling/task_repo_test.rb b/test/kamerling/task_repo_test.rb
index <HASH>..<HASH> 100644
--- a/test/kamerling/task_repo_test.rb
+++ b/test/kamerling/task_repo_test.rb
@@ -2,6 +2,8 @@
require 'sequel'
require_relative '../test_helper'
+require_relative '../../lib/kamerling/project'
+require_relative '../../lib/kamerling/task'
require_relative '../../lib/kamerling/task_repo'
require_relative 'new_repo_behaviour'
@@ -27,5 +29,14 @@ module Kamerling
Sequel::Migrator.run db, path
db[:projects] << project.new_to_h
end
+
+ describe '#for_project' do
+ it 'returns all Tasks for the given Project UUID' do
+ db[:projects] << Project.new(name: 'another', uuid: 'other').new_to_h
+ table << { data: '', done: true, project_uuid: 'pUUID', uuid: 'tpUUID' }
+ table << { data: '', done: true, project_uuid: 'other', uuid: 'tother' }
+ _(repo.for_project('pUUID')).must_equal [Task.new(uuid: 'tpUUID')]
+ end
+ end
end
end
|
add TaskRepo#for_project
|
chastell_kamerling
|
train
|
00659d6a61e9b660f99d14b1dc3ebd3d6c362624
|
diff --git a/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/CommandGroup.java b/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/CommandGroup.java
index <HASH>..<HASH> 100755
--- a/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/CommandGroup.java
+++ b/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/CommandGroup.java
@@ -107,6 +107,14 @@ public class CommandGroup extends CommandBase
}
@Override
+ public void setParentBehaviour(MissionBehaviour mb)
+ {
+ super.setParentBehaviour(mb);
+ for (ICommandHandler han : this.handlers)
+ ((HandlerBase)han).setParentBehaviour(mb);
+ }
+
+ @Override
public void appendExtraServerInformation(HashMap<String, String> map)
{
for (ICommandHandler han : this.handlers)
diff --git a/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/TurnBasedCommandsImplementation.java b/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/TurnBasedCommandsImplementation.java
index <HASH>..<HASH> 100755
--- a/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/TurnBasedCommandsImplementation.java
+++ b/Minecraft/src/main/java/com/microsoft/Malmo/MissionHandlers/TurnBasedCommandsImplementation.java
@@ -10,7 +10,6 @@ import com.microsoft.Malmo.MalmoMod.IMalmoMessageListener;
import com.microsoft.Malmo.MalmoMod.MalmoMessageType;
import com.microsoft.Malmo.Schemas.MissionInit;
import com.microsoft.Malmo.Schemas.TurnBasedCommands;
-import com.microsoft.Malmo.Utils.ScreenHelper;
public class TurnBasedCommandsImplementation extends CommandGroup implements IMalmoMessageListener
{
@@ -36,7 +35,12 @@ public class TurnBasedCommandsImplementation extends CommandGroup implements IMa
{
MissionBehaviour subHandlers = new MissionBehaviour();
subHandlers.addExtraHandlers(handlers);
- this.addCommandHandler(subHandlers.commandHandler);
+ if (subHandlers.commandHandler != null)
+ {
+ if (subHandlers.commandHandler instanceof HandlerBase)
+ ((HandlerBase)subHandlers.commandHandler).setParentBehaviour(this.parentBehaviour());
+ this.addCommandHandler(subHandlers.commandHandler);
+ }
}
}
return true;
@@ -45,6 +49,7 @@ public class TurnBasedCommandsImplementation extends CommandGroup implements IMa
@Override
public void install(MissionInit missionInit)
{
+ super.install(missionInit);
this.parentBehaviour().addObservationProducer(this.observationProducer);
this.agentName = missionInit.getMission().getAgentSection().get(missionInit.getClientRole()).getName();
MalmoMod.MalmoMessageHandler.registerForMessage(this, MalmoMessageType.SERVER_YOUR_TURN);
@@ -53,18 +58,20 @@ public class TurnBasedCommandsImplementation extends CommandGroup implements IMa
@Override
public void deinstall(MissionInit missionInit)
{
+ super.deinstall(missionInit);
MalmoMod.MalmoMessageHandler.deregisterForMessage(this, MalmoMessageType.SERVER_YOUR_TURN);
}
@Override
public boolean isOverriding()
{
- return true;
+ return super.isOverriding();
}
@Override
public void setOverriding(boolean b)
{
+ super.setOverriding(b);
}
@Override
@@ -123,6 +130,7 @@ public class TurnBasedCommandsImplementation extends CommandGroup implements IMa
@Override
public void appendExtraServerInformation(HashMap<String, String> map)
{
+ super.appendExtraServerInformation(map);
// Tell the server that we want to be part of the turn schedule.
map.put("turnPosition", String.valueOf(this.requestedPosition));
}
|
Fix for turn scheduler command handler nesting (#<I>)
|
Microsoft_malmo
|
train
|
e8a50f5feaa01b99a4fbf4f558dd0b6c8f16d3b6
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java
index <HASH>..<HASH> 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/sql/filter/OSQLFilterCondition.java
@@ -300,11 +300,14 @@ public class OSQLFilterCondition {
if (iValue == null)
return null;
- if (iCurrentRecord != null && iCurrentRecord.getRecord().getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) {
- try {
- iCurrentRecord = iCurrentRecord.getRecord().load();
- } catch (ORecordNotFoundException e) {
- return null;
+ if (iCurrentRecord != null) {
+ iCurrentRecord = iCurrentRecord.getRecord();
+ if (iCurrentRecord!=null && ((ODocument)iCurrentRecord).getInternalStatus() == ORecordElement.STATUS.NOT_LOADED) {
+ try {
+ iCurrentRecord = iCurrentRecord.getRecord().load();
+ } catch (ORecordNotFoundException e) {
+ return null;
+ }
}
}
|
fix null pointer during traversal of missing record
when a linked record is deleted, trying to check a WHERE condition on
that caused a NullPointerException
|
orientechnologies_orientdb
|
train
|
6bea9293beba260d9ca193daa0921a24591155eb
|
diff --git a/tests/mobly/controllers/android_device_lib/adb_test.py b/tests/mobly/controllers/android_device_lib/adb_test.py
index <HASH>..<HASH> 100755
--- a/tests/mobly/controllers/android_device_lib/adb_test.py
+++ b/tests/mobly/controllers/android_device_lib/adb_test.py
@@ -56,22 +56,7 @@ MOCK_ADB_SHELL_COMMAND_CHECK = 'adb shell command -v ls'
class AdbTest(unittest.TestCase):
- """Unit tests for mobly.controllers.android_device_lib.adb.
- """
-
- def _mock_process(self, mock_psutil_process, mock_popen):
- # the created proc object in adb._exec_cmd()
- mock_proc = mock.Mock()
- mock_popen.return_value = mock_proc
-
- # the created process object in adb._exec_cmd()
- mock_psutil_process.return_value = mock.Mock()
-
- mock_proc.communicate = mock.Mock(
- return_value=(MOCK_DEFAULT_STDOUT.encode('utf-8'),
- MOCK_DEFAULT_STDERR.encode('utf-8')))
- mock_proc.returncode = 0
- return (mock_psutil_process, mock_popen)
+ """Unit tests for mobly.controllers.android_device_lib.adb."""
def _mock_execute_and_process_stdout_process(self, mock_popen):
# the created proc object in adb._execute_and_process_stdout()
|
Remove unreachable class method in AdbTest. (#<I>)
|
google_mobly
|
train
|
ca268aa3ec78a4174e2d4037dc06db258953a6ad
|
diff --git a/finders.go b/finders.go
index <HASH>..<HASH> 100644
--- a/finders.go
+++ b/finders.go
@@ -134,14 +134,19 @@ func (q Query) Count(model interface{}) (int, error) {
}
func (q Query) CountByField(model interface{}, field string) (int, error) {
+ tmpQuery := Q(q.Connection)
+ q.Clone(tmpQuery) //avoid mendling with original query
+
res := &rowCount{}
- err := q.Connection.timeFunc("Count", func() error {
- q.Paginator = nil
- col := fmt.Sprintf("count(%s) as row_count", field)
- q.orderClauses = clauses{}
- query, args := q.ToSQL(&Model{Value: model}, col)
- Log(query, args...)
- return q.Connection.Store.Get(res, query, args...)
+ err := tmpQuery.Connection.timeFunc("Count", func() error {
+ tmpQuery.Paginator = nil
+ tmpQuery.orderClauses = clauses{}
+ query, args := tmpQuery.ToSQL(&Model{Value: model})
+
+ countQuery := fmt.Sprintf("select count(%s) as row_count from (%s) a", field, query)
+
+ Log(countQuery, args...)
+ return q.Connection.Store.Get(res, countQuery, args...)
})
return res.Count, err
}
diff --git a/finders_test.go b/finders_test.go
index <HASH>..<HASH> 100644
--- a/finders_test.go
+++ b/finders_test.go
@@ -167,6 +167,10 @@ func Test_Count_RawQuery(t *testing.T) {
c, err = tx.RawQuery("select count(*) as row_count from users as users where id = -1").Count(nil)
a.NoError(err)
a.Equal(c, 0)
+
+ c, err = tx.RawQuery("select count(*) as row_count from (select id, name from users group by name asc) a").Count(nil)
+ a.NoError(err)
+ a.Equal(c, 0)
})
}
|
count works with group by on sqlite, mysql n postgresql
|
gobuffalo_pop
|
train
|
5c5300d3a9bb227f43346f8086d6cb6eca15ccd2
|
diff --git a/src/main/java/graphql/execution/ValuesResolver.java b/src/main/java/graphql/execution/ValuesResolver.java
index <HASH>..<HASH> 100644
--- a/src/main/java/graphql/execution/ValuesResolver.java
+++ b/src/main/java/graphql/execution/ValuesResolver.java
@@ -2,6 +2,7 @@ package graphql.execution;
import graphql.GraphQLException;
+import graphql.Internal;
import graphql.language.Argument;
import graphql.language.ArrayValue;
import graphql.language.NullValue;
@@ -27,6 +28,7 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
+@Internal
public class ValuesResolver {
|
ValuesResolver is an internal class
|
graphql-java_graphql-java
|
train
|
23911abd7f1120aa773587d60a8d7164054e8455
|
diff --git a/dropwizard-testing/src/test/java/io/dropwizard/testing/junit5/DropwizardExtensionsSupportTest.java b/dropwizard-testing/src/test/java/io/dropwizard/testing/junit5/DropwizardExtensionsSupportTest.java
index <HASH>..<HASH> 100644
--- a/dropwizard-testing/src/test/java/io/dropwizard/testing/junit5/DropwizardExtensionsSupportTest.java
+++ b/dropwizard-testing/src/test/java/io/dropwizard/testing/junit5/DropwizardExtensionsSupportTest.java
@@ -88,7 +88,7 @@ abstract class ParentClass_ChildHasExtension implements DelayedAssertionsTest {
}
@Nested
- public class NestedClass_OnlyInParent implements DelayedAssertionsTest {
+ class NestedClass_OnlyInParent implements DelayedAssertionsTest {
@Override
public List<Invokable> getDelayedAssertions() {
return ParentClass_ChildHasExtension.this.getDelayedAssertions();
@@ -96,7 +96,7 @@ abstract class ParentClass_ChildHasExtension implements DelayedAssertionsTest {
// This specific test failed due to issue: #4205
@Test
- public void onlyInParent() {
+ void onlyInParent() {
// when, then
getDelayedAssertions().add(() -> {
assertThat(getExtension().getBeforeInvocations()).isEqualTo(1);
@@ -136,14 +136,14 @@ abstract class ParentClass_ParentHasExtension implements DelayedAssertionsTest {
}
@Nested
- public class NestedClass_OnlyInParent implements DelayedAssertionsTest {
+ class NestedClass_OnlyInParent implements DelayedAssertionsTest {
@Override
public List<Invokable> getDelayedAssertions() {
return delayedAssertions;
}
@Test
- public void onlyInParent() {
+ void onlyInParent() {
// when, then
getDelayedAssertions().add(() -> {
assertThat(extension.getBeforeInvocations()).isEqualTo(1);
@@ -165,7 +165,7 @@ class DropwizardExtensionsSupport_ChildHasExtension_NestedUseTest implements Del
}
@Test
- public void regularTestMethod() {
+ void regularTestMethod() {
// when, then
delayedAssertions.add(() -> {
assertThat(extension.getBeforeInvocations()).isEqualTo(1);
@@ -174,14 +174,14 @@ class DropwizardExtensionsSupport_ChildHasExtension_NestedUseTest implements Del
}
@Nested
- public class NestedClass_Standalone implements DelayedAssertionsTest {
+ class NestedClass_Standalone implements DelayedAssertionsTest {
@Override
public List<Invokable> getDelayedAssertions() {
return delayedAssertions;
}
@Test
- public void nestedClassMethod() {
+ void nestedClassMethod() {
// when, then
delayedAssertions.add(() -> {
assertThat(extension.getBeforeInvocations()).isEqualTo(1);
@@ -191,7 +191,7 @@ class DropwizardExtensionsSupport_ChildHasExtension_NestedUseTest implements Del
}
@Nested
- public class NestedClass_Inheriting extends ParentClass_ChildHasExtension {
+ class NestedClass_Inheriting extends ParentClass_ChildHasExtension {
@Override
public List<Invokable> getDelayedAssertions() {
return delayedAssertions;
@@ -203,7 +203,7 @@ class DropwizardExtensionsSupport_ChildHasExtension_NestedUseTest implements Del
}
@Test
- public void childClassTestMethod() {
+ void childClassTestMethod() {
// when, then
delayedAssertions.add(() -> {
assertThat(extension.getBeforeInvocations()).isEqualTo(1);
@@ -240,7 +240,7 @@ class DropwizardExtensionsSupport_ChildHasExtension_OuterUseTest extends ParentC
}
@Test
- public void regularTestMethod() {
+ void regularTestMethod() {
// when, then
delayedAssertions.add(() -> {
assertThat(extension.getBeforeInvocations()).isEqualTo(1);
@@ -249,14 +249,14 @@ class DropwizardExtensionsSupport_ChildHasExtension_OuterUseTest extends ParentC
}
@Nested
- public class NestedClass_Standalone implements DelayedAssertionsTest {
+ class NestedClass_Standalone implements DelayedAssertionsTest {
@Override
public List<Invokable> getDelayedAssertions() {
return delayedAssertions;
}
@Test
- public void nestedClassMethod() {
+ void nestedClassMethod() {
// when, then
delayedAssertions.add(() -> {
assertThat(extension.getBeforeInvocations()).isEqualTo(1);
@@ -268,9 +268,9 @@ class DropwizardExtensionsSupport_ChildHasExtension_OuterUseTest extends ParentC
class DropwizardExtensionsSupport_ParentHasExtensionTest {
@Nested
- public class NestedClass_Inheriting extends ParentClass_ParentHasExtension {
+ class NestedClass_Inheriting extends ParentClass_ParentHasExtension {
@Test
- public void childClassTestMethod() {
+ void childClassTestMethod() {
// when, then
delayedAssertions.add(() -> {
assertThat(extension.getBeforeInvocations()).isEqualTo(1);
|
Remove public modifiers from nested test classes and test methods
|
dropwizard_dropwizard
|
train
|
9566d2dbb4c9e79e2314b7468e6263d080832306
|
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -114,6 +114,41 @@ Uber.prototype = {
get(this.getAuthToken(), u, callback);
},
+ /**
+ * getHistory Get the currently logged in user history
+ *
+ * @param Function A callback function which takes two paramenters
+ */
+ getHistory: function(callback) {
+ if (typeof callback === 'undefined') {
+ } else {
+ var u = url+((this.version == "v1") ? "v1.1" : this.version)+"/history",
+ tokenData = this.getAuthToken();
+ if (tokenData.type != "bearer") {
+ throw new Error("Invalid token type. Must use a token of type bearer.");
+ }
+ get(tokenData, u, callback);
+ }
+ },
+
+ /**
+ * getMe Get the currently logged in user profile.
+ *
+ * @param Function A callback function which takes two parameters
+ */
+ getMe: function(callback) {
+ if (typeof callback === 'undefined') {
+ throw new Error("Callback function undefined");
+ } else {
+ var u = url+this.version+"/me",
+ tokenData = this.getAuthToken();
+ if (tokenData.type != "bearer") {
+ throw new Error("Invalid token type. Must use a token of type bearer.");
+ }
+ get(tokenData, u, callback);
+ }
+ },
+
setBearerToken: function(token) {
this.bearer_token = token;
|
Updating to add user profile and user history functionality
|
nathanpdaniel_uber-api
|
train
|
edfc38f0f5f724ff52829a4af0a6b68335af3aae
|
diff --git a/score-api/src/main/java/io/cloudslang/score/api/EndBranchDataContainer.java b/score-api/src/main/java/io/cloudslang/score/api/EndBranchDataContainer.java
index <HASH>..<HASH> 100644
--- a/score-api/src/main/java/io/cloudslang/score/api/EndBranchDataContainer.java
+++ b/score-api/src/main/java/io/cloudslang/score/api/EndBranchDataContainer.java
@@ -32,6 +32,7 @@ import java.util.Map;
* A POJO which serves as an holder for the contexts and exception (if exists) of a finished branch
*/
public class EndBranchDataContainer implements Serializable {
+ private static final long serialVersionUID = -6628394134724967947L;
private final Map<String, Serializable> contexts;
private final Map<String, Serializable> systemContext;
private final String exception;
diff --git a/score-api/src/main/java/io/cloudslang/score/api/ExecutionStep.java b/score-api/src/main/java/io/cloudslang/score/api/ExecutionStep.java
index <HASH>..<HASH> 100644
--- a/score-api/src/main/java/io/cloudslang/score/api/ExecutionStep.java
+++ b/score-api/src/main/java/io/cloudslang/score/api/ExecutionStep.java
@@ -27,6 +27,7 @@ import java.util.Map;
public class ExecutionStep implements Serializable {
+ private static final long serialVersionUID = -2446600690127912598L;
private Long execStepId;
private ControlActionMetadata action;
diff --git a/score-api/src/main/java/io/cloudslang/score/api/StartBranchDataContainer.java b/score-api/src/main/java/io/cloudslang/score/api/StartBranchDataContainer.java
index <HASH>..<HASH> 100644
--- a/score-api/src/main/java/io/cloudslang/score/api/StartBranchDataContainer.java
+++ b/score-api/src/main/java/io/cloudslang/score/api/StartBranchDataContainer.java
@@ -30,6 +30,7 @@ import java.util.Map;
* A POJO containing all the data necessary to create a new branch
*/
public class StartBranchDataContainer implements Serializable{
+ private static final long serialVersionUID = -6196905538533507836L;
private final Long startPosition;
private final Long executionPlanId;
private final Map<String, Serializable> contexts;
diff --git a/score-api/src/main/java/io/cloudslang/score/events/ScoreEvent.java b/score-api/src/main/java/io/cloudslang/score/events/ScoreEvent.java
index <HASH>..<HASH> 100644
--- a/score-api/src/main/java/io/cloudslang/score/events/ScoreEvent.java
+++ b/score-api/src/main/java/io/cloudslang/score/events/ScoreEvent.java
@@ -25,7 +25,8 @@ import java.util.Map;
*/
public class ScoreEvent implements Serializable {
- private String eventType;
+ private static final long serialVersionUID = -9190059094032864954L;
+ private String eventType;
private String languageName;
private Serializable data;
private Map<String, ? extends Serializable> metadata;
|
added serialVersionUID to api classes
|
CloudSlang_score
|
train
|
0c4476d51998c53a77c276433905bb374005487b
|
diff --git a/python/thunder/utils/context.py b/python/thunder/utils/context.py
index <HASH>..<HASH> 100644
--- a/python/thunder/utils/context.py
+++ b/python/thunder/utils/context.py
@@ -2,7 +2,6 @@
import glob
import os
-import json
from numpy import int16, dtype, frombuffer, zeros, fromfile, asarray, mod, floor, ceil, shape, concatenate, prod
from pyspark import SparkContext
import urllib
@@ -192,7 +191,7 @@ class ThunderContext():
else:
raise NotImplementedError("dataset '%s' not availiable" % dataset)
- def convertStack(self, datafile, dims, savefile, nblocks=None, filerange=None):
+ def convertStacks(self, datafile, dims, savefile, nblocks=None, filerange=None):
"""
Convert data from binary stack files to reformatted flat binary files,
see also convertStack
@@ -215,7 +214,7 @@ class ThunderContext():
Indices of first and last file to include
"""
- rdd = self.importStackAsBlocks(datafile, dims, nblocks=nblocks, filerange=filerange)
+ rdd = self.importStacksAsBlocks(datafile, dims, nblocks=nblocks, filerange=filerange)
# save blocks of data to flat binary files
def writeblock(part, mat, path):
@@ -241,7 +240,7 @@ class ThunderContext():
f = open(os.path.join(savefile, 'SUCCESS.json'), 'w')
json.dump(logout, f, indent=2)
- def importStack(self, datafile, dims, nblocks=None, filerange=None, filter=None):
+ def importStacks(self, datafile, dims, nblocks=None, filerange=None, filter=None):
"""
Import data from binary stack files as an RDD,
see also convertStack
@@ -268,12 +267,12 @@ class ThunderContext():
data : RDD of (tuple, array) pairs
Parsed and preprocessed data
"""
- rdd = self.importStackAsBlocks(datafile, dims, nblocks=nblocks, filerange=filerange)
+ rdd = self.importStacksAsBlocks(datafile, dims, nblocks=nblocks, filerange=filerange)
nkeys = len(dims)
data = rdd.values().flatMap(lambda x: list(x)).map(lambda x: (tuple(x[0:nkeys].astype(int)), x[nkeys:]))
return preprocess(data, method=filter)
- def importStackAsBlocks(self, datafile, dims, nblocks=None, filerange=None):
+ def importStacksAsBlocks(self, datafile, dims, nblocks=None, filerange=None):
"""
Convert data from binary stack files to blocks of an RDD,
which can either be saved to flat binary files,
|
Renamed stack -> stacks
|
thunder-project_thunder
|
train
|
01707d71d9d184d4c5b9602c93c2e46c9010d711
|
diff --git a/airflow/hooks/dbapi_hook.py b/airflow/hooks/dbapi_hook.py
index <HASH>..<HASH> 100644
--- a/airflow/hooks/dbapi_hook.py
+++ b/airflow/hooks/dbapi_hook.py
@@ -18,6 +18,7 @@
from contextlib import closing
from datetime import datetime
from typing import Any, Optional
+from urllib.parse import quote_plus
from sqlalchemy import create_engine
@@ -78,7 +79,7 @@ class DbApiHook(BaseHook):
conn = self.get_connection(getattr(self, self.conn_name_attr))
login = ''
if conn.login:
- login = '{conn.login}:{conn.password}@'.format(conn=conn)
+ login = f'{quote_plus(conn.login)}:{quote_plus(conn.password)}@'
host = conn.host
if conn.port is not None:
host += f':{conn.port}'
diff --git a/tests/hooks/test_dbapi_hook.py b/tests/hooks/test_dbapi_hook.py
index <HASH>..<HASH> 100644
--- a/tests/hooks/test_dbapi_hook.py
+++ b/tests/hooks/test_dbapi_hook.py
@@ -165,6 +165,19 @@ class TestDbApiHook(unittest.TestCase):
)
self.assertEqual("conn_type://login:password@host:1/", self.db_hook.get_uri())
+ def test_get_uri_special_characters(self):
+ self.db_hook.get_connection = mock.MagicMock(
+ return_value=Connection(
+ conn_type="conn_type",
+ host="host",
+ login="logi#! n",
+ password="pass*! word",
+ schema="schema",
+ port=1,
+ )
+ )
+ self.assertEqual("conn_type://logi%23%21+n:pass%2A%21+word@host:1/schema", self.db_hook.get_uri())
+
def test_run_log(self):
statement = 'SQL'
self.db_hook.run(statement)
|
Improve support for special characters in DbApiHook.get_uri (#<I>)
|
apache_airflow
|
train
|
bf75c2be7ceed5293d1b26f7fe66cb1189e70529
|
diff --git a/src/kff.BindingView.js b/src/kff.BindingView.js
index <HASH>..<HASH> 100644
--- a/src/kff.BindingView.js
+++ b/src/kff.BindingView.js
@@ -841,7 +841,11 @@ kff.BindingView = kff.createClass(
for(i = 0, l = positions.length; i < l; i++)
{
el = positions[i].$element[0];
- parentNode.insertBefore(el, lastChild.nextSibling);
+
+ if(el !== lastChild.nextSibling)
+ {
+ parentNode.insertBefore(el, lastChild.nextSibling);
+ }
newBoundViews[i] = positions[i];
newBoundViews[i].setBindingIndex(i);
newBoundViews[i].refreshIndexedBinders(true);
@@ -1053,7 +1057,6 @@ kff.BindingView = kff.createClass(
refreshAll: function()
{
if(typeof this.refresh === 'function') this.refresh();
- this.rebindModels();
if(this.collectionBinder)
{
this.collectionBinder.collection = this.getModel(this.collectionBinder.collectionPathArray);
@@ -1062,6 +1065,7 @@ kff.BindingView = kff.createClass(
}
else
{
+ this.rebindModels();
this.refreshOwnBinders();
if(this.subviews !== null)
{
|
refactor(kff.BindingView#refreshBoundViewsAll): add check for not inserting node before itself so that collection is not superfluously rerendered when all items are replaced by new ones
|
karfcz_kff
|
train
|
5e12c8418578a26cc8a312be2f5002280de1ee88
|
diff --git a/backtrader/strategy.py b/backtrader/strategy.py
index <HASH>..<HASH> 100644
--- a/backtrader/strategy.py
+++ b/backtrader/strategy.py
@@ -34,7 +34,24 @@ from .trade import Trade
class _Template(object):
- pass
+
+ def __init__(self):
+ self.members = list()
+ self.names = list()
+
+ def __len__(self):
+ return len(self.members)
+
+ def addmember(self, name, member):
+ setattr(self, name, member)
+ self.members.append(member)
+ self.names.append(name)
+
+ def __getitem__(self, key):
+ return self.members[key]
+
+ def getitems(self):
+ return zip(self.names, self.members)
class MetaStrategy(StrategyBase.__class__):
@@ -61,6 +78,7 @@ class MetaStrategy(StrategyBase.__class__):
_obj._tradespending = list()
_obj.stats = _Template()
+ _obj.analyzers = _Template()
return _obj, args, kwargs
@@ -130,7 +148,7 @@ class Strategy(six.with_metaclass(MetaStrategy, StrategyBase)):
if not multi:
newargs = list(itertools.chain(self.datas, obsargs))
obs = obscls(*newargs, **obskwargs)
- setattr(self.stats, obsname, obs)
+ self.stats.addmember(obsname, obs)
return
setattr(self.stats, obsname, list())
|
Extension of Template to support iteration and names
|
backtrader_backtrader
|
train
|
80043eac634164631cd1f1bc64c22a17bcf0715d
|
diff --git a/molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlEntityFactory.java b/molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlEntityFactory.java
index <HASH>..<HASH> 100644
--- a/molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlEntityFactory.java
+++ b/molgenis-data-postgresql/src/main/java/org/molgenis/data/postgresql/PostgreSqlEntityFactory.java
@@ -182,54 +182,30 @@ public class PostgreSqlEntityFactory
{
EntityMetaData entityMeta = attr.getRefEntity();
Object value;
- if (attr.getOrderBy() != null)
+ String[][] mrefIdsAndOrder = (String[][]) arrayValue.getArray();
+ if (mrefIdsAndOrder.length > 0 && mrefIdsAndOrder[0][0] != null)
{
- String[] oneToManyIdStrings = (String[]) arrayValue.getArray();
- if (oneToManyIdStrings.length > 0)
+ if(attr.getOrderBy() == null)
{
- AttributeMetaData idAttr = entityMeta.getIdAttribute();
- Object[] oneToManyIds = new Object[oneToManyIdStrings.length];
- for (int i = 0; i < oneToManyIdStrings.length; ++i)
- {
- String oneToManyIdString = oneToManyIdStrings[i];
- Object oneToManyId =
- oneToManyIdString != null ? convertMrefIdValue(oneToManyIdString, idAttr) : null;
- oneToManyIds[i] = oneToManyId;
- }
-
- // convert ids to (lazy) entities
- value = entityManager.getReferences(entityMeta, asList(oneToManyIds));
+ Arrays.sort(mrefIdsAndOrder, (arr0, arr1) -> Integer.compare(Integer.valueOf(arr0[0]), Integer.valueOf(arr1[0])));
}
- else
+
+ AttributeMetaData idAttr = entityMeta.getIdAttribute();
+ Object[] mrefIds = new Object[mrefIdsAndOrder.length];
+ for (int i = 0; i < mrefIdsAndOrder.length; ++i)
{
- value = null;
+ String[] mrefIdAndOrder = mrefIdsAndOrder[i];
+ String mrefIdStr = mrefIdAndOrder[1];
+ Object mrefId = mrefIdStr != null ? convertMrefIdValue(mrefIdStr, idAttr) : null;
+ mrefIds[i] = mrefId;
}
+
+ // convert ids to (lazy) entities
+ value = entityManager.getReferences(entityMeta, asList(mrefIds));
}
else
{
- String[][] mrefIdsAndOrder = (String[][]) arrayValue.getArray();
- if (mrefIdsAndOrder.length > 0 && mrefIdsAndOrder[0][0] != null)
- {
- Arrays.sort(mrefIdsAndOrder,
- (arr0, arr1) -> Integer.compare(Integer.valueOf(arr0[0]), Integer.valueOf(arr1[0])));
-
- AttributeMetaData idAttr = entityMeta.getIdAttribute();
- Object[] mrefIds = new Object[mrefIdsAndOrder.length];
- for (int i = 0; i < mrefIdsAndOrder.length; ++i)
- {
- String[] mrefIdAndOrder = mrefIdsAndOrder[i];
- String mrefIdStr = mrefIdAndOrder[1];
- Object mrefId = mrefIdStr != null ? convertMrefIdValue(mrefIdStr, idAttr) : null;
- mrefIds[i] = mrefId;
- }
-
- // convert ids to (lazy) entities
- value = entityManager.getReferences(entityMeta, asList(mrefIds));
- }
- else
- {
- value = null;
- }
+ value = null;
}
return value;
}
diff --git a/molgenis-platform-integration-tests/src/test/java/org/molgenis/integrationtest/platform/PlatformIT.java b/molgenis-platform-integration-tests/src/test/java/org/molgenis/integrationtest/platform/PlatformIT.java
index <HASH>..<HASH> 100644
--- a/molgenis-platform-integration-tests/src/test/java/org/molgenis/integrationtest/platform/PlatformIT.java
+++ b/molgenis-platform-integration-tests/src/test/java/org/molgenis/integrationtest/platform/PlatformIT.java
@@ -1376,8 +1376,7 @@ public class PlatformIT extends AbstractTestNGSpringContextTests
@Test
public void testOneToManyInsert()
{
- //FIXME case 5 and 6: L2 Cache exception when findOneById()
- for (int i = 1; i <= 4; i++)
+ for (int i = 1; i <= 6; i++)
{
OneToManyTestHarness.AuthorsAndBooks authorsAndBooks = importAuthorsAndBooks(i);
|
Fix one-to-many with orderBy select
|
molgenis_molgenis
|
train
|
de56c6c31a202e2a190ffa3fc52745ef2970e307
|
diff --git a/src/vendors/howler.js b/src/vendors/howler.js
index <HASH>..<HASH> 100644
--- a/src/vendors/howler.js
+++ b/src/vendors/howler.js
@@ -1,5 +1,5 @@
/*!
- * howler.js v1.1.17
+ * howler.js v1.1.18
* howlerjs.com
*
* (c) 2013-2014, James Simpson of GoldFire Studios
@@ -16,20 +16,28 @@
var ctx = null,
usingWebAudio = true,
noAudio = false;
- if (typeof AudioContext !== 'undefined') {
- ctx = new AudioContext();
- } else if (typeof webkitAudioContext !== 'undefined') {
- ctx = new webkitAudioContext();
- } else if (typeof Audio !== 'undefined') {
+ try {
+ if (typeof AudioContext !== 'undefined') {
+ ctx = new AudioContext();
+ } else if (typeof webkitAudioContext !== 'undefined') {
+ ctx = new webkitAudioContext();
+ } else {
+ usingWebAudio = false;
+ }
+ } catch(e) {
usingWebAudio = false;
- try {
- new Audio();
- } catch(e) {
+ }
+
+ if (!usingWebAudio) {
+ if (typeof Audio !== 'undefined') {
+ try {
+ new Audio();
+ } catch(e) {
+ noAudio = true;
+ }
+ } else {
noAudio = true;
}
- } else {
- usingWebAudio = false;
- noAudio = true;
}
// create a master gain node
@@ -205,7 +213,7 @@
}
// loop through source URLs and pick the first one that is compatible
- for (var i=0; i<self._urls.length; i++) {
+ for (var i=0; i<self._urls.length; i++) {
var ext, urlItem;
if (self._format) {
@@ -242,6 +250,16 @@
loadBuffer(self, url);
} else {
var newNode = new Audio();
+
+ // listen for errors with HTML5 audio (http://dev.w3.org/html5/spec-author-view/spec.html#mediaerror)
+ newNode.addEventListener('error', function () {
+ if (newNode.error && newNode.error.code === 4) {
+ HowlerGlobal.noAudio = true;
+ }
+
+ self.on('loaderror', {type: newNode.error.code});
+ }, false);
+
self._audioNode.push(newNode);
// setup the new audio node
@@ -249,7 +267,7 @@
newNode._pos = 0;
newNode.preload = 'auto';
newNode.volume = (Howler._muted) ? 0 : self._volume * Howler.volume();
-
+
// add this sound to the cache
cache[url] = self;
@@ -406,7 +424,7 @@
if (node.readyState === 4) {
node.id = soundId;
node.currentTime = pos;
- node.muted = Howler._muted;
+ node.muted = Howler._muted || node.muted;
node.volume = self._volume * Howler.volume();
setTimeout(function() { node.play(); }, 0);
} else {
@@ -556,7 +574,7 @@
if (self._webAudio) {
activeNode.gain.value = 0;
} else {
- activeNode.volume = 0;
+ activeNode.muted = true;
}
}
@@ -585,7 +603,7 @@
if (self._webAudio) {
activeNode.gain.value = self._volume;
} else {
- activeNode.volume = self._volume;
+ activeNode.muted = false;
}
}
@@ -997,7 +1015,7 @@
var self = this,
events = self['_on' + event];
- if (typeof fn === "function") {
+ if (typeof fn === 'function') {
events.push(fn);
} else {
for (var i=0; i<events.length; i++) {
@@ -1193,9 +1211,9 @@
exports.Howler = Howler;
exports.Howl = Howl;
}
-
+
// define globally in case AMD is not available or available but not used
window.Howler = Howler;
window.Howl = Howl;
-
+
})();
\ No newline at end of file
|
Updated Howler version (to <I>)
|
melonjs_melonJS
|
train
|
20e36b3f9478a58ea9c4b10c729a7f670ec45534
|
diff --git a/lib/slop.rb b/lib/slop.rb
index <HASH>..<HASH> 100644
--- a/lib/slop.rb
+++ b/lib/slop.rb
@@ -109,6 +109,7 @@ private
option.argument_value = argument
option.callback.call(option.argument_value) if option.has_callback?
else
+ option.argument_value = nil
if option.accepts_optional_argument?
option.callback.call(nil) if option.has_callback?
else
diff --git a/test/option_test.rb b/test/option_test.rb
index <HASH>..<HASH> 100644
--- a/test/option_test.rb
+++ b/test/option_test.rb
@@ -77,4 +77,11 @@ class OptionTest < TestCase
assert_equal " --age Your age", slop.options[:age].to_s
assert_equal " -V, Display the version", slop.options[:V].to_s
end
+
+ test 'falls back to default option' do
+ slop = Slop.new
+ slop.opt :foo, :optional => true, :default => 'lee'
+ slop.parse %w/--foo/
+ assert_equal 'lee', slop[:foo]
+ end
end
|
argument_value should be nil if the option expects an argument and none is given, added tests
|
leejarvis_slop
|
train
|
a24e0509e5d7d56f3c3c74fc93debabee6cbb2e9
|
diff --git a/devassistant/gui/runWindow.py b/devassistant/gui/runWindow.py
index <HASH>..<HASH> 100644
--- a/devassistant/gui/runWindow.py
+++ b/devassistant/gui/runWindow.py
@@ -23,9 +23,10 @@ from devassistant import exceptions
from devassistant.package_managers import DependencyInstaller
class RunLoggingHandler(logging.Handler):
- def __init__(self, treeview):
+ def __init__(self, parent, treeview):
logging.Handler.__init__(self)
self.treeview = treeview
+ self.parent = parent
def utf8conv(self,x):
@@ -41,6 +42,7 @@ class RunLoggingHandler(logging.Handler):
last = itr
itr = model.iter_next(itr)
return last
+
def _add_row(self, record, treeStore, lastRow):
if record.levelname == "INFO":
# Create a new root tree element
@@ -59,7 +61,6 @@ class RunLoggingHandler(logging.Handler):
# Message is empty and is not add to tree
pass
else:
-
if getattr(record,'event_type',''):
if not record.event_type.startswith("dep_"):
self._add_row(record, treeStore, lastRow)
@@ -75,7 +76,7 @@ class runWindow(object):
self.cancelBtn = builder.get_object("cancelRunBtn")
self.infoBox = builder.get_object("infoBox")
self.scrolledWindow = builder.get_object("scrolledWindow")
- self.tlh = RunLoggingHandler(self.runTreeView)
+ self.tlh = RunLoggingHandler(self, self.runTreeView)
self.gui_helper = gui_helper
logger.addHandler(self.tlh)
FORMAT = "%(levelname)s %(message)s"
@@ -121,9 +122,14 @@ class runWindow(object):
response = dlg.run()
if response == Gtk.ResponseType.YES:
if self.thread.isAlive():
+ self.info_label.set_label('<span color="#FFA500">Canceling...</span>')
self.pr.stop()
+ self.info_label.set_label('<span color="#FF0000">Failed</span>')
+ else:
+ self.info_label.set_label('<span color="#008000">Done</span>')
self.cancelBtn.set_label("Close")
dlg.destroy()
+
else:
Gtk.main_quit()
@@ -142,4 +148,6 @@ class runWindow(object):
self.cancelBtn.set_label("Close")
Gdk.threads_leave()
except exceptions.ExecutionException:
+ self.cancelBtn.set_label("Close")
+ self.info_label.set_label('<span color="#FF0000">Failed</span>')
pass
|
When user cancel package installation or project creation fails then GUI is updated accordingly
|
devassistant_devassistant
|
train
|
c746c3c5c280c8f32c9a6df83683c4df4fee0b23
|
diff --git a/backbone.js b/backbone.js
index <HASH>..<HASH> 100644
--- a/backbone.js
+++ b/backbone.js
@@ -366,7 +366,7 @@
options = options ? _.clone(options) : {};
// If we're "wait"-ing to set changed attributes, validate early.
- if (options.wait) {
+ if (attrs && options.wait) {
if (!this._validate(attrs, options)) return false;
current = _.clone(this.attributes);
}
|
Fixes #<I>, model.save(null, {wait: true}) with validation
|
jashkenas_backbone
|
train
|
5af9a98ceeb50a0925319d782051a8a94e274661
|
diff --git a/src/Task/PhpCsAutoFixerV2.php b/src/Task/PhpCsAutoFixerV2.php
index <HASH>..<HASH> 100644
--- a/src/Task/PhpCsAutoFixerV2.php
+++ b/src/Task/PhpCsAutoFixerV2.php
@@ -6,8 +6,10 @@ use GrumPHP\Collection\FilesCollection;
use GrumPHP\Collection\ProcessArgumentsCollection;
use GrumPHP\Runner\TaskResult;
use GrumPHP\Task\Context\ContextInterface;
+use GrumPHP\Task\Context\GitPreCommitContext;
use GrumPHP\Task\Context\RunContext;
use GrumPHP\Task\PhpCsFixerV2;
+use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
@@ -37,39 +39,46 @@ class PhpCsAutoFixerV2 extends PhpCsFixerV2
$this->formatter->resetCounter();
- $arguments = $this->createProcess($config, true);
+ $process = $this->runProcess($context, $config, $files, true);
- if ($context instanceof RunContext && $config['config'] !== null) {
- $result = $this->runOnAllFiles($context, $arguments);
- }else {
- $result = $this->runOnChangedFiles($context, $arguments, $files);
- }
+ if (!$process->isSuccessful()) {
+
+ $toAdd = $files->map(function(SplFileInfo $file) {
+ return $file->getRelativePathname();
+ });
- if ($result->hasFailed()) {
- $arguments = $this->createProcess($config, false);
+ $this->runProcess($context, $config, $files, false);
- if ($context instanceof RunContext && $config['config'] !== null) {
- $this->runOnAllFiles($context, $arguments);
- }else {
- $this->runOnChangedFiles($context, $arguments, $files);
- }
+ exec(sprintf('git add %s', implode(' ', $toAdd->toArray())));
- $result = TaskResult::createNonBlockingFailed($this, $result->getContext(), $result->getMessage());
+ $process = $this->runProcess($context, $config, $files, false);
+ $messages = [$this->formatter->format($process)];
+ $suggestions = [$this->formatter->formatSuggestion($process)];
+ $errorMessage = $this->formatter->formatErrorMessage($messages, $suggestions);
+
+ return TaskResult::createNonBlockingFailed($this, $context, $errorMessage);
}
- return $result;
+ return TaskResult::createPassed($this, $context);
}
/**
- * @param $config
- * @param bool $dryRun
+ * @param \GrumPHP\Task\Context\ContextInterface $context
+ * @param $config
+ * @param $files
+ * @param $dryRun
*
* @return \GrumPHP\Collection\ProcessArgumentsCollection
*/
- private function createProcess($config, $dryRun)
+ private function runProcess(ContextInterface $context, $config, $files, $dryRun)
{
$arguments = $this->processBuilder->createArgumentsForCommand('php-cs-fixer');
$arguments->add('--format=json');
+
+ if ($dryRun) {
+ $arguments->add('--dry-run');
+ }
+
$arguments->addOptionalArgument('--allow-risky=%s', $config['allow_risky'] ? 'yes' : 'no');
$arguments->addOptionalArgument('--cache-file=%s', $config['cache_file']);
$arguments->addOptionalArgument('--config=%s', $config['config']);
@@ -82,28 +91,22 @@ class PhpCsAutoFixerV2 extends PhpCsFixerV2
));
}
+ $canUseIntersection = !($context instanceof RunContext) && $config['config_contains_finder'];
+
$arguments->addOptionalArgument('--using-cache=%s', $config['using_cache'] ? 'yes' : 'no');
- $arguments->addOptionalArgument('--path-mode=%s', $config['path_mode']);
+ $arguments->addOptionalArgument('--path-mode=intersection', $canUseIntersection);
$arguments->addOptionalArgument('--verbose', $config['verbose']);
$arguments->addOptionalArgument('--diff', $config['diff']);
- $arguments->addOptionalArgument('--dry-run', $dryRun);
$arguments->add('fix');
- return $arguments;
- }
-
- /**
- * {@inheritdoc}
- */
- protected function runOnChangedFiles(
- ContextInterface $context,
- ProcessArgumentsCollection $arguments,
- FilesCollection $files
- ) {
- $result = parent::runOnChangedFiles($context, $arguments, $files);
- foreach ($files as $file) {
- exec(sprintf('git add %s', $file->getRelativePathname()));
+ if ($context instanceof GitPreCommitContext || !$config['config_contains_finder']) {
+ $arguments->addFiles($files);
}
- return $result;
+
+ $process = $this->processBuilder->buildProcess($arguments);
+
+ $process->run();
+
+ return $process;
}
}
|
Feature: Be compatible with latest PHPCSFixerV2
|
wearejust_grumphp-extra-tasks
|
train
|
41404f70f5d8f74b04e7f0da6c830a1e9a3b5642
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -5,7 +5,7 @@
Express Access Control Lists (express-acl) enable you to manage the requests made to your express server. It makes use of ACL rules to protect your sever from unauthorized access. ACLs defines which user groups are granted access and the type of access they have against a specified resource. When a request is received against a resource, `express-acl` checks the corresponding ACL policy to verify if the requester has the necessary access permissions.
-##### What is ACL rules
+##### What are ACL rules
ACL is a set of rules that tell `express-acl` how to handle the requests made to your server against a specific resource. Think of them like road signs or traffic lights that control how your traffic flows in your app. ACL rules are defined in JSON or yaml syntax.
**Example**
@@ -82,7 +82,7 @@ Express acl uses the configuration approach to define access levels.
First step is to create a file called `nacl.json` and place this in the root folder. This is the file where we will define the roles that can access our application, and the policies that restrict or give access to certain resources. Take a look at the example below.
```json
-
+
[{
"group": "admin",
"permissions": [{
@@ -108,7 +108,7 @@ Express acl uses the configuration approach to define access levels.
Property | Type | Description
--- | --- | ---
- **group** | `string` | This property defines the access group to which a user can belong to e.g `user`, `guest`, `admin`, `trainer`. This may vary depending with the architecture of you application.
+ **group** | `string` | This property defines the access group to which a user can belong to e.g `user`, `guest`, `admin`, `trainer`. This may vary depending with the architecture of your application.
**permissions** | `Array` | This property contains an array of objects that define the resources exposed to a group and the methods allowed/denied
**resource** | `string` | This is the resource that we are either giving access to. e.g `blogs` for route `/api/blogs`, `users` for route `/api/users`. You can also specify a glob `*` for all resource/routes in your application(recommended for admin users only)
**methods** | `string or Array` | This are http methods that a user is allowed or denied from executing. `["POST", "GET", "PUT"]`. use glob `*` if you want to include all http methods.
@@ -147,7 +147,7 @@ express-acl depends on the role of each authenticated user to pick the correspon
There are two API methods for express-acl.
**config[type: function, params: filename<string>,path<string>, yml<boolean>, encoding, baseUrl]**
-
+
This methods loads the configuration json file. When this method it looks for `nacl.json` the root folder if path is not specified.
**filename**: Name of the ACL rule file e.g nacl.json
**path**: Location of the ACL rule file
@@ -193,7 +193,7 @@ This methods loads the configuration json file. When this method it looks for `n
```
**unless[type:function, params: function or object]**
- By default any route that has no defined policy against it is blocked, this means you can not access this route untill you specify a policy. This method enables you to exclude unprotected routes. This method uses express-unless package to achive this functionality. For more details on its usage follow this link [express-unless](https://github.com/jfromaniello/express-unless/blob/master/README.md)
+ By default any route that has no defined policy against it is blocked, this means you cannot access this route untill you specify a policy. This method enables you to exclude unprotected routes. This method uses express-unless package to achive this functionality. For more details on its usage follow this link [express-unless](https://github.com/jfromaniello/express-unless/blob/master/README.md)
```js
//assuming we want to hide /auth/google from express acl
@@ -224,7 +224,7 @@ Create `nacl.json` in your root folder
"action": "allow"
}]
}]
-
+
```
Require express-acl in your project router file.
@@ -245,7 +245,7 @@ Add the acl middleware
app.use(acl.authorize);
```
-For more details check the examples folder.[examples](https://github.com/andela-thomas/express-acl/tree/master/examples)
+For more details checkout the [examples folder](https://github.com/andela-thomas/express-acl/tree/master/examples).
# Contributions
Pull requests are welcome. If you are adding a new feature or fixing an as-yet-untested use case, please consider writing unit tests to cover your change(s). For more information visit the contributions [page](https://github.com/andela-thomas/express-acl/wiki/contributions)
diff --git a/tests/behavior/nacl.authorize.glob.spec.js b/tests/behavior/nacl.authorize.glob.spec.js
index <HASH>..<HASH> 100644
--- a/tests/behavior/nacl.authorize.glob.spec.js
+++ b/tests/behavior/nacl.authorize.glob.spec.js
@@ -39,7 +39,7 @@
done();
});
- it('Shoud deny access to resource /api/user/42', function(done) {
+ it('Should deny access to resource /api/user/42', function(done) {
req = httpMocks.createRequest({
method: 'POST',
url: '/api/users/42'
@@ -103,7 +103,7 @@
done();
});
- it('Shoud Deny Access to resource /api/user/42', function(done) {
+ it('Should Deny Access to resource /api/user/42', function(done) {
req = httpMocks.createRequest({
method: 'POST',
url: '/api/users/42'
diff --git a/tests/behavior/nacl.authorize.spec.js b/tests/behavior/nacl.authorize.spec.js
index <HASH>..<HASH> 100644
--- a/tests/behavior/nacl.authorize.spec.js
+++ b/tests/behavior/nacl.authorize.spec.js
@@ -121,7 +121,7 @@
done();
});
- it('Shoud allow access to /api/user/42', function(done) {
+ it('Should allow access to /api/user/42', function(done) {
req = httpMocks.createRequest({
method: 'POST',
url: '/api/users/42'
|
correct readme typos (#<I>)
* correct readme typos
* correct typos in tests
|
nyambati_express-acl
|
train
|
881d0cb11258e96caa056b66c28ede384fd4433d
|
diff --git a/bids/modeling/model_spec.py b/bids/modeling/model_spec.py
index <HASH>..<HASH> 100644
--- a/bids/modeling/model_spec.py
+++ b/bids/modeling/model_spec.py
@@ -22,7 +22,8 @@ def create_model_spec(df, model, *args, **kwargs):
"""
kind = model.get('type', 'glm').lower()
SpecCls = {
- 'glm': GLMMSpec
+ 'glm': GLMMSpec,
+ 'meta': MetaAnalysisSpec,
}[kind]
return SpecCls.from_df(df, model, *args, **kwargs)
@@ -273,6 +274,10 @@ s
return GLMMSpec(**kwargs)
+class MetaAnalysisSpec(GLMMSpec):
+ pass
+
+
class Term(object):
"""Represents a model term.
|
ENH: Add meta-analysis spec, currently alias for GLMM
|
bids-standard_pybids
|
train
|
ac2522dd4e0df32eeb1a6074fa54211cdc473a8e
|
diff --git a/lib/metriks/librato_metrics_reporter.rb b/lib/metriks/librato_metrics_reporter.rb
index <HASH>..<HASH> 100644
--- a/lib/metriks/librato_metrics_reporter.rb
+++ b/lib/metriks/librato_metrics_reporter.rb
@@ -84,6 +84,7 @@ module Metriks
time = @time_tracker.now_floored
@registry.each do |name, metric|
+ next if name.nil? || name.blank?
name = name.to_s.gsub(/ +/, '_')
if prefix
|
Skip metric if name is empty.
|
eric_metriks-librato_metrics
|
train
|
4841431b66488726ff5d990e3c51211da5b88591
|
diff --git a/app/drivers/mzidplus.py b/app/drivers/mzidplus.py
index <HASH>..<HASH> 100644
--- a/app/drivers/mzidplus.py
+++ b/app/drivers/mzidplus.py
@@ -3,6 +3,7 @@ from app.preparation import mzidplus as prep
from app.writers import mzidplus as writers
from app.readers import basereader
+
class MzidPlusDriver(base.BaseDriver):
def run(self):
self.get_psms()
@@ -47,8 +48,8 @@ class MzidPercoTSVDriver(MzidPlusDriver):
else:
seqlookup = None
- self.header = prep.get_header_from_mzidtsv(self.fn,
- self.multipsm_per_scan)
+ self.header = prep.get_header_with_percolator(self.fn,
+ self.multipsm_per_scan)
self.psms = prep.add_percolator_to_mzidtsv(self.idfn,
self.fn,
self.multipsm_per_scan,
diff --git a/app/preparation/mzidplus.py b/app/preparation/mzidplus.py
index <HASH>..<HASH> 100644
--- a/app/preparation/mzidplus.py
+++ b/app/preparation/mzidplus.py
@@ -74,13 +74,16 @@ def add_percolator_to_mzidtsv(mzidfn, tsvfn, multipsm, seqdb=None):
yield writelines
-def get_header_from_mzidtsv(fn, multipsm):
- with open(fn) as fp:
- line = next(fp)
- line = line.split('\t')
+def get_header_with_percolator(fn, multipsm=False):
+ header = get_header_from_mzidtsv(fn)
if multipsm is True:
# FIXME should this be here???
- # Maybe define perco header in a global.
- line.append('rank')
- line.extend(readers.PERCO_HEADER)
- return line
+ header.append('rank')
+ header.extend(readers.PERCO_HEADER)
+ return header
+
+
+def get_header_from_mzidtsv(fn):
+ with open(fn) as fp:
+ line = next(fp)
+ return line.split('\t')
|
Broke up header creation in two smaller methods
|
glormph_msstitch
|
train
|
372a62c1bb3bb663feee64b295d5b44154a62b78
|
diff --git a/src/transform/parse.js b/src/transform/parse.js
index <HASH>..<HASH> 100644
--- a/src/transform/parse.js
+++ b/src/transform/parse.js
@@ -1,18 +1,10 @@
import decompose, {identity} from "./decompose";
-var cssNode,
- cssRoot,
- cssView,
- svgNode;
+var svgNode;
export function parseCss(value) {
- if (value === "none") return identity;
- if (!cssNode) cssNode = document.createElement("DIV"), cssRoot = document.documentElement, cssView = document.defaultView;
- cssNode.style.transform = value;
- value = cssView.getComputedStyle(cssRoot.appendChild(cssNode), null).getPropertyValue("transform");
- cssRoot.removeChild(cssNode);
- value = value.slice(7, -1).split(",");
- return decompose(+value[0], +value[1], +value[2], +value[3], +value[4], +value[5]);
+ const m = new (typeof DOMMatrix === "function" ? DOMMatrix : WebKitCSSMatrix)(value + "");
+ return m.isIdentity ? identity : decompose(m.a, m.b, m.c, m.d, m.e, m.f);
}
export function parseSvg(value) {
|
Use DOMMatrix to parse CSS transforms.
|
d3_d3-interpolate
|
train
|
8083f9240354f491cc373b44d9e90506a9a06c33
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -17,17 +17,16 @@ module.exports.transports = {
module.exports.createReceiver = function( params ) {
var transConfig = params.transports;
- var transport;
var receiver = new this.Receiver({
baseDir: params.baseDir
});
- if ( transConfig.express ) {
- transport = new this.transports.receivers.Express( transConfig.express );
- transport.init( function() {
- receiver.addTransport( transport );
- });
+ for ( var name in transConfig ) {
+ if ( transConfig.hasOwnProperty( name ) && this.transports.receivers.hasOwnProperty( name ) ) {
+ receiver.addTransport( new this.transports.receivers[ name ]( transConfig[ name ] ) );
+ }
}
+ return receiver;
};
diff --git a/lib/receive.js b/lib/receive.js
index <HASH>..<HASH> 100644
--- a/lib/receive.js
+++ b/lib/receive.js
@@ -90,6 +90,14 @@ FlingReceiver.prototype.addTransport = function ( transport ) {
};
+FlingReceiver.prototype.init = function ( done ) {
+
+ async.each( this._transports, function( transport, next ) {
+ transport.init( next );
+ }, done );
+
+};
+
FlingReceiver.prototype._selectTransportEntry = function ( transport ) {
for ( var i = 0; i < this._transports.length; i++ ) {
|
Changed the create receiver method to use hasOwnProperty and moved the init transport functionality to the receiver class.
|
BlueRival_json-fling
|
train
|
fc3b0c02d5bc7389dc8b9d914dc03c42c70f94c9
|
diff --git a/core-bundle/CHANGELOG.md b/core-bundle/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/core-bundle/CHANGELOG.md
+++ b/core-bundle/CHANGELOG.md
@@ -2,6 +2,7 @@
### DEV
+ * Order the files by name when selecting folders in the file picker (see #1270).
* Optimize inserting keywords into tl_search_index (see #1277).
### 4.4.11 (2017-12-28)
diff --git a/core-bundle/src/Resources/contao/elements/ContentDownloads.php b/core-bundle/src/Resources/contao/elements/ContentDownloads.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/elements/ContentDownloads.php
+++ b/core-bundle/src/Resources/contao/elements/ContentDownloads.php
@@ -175,7 +175,7 @@ class ContentDownloads extends \ContentElement
// Folders
else
{
- $objSubfiles = \FilesModel::findByPid($objFiles->uuid);
+ $objSubfiles = \FilesModel::findByPid($objFiles->uuid, array('order' => 'name'));
if ($objSubfiles === null)
{
diff --git a/core-bundle/src/Resources/contao/elements/ContentGallery.php b/core-bundle/src/Resources/contao/elements/ContentGallery.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/elements/ContentGallery.php
+++ b/core-bundle/src/Resources/contao/elements/ContentGallery.php
@@ -119,7 +119,7 @@ class ContentGallery extends \ContentElement
// Folders
else
{
- $objSubfiles = \FilesModel::findByPid($objFiles->uuid);
+ $objSubfiles = \FilesModel::findByPid($objFiles->uuid, array('order' => 'name'));
if ($objSubfiles === null)
{
diff --git a/core-bundle/src/Resources/contao/modules/ModuleRandomImage.php b/core-bundle/src/Resources/contao/modules/ModuleRandomImage.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/modules/ModuleRandomImage.php
+++ b/core-bundle/src/Resources/contao/modules/ModuleRandomImage.php
@@ -98,7 +98,7 @@ class ModuleRandomImage extends \Module
// Folders
else
{
- $objSubfiles = \FilesModel::findByPid($objFiles->uuid);
+ $objSubfiles = \FilesModel::findByPid($objFiles->uuid, array('order' => 'name'));
if ($objSubfiles === null)
{
diff --git a/core-bundle/src/Resources/contao/widgets/FileTree.php b/core-bundle/src/Resources/contao/widgets/FileTree.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/widgets/FileTree.php
+++ b/core-bundle/src/Resources/contao/widgets/FileTree.php
@@ -264,7 +264,7 @@ class FileTree extends \Widget
{
if ($objFiles->type == 'folder')
{
- $objSubfiles = \FilesModel::findByPid($objFiles->uuid);
+ $objSubfiles = \FilesModel::findByPid($objFiles->uuid, array('order' => 'name'));
if ($objSubfiles === null)
{
|
[Core] Order the files by name when selecting folders in the file picker (see #<I>).
|
contao_contao
|
train
|
0018ebc2dbef986eba821db2b1b3c04014e17b5e
|
diff --git a/src/edeposit/amqp/harvester/scrappers/cpress_cz.py b/src/edeposit/amqp/harvester/scrappers/cpress_cz.py
index <HASH>..<HASH> 100755
--- a/src/edeposit/amqp/harvester/scrappers/cpress_cz.py
+++ b/src/edeposit/amqp/harvester/scrappers/cpress_cz.py
@@ -100,8 +100,37 @@ def _parse_price(html_chunk):
return get_first_content(price)
+def _match_table(th_content):
+ def _match_table_closure(element):
+ # I need <tr> tag
+ if element.getTagName() != "tr":
+ return False
+
+ # containing in first level of childs <th> tag
+ th = element.match("th", absolute=True)
+ if not th:
+ return False
+
+ # which's content match `th_content`
+ if th[0].getContent() != th_content:
+ return False
+
+ # and also contains <td> tag
+ if not element.match("td", absolute=True):
+ return False
+
+ return True
+
+ return _match_table_closure
+
+
def _parse_ean(html_chunk):
- pass
+ ean_tag = html_chunk.find("tr", fn=_match_table("EAN:"))
+
+ if not ean_tag:
+ return None
+
+ return get_first_content(ean_tag[0].find("td"))
def _parse_date(html_chunk):
|
#<I>: _parse_ean() is now working. Added _match_table() function.
|
edeposit_edeposit.amqp.harvester
|
train
|
ff612aee49deb31d65effdfadd6e98aef6d6308e
|
diff --git a/lib/podio/models/item.rb b/lib/podio/models/item.rb
index <HASH>..<HASH> 100644
--- a/lib/podio/models/item.rb
+++ b/lib/podio/models/item.rb
@@ -200,8 +200,13 @@ class Podio::Item < ActivePodio::Base
Podio.connection.post("/item/app/#{app_id}/cleanup_field_values").body
end
- def move_in_card_view(id)
- Podio.connection.post("/item/#{id}/cardview").body
+ def rearrange(id, attributes)
+ response = Podio.connection.post do |req|
+ req.url "/item/#{id}/rearrange"
+ req.body = attributes
+ end
+
+ member response.body
end
protected
|
Adjustments to the move method that has been renamed to rearrange and will now include a body and return a member.
|
podio_podio-rb
|
train
|
464eca2fa04b4b7958be0d7e914b6e5d7a441500
|
diff --git a/recorder/test/simplerec.py b/recorder/test/simplerec.py
index <HASH>..<HASH> 100644
--- a/recorder/test/simplerec.py
+++ b/recorder/test/simplerec.py
@@ -6,9 +6,27 @@ from recorder.redisindexer import WritableRedisIndexer
from recorder.warcwriter import MultiFileWARCWriter
from recorder.filters import SkipDupePolicy
+import atexit
+import tempfile
+import redis
+
upstream_url = 'http://localhost:8080'
-target = './_recordings/'
+target = tempfile.mkdtemp(prefix='tmprec') + '/'
+
+print('Recording to ' + target)
+
+def rm_target():
+ print('Removing ' + target)
+ shutil.rmtree(target)
+
+atexit.register(rm_target)
+
+local_r = redis.StrictRedis.from_url('redis://localhost/2')
+local_r.delete('rec:cdxj')
+local_r.delete('rec:warc')
+
+#target = './_recordings/'
dedup_index = WritableRedisIndexer(
redis_url='redis://localhost/2/rec:cdxj',
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -35,7 +35,7 @@ setup(
'proxy',
],
install_requires=[
- 'pywb==0.30.0',
+ 'pywb>=0.30.0',
],
dependency_links=[
'git+https://github.com/ikreymer/pywb.git@develop#egg=pywb-0.30.0-develop',
diff --git a/urlrewrite/test/simpleapp.py b/urlrewrite/test/simpleapp.py
index <HASH>..<HASH> 100644
--- a/urlrewrite/test/simpleapp.py
+++ b/urlrewrite/test/simpleapp.py
@@ -26,6 +26,14 @@ class RWApp(RewriterApp):
self.cookie_tracker = CookieTracker(redis)
+ self.orig_error_handler = self.app.default_error_handler
+ self.app.default_error_handler = self.err_handler
+
+ def err_handler(self, exc):
+ print(exc)
+ traceback.print_exc()
+ return self.orig_error_handler(exc)
+
def get_upstream_url(self, url, wb_url, closest, kwargs):
type = kwargs.get('type')
return self.upstream_urls[type].format(url=quote(url),
diff --git a/webagg/test/live.py b/webagg/test/live.py
index <HASH>..<HASH> 100644
--- a/webagg/test/live.py
+++ b/webagg/test/live.py
@@ -7,7 +7,7 @@ from webagg.indexsource import LiveIndexSource, RedisIndexSource
from webagg.aggregator import SimpleAggregator, CacheDirectoryIndexSource
def simpleapp():
- app = ResAggApp()
+ app = ResAggApp(debug=True)
app.add_route('/live',
DefaultResourceHandler(SimpleAggregator(
{'live': LiveIndexSource()})
|
test apps: enable debugging for test apps
test recorder: write to a temp dir for each run
|
webrecorder_pywb
|
train
|
fee4c9a7d94e4a44a3b54f04f4e6e17fe2dde3f5
|
diff --git a/pkg/kubelet/dockershim/helpers.go b/pkg/kubelet/dockershim/helpers.go
index <HASH>..<HASH> 100644
--- a/pkg/kubelet/dockershim/helpers.go
+++ b/pkg/kubelet/dockershim/helpers.go
@@ -213,6 +213,12 @@ func getSandboxSecurityOpts(sandboxConfig *runtimeApi.PodSandboxConfig, seccompP
}
func getNetworkNamespace(c *dockertypes.ContainerJSON) string {
+ if c.State.Pid == 0 {
+ // Docker reports pid 0 for an exited container. We can't use it to
+ // check the network namespace, so return an empty string instead.
+ glog.V(4).Infof("Cannot find network namespace for the terminated container %q", c.ID)
+ return ""
+ }
return fmt.Sprintf(dockerNetNSFmt, c.State.Pid)
}
diff --git a/pkg/kubelet/dockertools/docker_manager.go b/pkg/kubelet/dockertools/docker_manager.go
index <HASH>..<HASH> 100644
--- a/pkg/kubelet/dockertools/docker_manager.go
+++ b/pkg/kubelet/dockertools/docker_manager.go
@@ -2531,6 +2531,13 @@ func (dm *DockerManager) GetNetNS(containerID kubecontainer.ContainerID) (string
glog.Errorf("Error inspecting container: '%v'", err)
return "", err
}
+ if inspectResult.State.Pid == 0 {
+ // Docker reports pid 0 for an exited container. We can't use it to
+ // check the network namespace, so return an empty string instead.
+ glog.V(4).Infof("Cannot find network namespace for the terminated container %q", containerID.ID)
+ return "", nil
+ }
+
netnsPath := fmt.Sprintf(DockerNetnsFmt, inspectResult.State.Pid)
return netnsPath, nil
}
|
Return empty network namespace if the infra container has exited
If the infra container has already terminated, `docker inspect` will report
pid 0. The path constructed using the pid to check the network namespace of
the process will be invalid. This commit changes docker to report an empty
path to stop kubenet from erroring out whenever TearDown is called on an
exited infra container.
This is not a fix for all the plugins, as some plugins may require the actual
network namespace to tear down properly.
|
kubernetes_kubernetes
|
train
|
b0d2536e64ae5e0c8d7b35efd3ce8a0d88f516a4
|
diff --git a/nion/swift/DisplayPanel.py b/nion/swift/DisplayPanel.py
index <HASH>..<HASH> 100644
--- a/nion/swift/DisplayPanel.py
+++ b/nion/swift/DisplayPanel.py
@@ -551,7 +551,7 @@ class DataItemDataSourceDisplay:
elif len(displayed_dimensional_calibrations) == 1:
dimensional_calibration = displayed_dimensional_calibrations[0]
else:
- dimensional_calibration = displayed_dimensional_calibrations[1]
+ dimensional_calibration = displayed_dimensional_calibrations[-1]
display_canvas_item.update_image_display_state(lambda: display.preview_2d, display.preview_2d_shape, dimensional_calibration, metadata)
elif display_type == "line_plot":
display_properties = {"y_min": display.y_min, "y_max": display.y_max, "y_style": display.y_style, "left_channel": display.left_channel,
|
Use last dimension rather than hard coded dimension 1 for scale marker on images.
|
nion-software_nionswift
|
train
|
0438b2df13e08dd13d7071962cdd4bb975adbb4b
|
diff --git a/libraries/mako/Mako.php b/libraries/mako/Mako.php
index <HASH>..<HASH> 100644
--- a/libraries/mako/Mako.php
+++ b/libraries/mako/Mako.php
@@ -252,8 +252,8 @@ class Mako
$highlight = function($string)
{
- $search = array("\n", '<code>', '</code>', '<span style="color: #0000BB"><?php ', '#$@r4!/*');
- $replace = array('', '', '', '<span style="color: #0000BB">', '/*');
+ $search = array("\r\n", "\n\r", "\r", "\n", '<code>', '</code>', '<span style="color: #0000BB"><?php ', '#$@r4!/*');
+ $replace = array('', '', '', '', '', '', '<span style="color: #0000BB">', '/*');
return str_replace($search, $replace, highlight_string('<?php ' . str_replace('/*', '#$@r4!/*', $string), true));
};
|
Fixed syntax highlighting for code written on windows systems
|
mako-framework_framework
|
train
|
b3928e8371002707b6d5d404c0b6b6361da77f16
|
diff --git a/lib/polyamorous.rb b/lib/polyamorous.rb
index <HASH>..<HASH> 100644
--- a/lib/polyamorous.rb
+++ b/lib/polyamorous.rb
@@ -5,9 +5,11 @@ module Polyamorous
if defined?(::ActiveRecord::Associations::JoinDependency)
JoinDependency = ::ActiveRecord::Associations::JoinDependency
JoinAssociation = ::ActiveRecord::Associations::JoinDependency::JoinAssociation
+ JoinBase = ::ActiveRecord::Associations::JoinDependency::JoinBase
else
JoinDependency = ::ActiveRecord::Associations::ClassMethods::JoinDependency
JoinAssociation = ::ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation
+ JoinBase = ::ActiveRecord::Associations::ClassMethods::JoinDependency::JoinBase
end
end
@@ -17,3 +19,8 @@ require 'polyamorous/join_dependency'
Polyamorous::JoinDependency.send(:include, Polyamorous::JoinDependencyExtensions)
Polyamorous::JoinAssociation.send(:include, Polyamorous::JoinAssociationExtensions)
+Polyamorous::JoinBase.class_eval do
+ if method_defined?(:active_record)
+ alias_method :base_klass, :active_record
+ end
+end
diff --git a/lib/polyamorous/version.rb b/lib/polyamorous/version.rb
index <HASH>..<HASH> 100644
--- a/lib/polyamorous/version.rb
+++ b/lib/polyamorous/version.rb
@@ -1,3 +1,3 @@
module Polyamorous
- VERSION = "0.6.2"
+ VERSION = "0.6.3"
end
|
Alias base_klass to active_record on JoinBase.
Release <I>
|
activerecord-hackery_polyamorous
|
train
|
553fba1fd12b570147b33d61716823affa7b7d17
|
diff --git a/greenmail-core/src/test/java/com/icegreen/greenmail/test/ServerStartStopTest.java b/greenmail-core/src/test/java/com/icegreen/greenmail/test/ServerStartStopTest.java
index <HASH>..<HASH> 100644
--- a/greenmail-core/src/test/java/com/icegreen/greenmail/test/ServerStartStopTest.java
+++ b/greenmail-core/src/test/java/com/icegreen/greenmail/test/ServerStartStopTest.java
@@ -3,7 +3,6 @@ package com.icegreen.greenmail.test;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;
import com.icegreen.greenmail.util.ServerSetupTest;
-import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
@@ -14,7 +13,6 @@ import static org.junit.Assert.fail;
*/
public class ServerStartStopTest {
@Test
- @Ignore
public void testStartStop() {
GreenMail service = new GreenMail(ServerSetupTest.ALL);
try {
@@ -33,7 +31,6 @@ public class ServerStartStopTest {
}
@Test
- @Ignore
public void testServerStartupTimeout() {
// Create a few setups
ServerSetup setups[] = ServerSetupTest.ALL;
|
Remove ignore. Didn't help
|
greenmail-mail-test_greenmail
|
train
|
37e772e6a27ab319023e844e1de6132db418e06d
|
diff --git a/src/main/java/org/paylogic/fogbugz/FogbugzManager.java b/src/main/java/org/paylogic/fogbugz/FogbugzManager.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/paylogic/fogbugz/FogbugzManager.java
+++ b/src/main/java/org/paylogic/fogbugz/FogbugzManager.java
@@ -3,9 +3,6 @@ package org.paylogic.fogbugz;
import edu.umd.cs.findbugs.annotations.Nullable;
import lombok.Getter;
import lombok.extern.java.Log;
-import org.apache.http.NameValuePair;
-import org.apache.http.client.utils.URLEncodedUtils;
-import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
@@ -14,8 +11,10 @@ import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
+import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
+import java.net.URLEncoder;
import java.util.*;
import java.util.logging.Level;
@@ -82,15 +81,14 @@ public class FogbugzManager {
* @param params Map with parameters to encode.
* @return String which represents API URL.
*/
- private String mapToFogbugzUrl(Map<String, String> params) {
- List<NameValuePair> paramList = new ArrayList<NameValuePair>();
+ private String mapToFogbugzUrl(Map<String, String> params) throws UnsupportedEncodingException {
+ String output = this.getFogbugzUrl();
for (String key: params.keySet()) {
String value = params.get(key);
if (!value.isEmpty()) {
- paramList.add(new BasicNameValuePair(key, value));
+ output += "&" + URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8");
}
}
- String output = this.getFogbugzUrl() + "&" + URLEncodedUtils.format(paramList, '&', "UTF-8");
FogbugzManager.log.info("Generated URL to send to Fogbugz: " + output);
return output;
}
|
Remove dependencys, we can do without them
|
paylogic_java-fogbugz
|
train
|
01607e85d9f0aa53b35d67582403fee924ca7c31
|
diff --git a/tests/tests.py b/tests/tests.py
index <HASH>..<HASH> 100644
--- a/tests/tests.py
+++ b/tests/tests.py
@@ -260,7 +260,7 @@ class PhoneNumberFieldTestCase(TestCase):
)
-class PhonenumerFieldAppTest(TestCase):
+class PhoneNumberFieldAppTest(TestCase):
def test_save_field_to_database(self):
"""Basic Field Test"""
tm = models.TestModel()
|
Fix typo PhonenumberFieldAppTest
Reviewed-by: Stefan Foulis
|
stefanfoulis_django-phonenumber-field
|
train
|
c07608b294f58a44174f279e02c028b1de2ac049
|
diff --git a/pyang/translators/dsdl.py b/pyang/translators/dsdl.py
index <HASH>..<HASH> 100644
--- a/pyang/translators/dsdl.py
+++ b/pyang/translators/dsdl.py
@@ -161,6 +161,13 @@ class HybridDSDLSchema(object):
* `self.has_anyxml`: boolean flag indicating presence of the
'anyxml' statement in any input YANG module.
+ * `self.identities`: dictionary of identity names as keys and the
+ corresponding name pattern definitions as values.
+
+ * `self.identity_deps: dictionary showing the dependences among
+ identities - identity_name -> list of all identities that define
+ identity_name as their base.
+
* `self.local_defs`: dictionary of local named pattern
definitions. The keys are mangled names of the definitions.
|
DSDL: Updated comments - list of instance variables.
|
mbj4668_pyang
|
train
|
312a5a4201a7b0a192c0b47cc39145b5e6dfe071
|
diff --git a/src/Symfony/Component/Locale/Stub/StubIntlDateFormatter.php b/src/Symfony/Component/Locale/Stub/StubIntlDateFormatter.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Locale/Stub/StubIntlDateFormatter.php
+++ b/src/Symfony/Component/Locale/Stub/StubIntlDateFormatter.php
@@ -179,8 +179,17 @@ class StubIntlDateFormatter
}
// behave like the intl extension
+ $argumentError = null;
if (!is_int($timestamp) && version_compare(\PHP_VERSION, '5.3.4', '<')) {
- StubIntl::setError(StubIntl::U_ILLEGAL_ARGUMENT_ERROR, 'datefmt_format: takes either an array or an integer timestamp value ');
+ $argumentError = 'datefmt_format: takes either an array or an integer timestamp value ';
+ } elseif (!is_int($timestamp) && !$timestamp instanceOf \DateTime && version_compare(\PHP_VERSION, '5.3.4', '>=')) {
+ $argumentError = 'datefmt_format: takes either an array or an integer timestamp value or a DateTime object';
+ }
+
+ if (null !== $argumentError) {
+ StubIntl::setError(StubIntl::U_ILLEGAL_ARGUMENT_ERROR, $argumentError);
+ $this->errorCode = StubIntl::getErrorCode();
+ $this->errorMessage = StubIntl::getErrorMessage();
return false;
}
@@ -193,6 +202,11 @@ class StubIntlDateFormatter
$transformer = new FullTransformer($this->getPattern(), $this->getTimeZoneId());
$formatted = $transformer->format($this->createDateTime($timestamp));
+ // behave like the intl extension
+ StubIntl::setError(StubIntl::U_ZERO_ERROR);
+ $this->errorCode = StubIntl::getErrorCode();
+ $this->errorMessage = StubIntl::getErrorMessage();
+
return $formatted;
}
@@ -359,6 +373,7 @@ class StubIntlDateFormatter
$timestamp = $transformer->parse($dateTime, $value);
+ // behave like the intl extension. FullTransformer::parse() set the proper error
if (false === $timestamp) {
$this->errorCode = StubIntl::getErrorCode();
$this->errorMessage = StubIntl::getErrorMessage();
diff --git a/tests/Symfony/Tests/Component/Locale/Stub/StubIntlDateFormatterTest.php b/tests/Symfony/Tests/Component/Locale/Stub/StubIntlDateFormatterTest.php
index <HASH>..<HASH> 100644
--- a/tests/Symfony/Tests/Component/Locale/Stub/StubIntlDateFormatterTest.php
+++ b/tests/Symfony/Tests/Component/Locale/Stub/StubIntlDateFormatterTest.php
@@ -85,15 +85,26 @@ class StubIntlDateFormatterTest extends LocaleTestCase
/**
* @dataProvider formatErrorProvider
*/
+ public function testFormatErrorStub($pattern, $timestamp, $expected, $errorCode = 0, $errorMessage = 'U_ZERO_ERROR')
+ {
+ $formatter = $this->createStubFormatter($pattern);
+ $this->assertSame($expected, $formatter->format($timestamp));
+ $this->assertSame($errorMessage, StubIntl::getErrorMessage());
+ $this->assertSame($errorCode, StubIntl::getErrorCode());
+ $this->assertSame($errorCode != 0, StubIntl::isFailure(StubIntl::getErrorCode()));
+ $this->assertSame($errorMessage, $formatter->getErrorMessage());
+ $this->assertSame($errorCode, $formatter->getErrorCode());
+ $this->assertSame($errorCode != 0, StubIntl::isFailure($formatter->getErrorCode()));
+ }
+
+ /**
+ * @dataProvider formatErrorProvider
+ */
public function testFormatErrorIntl($pattern, $timestamp, $expected, $errorCode = 0, $errorMessage = 'U_ZERO_ERROR')
{
$this->skipIfIntlExtensionIsNotLoaded();
$this->skipIfICUVersionIsTooOld();
- if (version_compare(PHP_VERSION, '5.3.3') > 0) {
- $this->markTestSkipped('The intl error messages were change in PHP 5.3.3.');
- }
-
$formatter = $this->createIntlFormatter($pattern);
$this->assertSame($expected, $formatter->format($timestamp));
$this->assertSame($errorMessage, intl_get_error_message());
@@ -297,11 +308,15 @@ class StubIntlDateFormatterTest extends LocaleTestCase
public function formatErrorProvider()
{
- /* errors */
+ $message = 'datefmt_format: takes either an array or an integer timestamp value : U_ILLEGAL_ARGUMENT_ERROR';
+
+ if (version_compare(\PHP_VERSION, '5.3.4', '>=')) {
+ $message = 'datefmt_format: takes either an array or an integer timestamp value or a DateTime object: U_ILLEGAL_ARGUMENT_ERROR';
+ }
return array(
- array('y-M-d', '0', false, 1, 'datefmt_format: takes either an array or an integer timestamp value : U_ILLEGAL_ARGUMENT_ERROR'),
- array('y-M-d', 'foobar', false, 1, 'datefmt_format: takes either an array or an integer timestamp value : U_ILLEGAL_ARGUMENT_ERROR'),
+ array('y-M-d', '0', false, 1, $message),
+ array('y-M-d', 'foobar', false, 1, $message),
);
}
|
[Locale] fixed StubIntlDateFormatter::format() to set the right error for PHP >= <I> and to behave like the intl when formatting successfully
|
symfony_symfony
|
train
|
e3e0cd6848d4b2acb70047c092e39d7f782c8897
|
diff --git a/src/Rocketeer/TasksQueue.php b/src/Rocketeer/TasksQueue.php
index <HASH>..<HASH> 100644
--- a/src/Rocketeer/TasksQueue.php
+++ b/src/Rocketeer/TasksQueue.php
@@ -237,7 +237,7 @@ class TasksQueue
if (is_string($task)) {
$stringTask = $task;
$closure = function($task) use ($stringTask) {
- return $task->run($stringTask);
+ return $task->runForCurrentRelease($stringTask);
};
}
|
Make string tasks run in release folder by default
|
rocketeers_rocketeer
|
train
|
bdcf03fecab1f24133e9aca18930daa38d643305
|
diff --git a/mesh_tensorflow/transformer/transformer.py b/mesh_tensorflow/transformer/transformer.py
index <HASH>..<HASH> 100644
--- a/mesh_tensorflow/transformer/transformer.py
+++ b/mesh_tensorflow/transformer/transformer.py
@@ -377,7 +377,7 @@ class Unitransformer(object):
mesh, self.max_length_dim, self.model_dim, context.variable_dtype,
"positional_embedding")
slice_positional_embedding = context.position_is_default
- if (context.length_dim.size == self.max_length_dim.size and
+ if (context.length_dim.size < self.max_length_dim.size and
context.activation_dtype == tf.float32):
# This masks a bug.
# For some unknown reason the slice on TPU produces incorrect results
|
Fix to the bug workaround - it was wrong the first time.
PiperOrigin-RevId: <I>
|
tensorflow_mesh
|
train
|
e9edcc08ac6a7cbb49be66298dc16231fb3bf686
|
diff --git a/test/support/reporters/styled_reporter.rb b/test/support/reporters/styled_reporter.rb
index <HASH>..<HASH> 100644
--- a/test/support/reporters/styled_reporter.rb
+++ b/test/support/reporters/styled_reporter.rb
@@ -3,39 +3,36 @@ require 'minitest/reporters'
class StyledReporter < Minitest::Reporters::SpecReporter
# minitest-reporters methods for version 0.14.24
def pass(suite, test, test_runner)
- common_print(suite, test, test_runner, :green, 'PASS')
+ common_print(suite, test, :green, 'PASS')
end
def skip(suite, test, test_runner)
- common_print(suite, test, test_runner, :yellow, 'SKIP')
+ common_print(suite, test, :yellow, 'SKIP')
end
def failure(suite, test, test_runner)
- common_print(suite, test, test_runner, :red, 'FAIL')
+ common_print(suite, test, :red, 'FAIL')
print_exception(test_runner.exception)
end
def error(suite, test, test_runner)
- common_print(suite, test, test_runner, :red, 'ERROR')
+ common_print(suite, test, :red, 'ERROR')
print_exception(test_runner.exception)
end
# Just in case we load a more recent minitest-reporters v1
def record(test)
- super
+ Minitest::Reporters::BaseReporter.instance_method(:record).bind(self).call(test)
print pad_test(test.name) if test.failure
print_colored_status(test)
print(" (%.2fs)" % test.time)
print " :: #{test.name}" unless test.failure
puts
- if !test.skipped? && test.failure
- print_info(test.failure)
- puts
- end
+ print_exception(test.failure) if !test.skipped? && test.failure
end
private
- def common_print(suite, test, test_runner, color, message)
+ def common_print(suite, test, color, message)
print_suite(suite) unless @suites.include?(suite)
print pad_test(test) if color.eql?(:red)
print( send(color) { pad_mark(message) } )
|
Updated for both minitest-reporters <I> and <I>
|
danielpclark_PolyBelongsTo
|
train
|
406880c95358f39365ecf1c06f4140d25ca7995d
|
diff --git a/lib/ffaker/airline.rb b/lib/ffaker/airline.rb
index <HASH>..<HASH> 100644
--- a/lib/ffaker/airline.rb
+++ b/lib/ffaker/airline.rb
@@ -6,11 +6,11 @@ module FFaker
extend self
def name
- NAMES_LIST.sample
+ fetch_sample(NAMES_LIST)
end
def flight_number
- "#{CODES_LIST.sample} #{rand(1..3999)}"
+ "#{fetch_sample(CODES_LIST)} #{rand(1..3999)}"
end
end
end
diff --git a/test/test_airline.rb b/test/test_airline.rb
index <HASH>..<HASH> 100644
--- a/test/test_airline.rb
+++ b/test/test_airline.rb
@@ -3,6 +3,10 @@
require 'helper'
class TestAirline < Test::Unit::TestCase
+ include DeterministicHelper
+
+ assert_methods_are_deterministic(FFaker::Airline, :name, :flight_number)
+
def test_name
assert_match(/\A.+\z/, FFaker::Airline.name)
end
diff --git a/test/test_avatar.rb b/test/test_avatar.rb
index <HASH>..<HASH> 100644
--- a/test/test_avatar.rb
+++ b/test/test_avatar.rb
@@ -1,8 +1,12 @@
require 'helper'
class TestAvatar < Test::Unit::TestCase
+ include DeterministicHelper
+
ROBOHASH = 'https://robohash.org'.freeze
+ assert_methods_are_deterministic(FFaker::Avatar, :image)
+
def setup
@tester = FFaker::Avatar
end
|
Updated remaining "A*" modules to be deterministic.
|
ffaker_ffaker
|
train
|
fd283af193871a9412f5d7a719b8b74042e3ab4f
|
diff --git a/moco-runner/src/main/java/com/github/dreamhead/moco/parser/CollectionReader.java b/moco-runner/src/main/java/com/github/dreamhead/moco/parser/CollectionReader.java
index <HASH>..<HASH> 100644
--- a/moco-runner/src/main/java/com/github/dreamhead/moco/parser/CollectionReader.java
+++ b/moco-runner/src/main/java/com/github/dreamhead/moco/parser/CollectionReader.java
@@ -13,6 +13,8 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.nio.charset.Charset;
import java.util.List;
import static com.google.common.collect.ImmutableList.copyOf;
@@ -33,7 +35,7 @@ public class CollectionReader {
public <T> ImmutableList<T> read(InputStream is, Class<T> elementClass) {
try {
CollectionType type = factory.constructCollectionType(List.class, elementClass);
- List<T> sessionSettings = mapper.readValue(is, type);
+ List<T> sessionSettings = mapper.readValue(new InputStreamReader(is, Charset.defaultCharset()), type);
return copyOf(sessionSettings);
} catch (UnrecognizedPropertyException e) {
logger.info("Unrecognized field: {}", e.getMessage());
|
helped jackson to know encoding for #<I>
|
dreamhead_moco
|
train
|
8bb5f96a00c321ed4701517d798ab44c6438e6e5
|
diff --git a/lib/Menu.php b/lib/Menu.php
index <HASH>..<HASH> 100644
--- a/lib/Menu.php
+++ b/lib/Menu.php
@@ -122,7 +122,7 @@ class Menu extends Core {
/**
* @internal
*/
- protected function init_as_page_menu() {
+ protected function init_as_page_menu(array('sort_column' => 'menu_order')) {
$menu = get_pages();
if ( $menu ) {
foreach ( $menu as $mi ) {
|
Sort menu items by order instead of title
By default init_as_page_menu() sorts items by the title.
|
timber_timber
|
train
|
d7c0d450094d1dfbc0d3ef94fd93b6f9ddebc15d
|
diff --git a/generator/snippet_writer_test.go b/generator/snippet_writer_test.go
index <HASH>..<HASH> 100644
--- a/generator/snippet_writer_test.go
+++ b/generator/snippet_writer_test.go
@@ -29,7 +29,7 @@ import (
func construct(t *testing.T, files map[string]string) *generator.Context {
b := parser.New()
for name, src := range files {
- if err := b.AddFile("/tmp/"+name, name, []byte(src)); err != nil {
+ if err := b.AddFileForTest("/tmp/"+name, name, []byte(src)); err != nil {
t.Fatal(err)
}
}
diff --git a/parser/parse.go b/parser/parse.go
index <HASH>..<HASH> 100644
--- a/parser/parse.go
+++ b/parser/parse.go
@@ -150,9 +150,9 @@ func (b *Builder) importBuildPackage(pkgPath string) (*build.Package, error) {
return pkg, nil
}
-// AddFile adds a file to the set. The pkg must be of the form
+// AddFileForTest adds a file to the set. The pkg must be of the form
// "canonical/pkg/path" and the path must be the absolute path to the file.
-func (b *Builder) AddFile(pkg string, path string, src []byte) error {
+func (b *Builder) AddFileForTest(pkg string, path string, src []byte) error {
return b.addFile(pkg, path, src, true)
}
diff --git a/parser/parse_test.go b/parser/parse_test.go
index <HASH>..<HASH> 100644
--- a/parser/parse_test.go
+++ b/parser/parse_test.go
@@ -55,7 +55,7 @@ func TestRecursive(t *testing.T) {
func construct(t *testing.T, files map[string]string, testNamer namer.Namer) (*parser.Builder, types.Universe, []*types.Type) {
b := parser.New()
for name, src := range files {
- if err := b.AddFile(filepath.Dir(name), name, []byte(src)); err != nil {
+ if err := b.AddFileForTest(filepath.Dir(name), name, []byte(src)); err != nil {
t.Fatal(err)
}
}
|
Rename AddFile to AddFileForTest
Working to canonicalize paths, it became clear that this path is an exception
only used in tests. Subsequent commits will make it clear why this is
different - it doesn't ACTUALLY find the pkg on disk...
|
kubernetes_gengo
|
train
|
58f459f77d89134cc1c7fdf5b777d29065716cd1
|
diff --git a/lib/jpickle.js b/lib/jpickle.js
index <HASH>..<HASH> 100644
--- a/lib/jpickle.js
+++ b/lib/jpickle.js
@@ -183,18 +183,18 @@ Parser.prototype.load = function(pickle) {
case BINSTRING:
var length = buffer.readUInt32LE(i);
i += 4;
- this.stack.push(pickle.substr(i, length));
+ this.stack.push(buffer.toString('binary', i, i + length));
i += length;
break;
case SHORT_BINSTRING:
var length = buffer.readUInt8(i++);
- this.stack.push(pickle.substr(i, length));
+ this.stack.push(buffer.toString('binary', i, i + length));
i += length;
break;
case BINUNICODE:
var length = buffer.readUInt32LE(i);
i += 4;
- this.stack.push(buffer.toString('utf-8', i, i + length));
+ this.stack.push(buffer.toString('utf8', i, i + length));
i += length;
break;
case APPEND:
|
don't access pickle directly, always use Buffer
|
jlaine_node-jpickle
|
train
|
9f25da3263cdf5c0040194b43b144d4044f1a9b6
|
diff --git a/lib/opal-react/component.rb b/lib/opal-react/component.rb
index <HASH>..<HASH> 100644
--- a/lib/opal-react/component.rb
+++ b/lib/opal-react/component.rb
@@ -269,9 +269,17 @@ module React
def export_component(opts = {})
export_name = (opts[:as] || name).split("::")
- Native(`window`)[export_name.first] = ([React::API.create_native_react_class(self)] + export_name[1..-1].reverse).inject do |memo, sub_name|
- {sub_name => memo}
- end.to_n
+ first_name = export_name.first
+ Native(`window`)[first_name] = add_item_to_tree(Native(`window`)[first_name], [React::API.create_native_react_class(self)] + export_name[1..-1].reverse).to_n
+ end
+
+ def add_item_to_tree(current_tree, new_item)
+ if Native(current_tree).class != Native::Object or new_item.length == 1
+ new_item.inject do |memo, sub_name| {sub_name => memo} end
+ else
+ Native(current_tree)[new_item.last] = add_item_to_tree(Native(current_tree)[new_item.last], new_item[0..-2])
+ current_tree
+ end
end
end
|
got nested tree of module names working for export
|
zetachang_react.rb
|
train
|
b6c8d9897084444e3afd451acbebedbe5802325f
|
diff --git a/lib/Firelit/DatabaseObject.php b/lib/Firelit/DatabaseObject.php
index <HASH>..<HASH> 100644
--- a/lib/Firelit/DatabaseObject.php
+++ b/lib/Firelit/DatabaseObject.php
@@ -165,6 +165,12 @@ class DatabaseObject {
}
+ public function __isset($var) {
+
+ return isset($this->_data[$var]);
+
+ }
+
public function __set($var, $val) {
// If pre-construct loading
|
Added isset magic method to DatabaseObject class
|
firelit_firelit-framework
|
train
|
3172e84bb360838a9fda7ec9d0b12234ad911f5f
|
diff --git a/rpcserver.go b/rpcserver.go
index <HASH>..<HASH> 100644
--- a/rpcserver.go
+++ b/rpcserver.go
@@ -27,6 +27,7 @@ import (
"time"
"github.com/btcsuite/btcutil"
+ "github.com/btcsuite/fastsha256"
"github.com/btcsuite/websocket"
"github.com/conformal/btcchain"
"github.com/conformal/btcdb"
@@ -36,7 +37,6 @@ import (
"github.com/conformal/btcscript"
"github.com/conformal/btcwire"
"github.com/conformal/btcws"
- "github.com/conformal/fastsha256"
)
const (
diff --git a/rpcwebsocket.go b/rpcwebsocket.go
index <HASH>..<HASH> 100644
--- a/rpcwebsocket.go
+++ b/rpcwebsocket.go
@@ -20,13 +20,13 @@ import (
"golang.org/x/crypto/ripemd160"
"github.com/btcsuite/btcutil"
+ "github.com/btcsuite/fastsha256"
"github.com/btcsuite/websocket"
"github.com/conformal/btcdb"
"github.com/conformal/btcjson"
"github.com/conformal/btcscript"
"github.com/conformal/btcwire"
"github.com/conformal/btcws"
- "github.com/conformal/fastsha256"
)
const (
|
Update fastsha<I> import paths to new location.
|
btcsuite_btcd
|
train
|
28b6e0a0ab7eec6ad4eeb4c0128295e55af728f9
|
diff --git a/src/Client/Abstracts/AbstractClient.php b/src/Client/Abstracts/AbstractClient.php
index <HASH>..<HASH> 100644
--- a/src/Client/Abstracts/AbstractClient.php
+++ b/src/Client/Abstracts/AbstractClient.php
@@ -155,7 +155,7 @@ abstract class AbstractClient implements ClientInterface {
* @inheritdoc
*/
public function logout(){
- unset($this->token);
+ $this->token = NULL;
return TRUE;
}
|
Trying to get a completed Build in Travis CI
|
sugarcrm_rest-php-client
|
train
|
6ea49cf1d0d00c618affe5523af9584a6f673fb2
|
diff --git a/core/src/main/java/com/graphhopper/routing/util/CarFlagEncoder.java b/core/src/main/java/com/graphhopper/routing/util/CarFlagEncoder.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/graphhopper/routing/util/CarFlagEncoder.java
+++ b/core/src/main/java/com/graphhopper/routing/util/CarFlagEncoder.java
@@ -176,6 +176,13 @@ public class CarFlagEncoder extends AbstractFlagEncoder
return 0;
}
+ if ("track".equals(highwayValue))
+ {
+ String tt = way.getTag("tracktype");
+ if (tt != null && !tt.equals("grade1"))
+ return 0;
+ }
+
if (!defaultSpeedMap.containsKey(highwayValue))
return 0;
diff --git a/core/src/test/java/com/graphhopper/routing/util/CarFlagEncoderTest.java b/core/src/test/java/com/graphhopper/routing/util/CarFlagEncoderTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/com/graphhopper/routing/util/CarFlagEncoderTest.java
+++ b/core/src/test/java/com/graphhopper/routing/util/CarFlagEncoderTest.java
@@ -43,18 +43,26 @@ public class CarFlagEncoderTest
way.clearTags();
way.setTag("highway", "track");
+ assertTrue(encoder.acceptWay(way) > 0);
+
way.setTag("motorcar", "no");
assertFalse(encoder.acceptWay(way) > 0);
-
+
+ way.clearTags();
+ way.setTag("highway", "track");
+ way.setTag("tracktype", "grade2");
+ // disallow too rough tracks
+ assertFalse(encoder.acceptWay(way) > 0);
+
way.clearTags();
way.setTag("highway", "service");
way.setTag("access", "no");
way.setTag("motorcar", "yes");
assertTrue(encoder.acceptWay(way) > 0);
-
+
way.clearTags();
way.setTag("highway", "service");
- way.setTag("access", "delivery");
+ way.setTag("access", "delivery");
assertFalse(encoder.acceptWay(way) > 0);
way.clearTags();
@@ -160,13 +168,6 @@ public class CarFlagEncoderTest
encoded = encoder.handleWayTags(way, allowed, 0);
assertEquals(20, encoder.getSpeed(encoded), 1e-1);
- way.clearTags();
- way.setTag("highway", "track");
- way.setTag("tracktype", "grade5");
- allowed = encoder.acceptWay(way);
- encoded = encoder.handleWayTags(way, allowed, 0);
- assertEquals(5, encoder.getSpeed(encoded), 1e-1);
-
try
{
encoder.setSpeed(0, -1);
@@ -189,7 +190,18 @@ public class CarFlagEncoderTest
way.setTag("highway", "secondary");
way.setTag("railway", "rail");
// disallow rail
- assertEquals(0, encoder.acceptWay(way));
+ assertTrue(encoder.acceptWay(way) == 0);
+
+ way.clearTags();
+ way.setTag("highway", "path");
+ way.setTag("railway", "abandoned");
+ assertTrue(encoder.acceptWay(way) == 0);
+
+ way.setTag("highway", "track");
+ assertTrue(encoder.acceptWay(way) > 0);
+
+ way.setTag("motorcar", "no");
+ assertTrue(encoder.acceptWay(way) == 0);
way = new OSMWay(1);
way.setTag("highway", "secondary");
|
trying to reduce street count for car (track)
|
graphhopper_graphhopper
|
train
|
8fe5fbd0e92ee9aeb3676e01f7ef81aef8900a90
|
diff --git a/lib/mongoid/relations/targets/enumerable.rb b/lib/mongoid/relations/targets/enumerable.rb
index <HASH>..<HASH> 100644
--- a/lib/mongoid/relations/targets/enumerable.rb
+++ b/lib/mongoid/relations/targets/enumerable.rb
@@ -138,6 +138,19 @@ module Mongoid #:nodoc:
!!@executed
end
+ # Reset the enumerable back to it's persisted state.
+ #
+ # @example Reset the enumerable.
+ # enumerable.reset
+ #
+ # @return [ false ] Always false.
+ #
+ # @since 2.1.0
+ def reset
+ loaded.clear and added.clear
+ @executed = false
+ end
+
# Gets the total size of this enumerable. This is a combination of all
# the persisted and unpersisted documents.
#
diff --git a/spec/functional/mongoid/relations/targets/enumerable_spec.rb b/spec/functional/mongoid/relations/targets/enumerable_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/functional/mongoid/relations/targets/enumerable_spec.rb
+++ b/spec/functional/mongoid/relations/targets/enumerable_spec.rb
@@ -370,6 +370,45 @@ describe Mongoid::Relations::Targets::Enumerable do
end
end
+ describe "#reset" do
+
+ let(:person) do
+ Person.create(:ssn => "543-98-1238")
+ end
+
+ let(:post) do
+ Post.create(:person_id => person.id)
+ end
+
+ let(:post_two) do
+ Post.create(:person_id => person.id)
+ end
+
+ let(:enumerable) do
+ described_class.new([ post ])
+ end
+
+ before do
+ enumerable << post_two
+ end
+
+ let!(:reset) do
+ enumerable.reset
+ end
+
+ it "is not loaded" do
+ enumerable.should_not be_loaded
+ end
+
+ it "clears out the loaded docs" do
+ enumerable.loaded.should be_empty
+ end
+
+ it "clears out the added docs" do
+ enumerable.added.should be_empty
+ end
+ end
+
describe "#size" do
let(:person) do
|
Add ability to reset an enumerable
|
mongodb_mongoid
|
train
|
d3b053cae0fd40a4e0950fa17375b1d00d5c2848
|
diff --git a/src/ui/js/diff2html-ui.js b/src/ui/js/diff2html-ui.js
index <HASH>..<HASH> 100644
--- a/src/ui/js/diff2html-ui.js
+++ b/src/ui/js/diff2html-ui.js
@@ -31,10 +31,11 @@
Diff2HtmlUI.prototype.draw = function(targetId, config) {
var cfg = config || {};
+ cfg.inputFormat = 'json';
var $target = this._getTarget(targetId);
- $target.html(Diff2Html.getPrettyHtml(diffJson, cfg));
+ $target.html(Diff2Html.getPrettyHtml(diffJson, cfg.inputFormat));
- synchronisedScroll($target, config);
+ synchronisedScroll($target, cfg);
};
function synchronisedScroll($target, config) {
|
Force inputFormat on ui helper since it is always json
|
rtfpessoa_diff2html
|
train
|
a2fb6657aac4f8ba5ba8cabf00f89cf878a0321a
|
diff --git a/dist/middleware/logger.js b/dist/middleware/logger.js
index <HASH>..<HASH> 100644
--- a/dist/middleware/logger.js
+++ b/dist/middleware/logger.js
@@ -42,11 +42,12 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol
exports.default = function () {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+ var logger = getLogger(opts);
return function () {
var _ref = _asyncToGenerator(function* (ctx, next) {
ctx.requestId = uuidV4();
- var logger = getLogger(opts, ctx.requestId);
ctx.logger = logger || getNullLogger();
+ ctx.logger.requestId = ctx.requestId;
ctx.logger.Timer = _lodash2.default.bind(InnerTimer, {}, ctx.logger);
var timer = new ctx.logger.Timer({
@@ -79,7 +80,7 @@ var log4js = require('log4js'),
util = require('util'),
uuidV4 = require('uuid/v4');
-function getLogger(opts, requestId) {
+function getLogger(opts) {
if (!opts.log4js) {
return null;
}
@@ -91,7 +92,7 @@ function getLogger(opts, requestId) {
// CAUTION: currently only support [message_string, context_object]
// logevent is supposed to be like: [aaa %s bbb, aaa, ... , {context}]
var context = {
- requestId: requestId || uuidV4()
+ // requestId: requestId || uuidV4()
};
if (Array.isArray(logEvent.data) && logEvent.data.length > 0) {
@@ -187,6 +188,8 @@ function InnerTimer(logger, context) {
//this.timePoints = [this.start];
this.context = context || {};
+ this.context.requestId = this.logger.requestId || uuidV4();
+
this.logger.info('timer starting...', _lodash2.default.assign(this.context, { timerType: 'start' }));
this.reset = function reset() {
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "pomjs",
- "version": "0.1.22",
+ "version": "0.1.23",
"description": "Module Solution base on Vue ",
"main": "dist/app.js",
"scripts": {
diff --git a/src/middleware/logger.js b/src/middleware/logger.js
index <HASH>..<HASH> 100644
--- a/src/middleware/logger.js
+++ b/src/middleware/logger.js
@@ -39,7 +39,7 @@ const log4js = require('log4js'),
import _ from 'lodash'
-function getLogger(opts, requestId) {
+function getLogger(opts) {
if (!opts.log4js) {
return null
}
@@ -53,7 +53,7 @@ function getLogger(opts, requestId) {
// CAUTION: currently only support [message_string, context_object]
// logevent is supposed to be like: [aaa %s bbb, aaa, ... , {context}]
let context = {
- requestId: requestId || uuidV4()
+ // requestId: requestId || uuidV4()
}
if (Array.isArray(logEvent.data) && logEvent.data.length > 0) {
@@ -132,6 +132,8 @@ function InnerTimer(logger, context) {
//this.timePoints = [this.start];
this.context = context || {}
+ this.context.requestId = this.logger.requestId || uuidV4()
+
this.logger.info(
'timer starting...',
_.assign(this.context, { timerType: 'start' })
@@ -159,10 +161,11 @@ function InnerTimer(logger, context) {
}
export default function(opts = {}) {
+ const logger = getLogger(opts)
return async function log(ctx, next) {
ctx.requestId = uuidV4()
- let logger = getLogger(opts, ctx.requestId)
ctx.logger = logger || getNullLogger()
+ ctx.logger.requestId = ctx.requestId
ctx.logger.Timer = _.bind(InnerTimer, {}, ctx.logger)
let timer = new ctx.logger.Timer({
|
fix(logger) the former logger will create a socket object per request. This will cause some wired problem. Do some refector to resolve.
|
quancheng-ec_pomjs
|
train
|
fbeaf9db1eeb8b65847863532a87fa61226f4ff1
|
diff --git a/core/src/main/java/fi/iki/elonen/NanoHTTPD.java b/core/src/main/java/fi/iki/elonen/NanoHTTPD.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/fi/iki/elonen/NanoHTTPD.java
+++ b/core/src/main/java/fi/iki/elonen/NanoHTTPD.java
@@ -833,7 +833,7 @@ public abstract class NanoHTTPD {
this.method = Method.lookup(pre.get("method"));
if (this.method == null) {
- throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error.");
+ throw new ResponseException(Response.Status.BAD_REQUEST, "BAD REQUEST: Syntax error. HTTP verb "+pre.get("method")+" unhandled.");
}
this.uri = pre.get("uri");
@@ -1192,7 +1192,14 @@ public abstract class NanoHTTPD {
OPTIONS,
TRACE,
CONNECT,
- PATCH;
+ PATCH,
+ PROPFIND,
+ PROPPATCH,
+ MKCOL,
+ MOVE,
+ COPY,
+ LOCK,
+ UNLOCK;
static Method lookup(String method) {
for (Method m : Method.values()) {
@@ -1226,6 +1233,7 @@ public abstract class NanoHTTPD {
ACCEPTED(202, "Accepted"),
NO_CONTENT(204, "No Content"),
PARTIAL_CONTENT(206, "Partial Content"),
+ MULTI_STATUS(207, "Multi-Status"),
REDIRECT(301, "Moved Permanently"),
NOT_MODIFIED(304, "Not Modified"),
BAD_REQUEST(400, "Bad Request"),
|
add HTTP verbs and status codes for WebDAV (RFC <I>)
Extra HTTP verbs:
PROPFIND, PROPPATCH, MKCOL, MOVE, COPY, LOCK, UNLOCK
Extra HTTP status code:
<I> "Multi-Status"
More detailed BAD REQUEST error message:
When serving a request, if some data is left unconsumed then those data
corrupt the subsequent request. An extended error message makes this
programming error easier to identify.
|
NanoHttpd_nanohttpd
|
train
|
35081c0d21d0584ccbb8b77dade84f25e28dd9ce
|
diff --git a/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php b/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php
index <HASH>..<HASH> 100644
--- a/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php
+++ b/src/Psalm/Internal/Analyzer/Statements/Block/TryAnalyzer.php
@@ -5,6 +5,7 @@ use PhpParser;
use Psalm\Internal\Analyzer\ClassLikeAnalyzer;
use Psalm\Internal\Analyzer\ScopeAnalyzer;
use Psalm\Internal\Analyzer\StatementsAnalyzer;
+use Psalm\Internal\ControlFlow\ControlFlowNode;
use Psalm\CodeLocation;
use Psalm\Context;
use Psalm\Issue\InvalidCatch;
@@ -308,6 +309,37 @@ class TryAnalyzer
);
$catch_context->vars_possibly_in_scope[$catch_var_id] = true;
+
+ $location = new CodeLocation($statements_analyzer->getSource(), $catch->var);
+
+ if (!$statements_analyzer->hasVariable($catch_var_id)) {
+ $statements_analyzer->registerVariable(
+ $catch_var_id,
+ $location,
+ $catch_context->branch_point
+ );
+ } else {
+ $statements_analyzer->registerVariableAssignment(
+ $catch_var_id,
+ $location
+ );
+ }
+
+ if ($statements_analyzer->control_flow_graph) {
+ $catch_var_node = ControlFlowNode::getForAssignment($catch_var_id, $location);
+
+ $catch_context->vars_in_scope[$catch_var_id]->parent_nodes = [
+ $catch_var_node->id => $catch_var_node
+ ];
+
+ if ($statements_analyzer->control_flow_graph instanceof \Psalm\Internal\Codebase\VariableUseGraph) {
+ $statements_analyzer->control_flow_graph->addPath(
+ $catch_var_node,
+ new ControlFlowNode('variable-use', 'variable use', null),
+ 'variable-use'
+ );
+ }
+ }
}
$suppressed_issues = $statements_analyzer->getSuppressedIssues();
|
Ensure catch variables are marked as used
|
vimeo_psalm
|
train
|
aa21b3a90a0f905b4787d9f5444ff4d9bf57edc2
|
diff --git a/Classes/Typo3/Hook/LinkWizzard.php b/Classes/Typo3/Hook/LinkWizzard.php
index <HASH>..<HASH> 100644
--- a/Classes/Typo3/Hook/LinkWizzard.php
+++ b/Classes/Typo3/Hook/LinkWizzard.php
@@ -84,7 +84,7 @@ class LinkWizzard extends AbstractLinkHandler implements LinkHandlerInterface, L
*/
public function canHandleLink(array $linkParts): bool
{
- if (strcmp($linkParts['type'], 'happy_feet') !== 0) {
+ if ($linkParts['type'] === null || strcmp($linkParts['type'], 'happy_feet') !== 0) {
return false;
}
if (!$linkParts['url']) {
|
[FIX] Avoid Oops on opening linkwizard on empty links.
|
AOEpeople_happy_feet
|
train
|
6e9081312bd3778a0dad9042b696b8cc58c9e67b
|
diff --git a/src/main/java/org/cactoos/map/MapEnvelope.java b/src/main/java/org/cactoos/map/MapEnvelope.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/cactoos/map/MapEnvelope.java
+++ b/src/main/java/org/cactoos/map/MapEnvelope.java
@@ -35,7 +35,6 @@ import org.cactoos.text.TextOf;
*
* @param <X> Type of key
* @param <Y> Type of value
- * @see Sticky
* @since 0.24
* @checkstyle AbstractClassNameCheck (500 lines)
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
|
(#<I>) Remove dead link
|
yegor256_cactoos
|
train
|
6c44510812232ebb34aed5d2412dbb07e8d59257
|
diff --git a/server/src/main/java/org/jboss/as/server/operations/sockets/SpecifiedInterfaceRemoveHandler.java b/server/src/main/java/org/jboss/as/server/operations/sockets/SpecifiedInterfaceRemoveHandler.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/org/jboss/as/server/operations/sockets/SpecifiedInterfaceRemoveHandler.java
+++ b/server/src/main/java/org/jboss/as/server/operations/sockets/SpecifiedInterfaceRemoveHandler.java
@@ -23,7 +23,6 @@ import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.controller.OperationResult;
import org.jboss.as.controller.ResultHandler;
-import org.jboss.as.controller.RuntimeOperationContext;
import org.jboss.as.controller.RuntimeTask;
import org.jboss.as.controller.RuntimeTaskContext;
import org.jboss.as.controller.operations.common.InterfaceRemoveHandler;
@@ -44,8 +43,8 @@ public class SpecifiedInterfaceRemoveHandler extends InterfaceRemoveHandler {
protected OperationResult uninstallInterface(final String name, final ModelNode criteria, final OperationContext context, final ResultHandler resultHandler, final ModelNode compensatingOp) {
if (context.getRuntimeContext() != null) {
context.getRuntimeContext().setRuntimeTask(new RuntimeTask() {
+ @Override
public void execute(RuntimeTaskContext context) throws OperationFailedException {
- RuntimeOperationContext runtimeContext = (RuntimeOperationContext) context;
final ServiceController<?> controller = context.getServiceRegistry()
.getService(NetworkInterfaceService.JBOSS_NETWORK_INTERFACE.append(name));
if (controller != null) {
|
[JBAS-<I>] Remove incorrect cast
was: 7c2ead<I>e0c<I>bd<I>d0f<I>c<I>e<I>a4b6
|
wildfly_wildfly-core
|
train
|
199cfd93d20a27142b6fff0673198008ff559442
|
diff --git a/src/ProxyManager/ProxyGenerator/AccessInterceptorScopeLocalizer/MethodGenerator/StaticProxyConstructor.php b/src/ProxyManager/ProxyGenerator/AccessInterceptorScopeLocalizer/MethodGenerator/StaticProxyConstructor.php
index <HASH>..<HASH> 100644
--- a/src/ProxyManager/ProxyGenerator/AccessInterceptorScopeLocalizer/MethodGenerator/StaticProxyConstructor.php
+++ b/src/ProxyManager/ProxyGenerator/AccessInterceptorScopeLocalizer/MethodGenerator/StaticProxyConstructor.php
@@ -90,7 +90,8 @@ class StaticProxyConstructor extends MethodGenerator
$instanceGenerator
. (empty($localizedProperties) ? '' : implode("\n\n", $localizedProperties) . "\n\n")
. '$instance->' . $prefixInterceptors->getName() . " = \$prefixInterceptors;\n"
- . '$instance->' . $suffixInterceptors->getName() . " = \$suffixInterceptors;"
+ . '$instance->' . $suffixInterceptors->getName() . " = \$suffixInterceptors;\n\n"
+ . 'return $instance'
);
}
}
|
Built instance should be returned by the static constructor
|
Ocramius_ProxyManager
|
train
|
7d848cd8554e55b7911d0c524c74031aa400f6d1
|
diff --git a/src/__tests__/annotate.test.js b/src/__tests__/annotate.test.js
index <HASH>..<HASH> 100644
--- a/src/__tests__/annotate.test.js
+++ b/src/__tests__/annotate.test.js
@@ -15,6 +15,8 @@ describe('annotation detection', () => {
expect(isAnnotation({ type: 'ObjectAnnotation' })).toBe(true);
expect(isAnnotation({ type: 'ArrayAnnotation' })).toBe(true);
expect(isAnnotation({ type: 'ScalarAnnotation' })).toBe(true);
+ expect(isAnnotation({ type: 'FunctionAnnotation' })).toBe(true);
+ expect(isAnnotation({ type: 'CircularRefAnnotation' })).toBe(true);
});
});
@@ -289,6 +291,18 @@ describe('annotating circular objects', () => {
{ type: 'CircularRefAnnotation' },
],
});
+ expect(annotate(annotate(annotate(circularArray)))).toEqual({
+ type: 'ArrayAnnotation',
+ annotation: undefined,
+ items: [
+ {
+ type: 'ScalarAnnotation',
+ value: 'foo',
+ annotation: undefined,
+ },
+ { type: 'CircularRefAnnotation' },
+ ],
+ });
});
it('circular objects', () => {
@@ -339,4 +353,32 @@ describe('annotating circular objects', () => {
annotation: undefined,
});
});
+
+ it('circular objects (w/ explicit seen)', () => {
+ var circularObject = { foo: 42, bar: { qux: 'hello' } };
+ // $FlowFixMe
+ circularObject.bar.self = circularObject;
+ // $FlowFixMe
+ circularObject.self = circularObject;
+
+ const seen = new WeakSet();
+ seen.add(circularObject);
+ expect(annotateFields(circularObject, [['self', 'Example']], seen)).toEqual({
+ type: 'CircularRefAnnotation',
+ annotation: undefined,
+ });
+ });
+
+ it('circular objects (w/ explicit annotation)', () => {
+ var circularObject = { foo: 42 };
+ // $FlowFixMe
+ circularObject.self = circularObject;
+
+ const seen = new WeakSet();
+ seen.add(circularObject);
+ expect(annotate(annotate(circularObject, undefined, seen), 'Example', seen)).toEqual({
+ type: 'CircularRefAnnotation',
+ annotation: 'Example',
+ });
+ });
});
|
Back to <I>% test coverage
|
nvie_debrief.js
|
train
|
0c5b5ead159b75d9b0307e73b17ed2a0c0834594
|
diff --git a/tests/PHPUnit/Unit/AssetManagerTest.php b/tests/PHPUnit/Unit/AssetManagerTest.php
index <HASH>..<HASH> 100644
--- a/tests/PHPUnit/Unit/AssetManagerTest.php
+++ b/tests/PHPUnit/Unit/AssetManagerTest.php
@@ -251,7 +251,7 @@ class AssetManagerTest extends PHPUnit_Framework_TestCase
{
$this->clearDateCache();
- sleep(1.5);
+ sleep(1);
$modificationDate = $this->mergedAsset->getModificationDate();
diff --git a/tests/PHPUnit/Unit/CommonTest.php b/tests/PHPUnit/Unit/CommonTest.php
index <HASH>..<HASH> 100644
--- a/tests/PHPUnit/Unit/CommonTest.php
+++ b/tests/PHPUnit/Unit/CommonTest.php
@@ -5,6 +5,8 @@ use Piwik\Filesystem;
/**
* Piwik - free/libre analytics platform
*
+ * @backupGlobals enabled
+ *
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
diff --git a/tests/PHPUnit/Unit/DataTable/Filter/PivotByDimensionTest.php b/tests/PHPUnit/Unit/DataTable/Filter/PivotByDimensionTest.php
index <HASH>..<HASH> 100644
--- a/tests/PHPUnit/Unit/DataTable/Filter/PivotByDimensionTest.php
+++ b/tests/PHPUnit/Unit/DataTable/Filter/PivotByDimensionTest.php
@@ -181,6 +181,9 @@ class PivotByDimensionTest extends PHPUnit_Framework_TestCase
$this->assertTableRowsEquals($expectedRows, $table);
}
+ /**
+ * @backupGlobals enabled
+ */
public function test_filter_UsesCorrectSegment_WhenPivotingSegmentedReport()
{
$this->loadPlugins('Referrers', 'UserCountry', 'CustomVariables');
diff --git a/tests/PHPUnit/Unit/IPTest.php b/tests/PHPUnit/Unit/IPTest.php
index <HASH>..<HASH> 100644
--- a/tests/PHPUnit/Unit/IPTest.php
+++ b/tests/PHPUnit/Unit/IPTest.php
@@ -7,6 +7,8 @@ use Piwik\SettingsServer;
/**
* Piwik - free/libre analytics platform
*
+ * @backupGlobals enabled
+ *
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
diff --git a/tests/PHPUnit/Unit/NonceTest.php b/tests/PHPUnit/Unit/NonceTest.php
index <HASH>..<HASH> 100644
--- a/tests/PHPUnit/Unit/NonceTest.php
+++ b/tests/PHPUnit/Unit/NonceTest.php
@@ -5,6 +5,8 @@ use Piwik\Nonce;
/**
* Piwik - free/libre analytics platform
*
+ * @backupGlobals enabled
+ *
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
diff --git a/tests/PHPUnit/Unit/UrlTest.php b/tests/PHPUnit/Unit/UrlTest.php
index <HASH>..<HASH> 100644
--- a/tests/PHPUnit/Unit/UrlTest.php
+++ b/tests/PHPUnit/Unit/UrlTest.php
@@ -5,6 +5,8 @@ use Piwik\Url;
/**
* Piwik - free/libre analytics platform
*
+ * @backupGlobals enabled
+ *
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
|
Speed up unit tests by enabling PHPUnit backupGlobals only for specific tests
|
matomo-org_matomo
|
train
|
bd7a3d9fc965bddba1363d51926e3fd888b9e9cf
|
diff --git a/test/android/uk/co/real_logic/sbe/codec/java/CodecUtilTest.java b/test/android/uk/co/real_logic/sbe/codec/java/CodecUtilTest.java
index <HASH>..<HASH> 100644
--- a/test/android/uk/co/real_logic/sbe/codec/java/CodecUtilTest.java
+++ b/test/android/uk/co/real_logic/sbe/codec/java/CodecUtilTest.java
@@ -17,6 +17,8 @@ package uk.co.real_logic.sbe.codec.java;
import org.junit.Test;
+import android.test.suitebuilder.annotation.SmallTest;
+
import java.nio.ByteOrder;
import static org.hamcrest.Matchers.is;
@@ -24,6 +26,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
+@SmallTest
public class CodecUtilTest
{
private static final ByteOrder BYTE_ORDER = ByteOrder.nativeOrder();
diff --git a/test/android/uk/co/real_logic/sbe/codec/java/DirectBufferTest.java b/test/android/uk/co/real_logic/sbe/codec/java/DirectBufferTest.java
index <HASH>..<HASH> 100644
--- a/test/android/uk/co/real_logic/sbe/codec/java/DirectBufferTest.java
+++ b/test/android/uk/co/real_logic/sbe/codec/java/DirectBufferTest.java
@@ -23,6 +23,7 @@ import org.junit.experimental.theories.Theory;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
+import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
import java.io.File;
@@ -38,6 +39,7 @@ import static java.lang.Integer.valueOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
+@SmallTest
@RunWith(Theories.class)
public class DirectBufferTest
{
@@ -77,7 +79,7 @@ public class DirectBufferTest
@DataPoint
public static final DirectBuffer MEMORY_MAPPED_BUFFER = new DirectBuffer(createMemoryMappedBuffer());
- // private static long memoryBlockAddress = BitUtil.getUnsafe().allocateMemory(BUFFER_CAPACITY);
+ // private static long memoryBlockAddress = 0;
// @DataPoint //not valid for android
// public static final DirectBuffer OFF_HEAP_BUFFER =
@@ -521,14 +523,12 @@ public class DirectBufferTest
private static RandomAccessFile memoryMappedFile;
private static MappedByteBuffer buffer;
- private static File tempFile;
private static ByteBuffer createMemoryMappedBuffer()
{
try
{
- tempFile = File.createTempFile("tempDirectBufferTest", ".tmp");
- tempFile.deleteOnExit();
+ File tempFile = new File("/dev/zero");
memoryMappedFile = new RandomAccessFile(tempFile, "rw");
buffer = memoryMappedFile.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, BUFFER_CAPACITY);
return buffer;
@@ -553,7 +553,6 @@ public class DirectBufferTest
cleanMethod.invoke(buffer);
memoryMappedFile.close();
- tempFile.delete();
}
catch (Exception e)
{
|
[Android] Added test annotations
|
real-logic_simple-binary-encoding
|
train
|
d311b36542fe8a36f0483a30a35198d2a4d602d9
|
diff --git a/lib/Collection.js b/lib/Collection.js
index <HASH>..<HASH> 100644
--- a/lib/Collection.js
+++ b/lib/Collection.js
@@ -84,9 +84,11 @@ function Collection( world , name , schema )
var key , element , indexName ;
if ( typeof schema.url !== 'string' ) { throw new Error( '[roots-db] schema.url should be a string' ) ; }
+
collection.url = schema.url ;
collection.config = url.parse( collection.url , true ) ;
collection.config.driver = collection.config.protocol.split( ':' )[ 0 ] ;
+
if ( ! schema.properties ) { schema.properties = {} ; }
// Create the validator schema
@@ -97,6 +99,7 @@ function Collection( world , name , schema )
if ( ! collection.documentSchema.properties._id ) { collection.documentSchema.properties._id = { optional: true , type: 'objectId' } ; }
collection.validate = doormen.bind( doormen , collection.documentSchema ) ;
+ collection.skipValidation = !! schema.skipValidation ;
// Attachment URL for files
if ( typeof schema.attachmentUrl === 'string' )
diff --git a/lib/DocumentWrapper.js b/lib/DocumentWrapper.js
index <HASH>..<HASH> 100644
--- a/lib/DocumentWrapper.js
+++ b/lib/DocumentWrapper.js
@@ -54,7 +54,7 @@ function DocumentWrapper( collection , rawDocument , options )
var id = collection.driver.checkId( rawDocument , true ) ;
// Then validate the document
- if ( ! options.skipValidation )
+ if ( ! ( options.skipValidation !== undefined ? options.skipValidation : collection.skipValidation ) )
{
try {
collection.validate( rawDocument ) ;
@@ -120,6 +120,22 @@ DocumentWrapper.prototype.save = function documentSave( options , callback )
//if ( this.suspected ) { throw new Error( '[roots-db] cannot save a suspected document - it is on the TODO LIST already' ) ; }
if ( this.deleted ) { throw new Error( 'Current document is deleted' ) ; }
+ // Validation
+ if ( ! ( options.skipValidation !== undefined ? options.skipValidation : this.collection.skipValidation ) )
+ {
+ try {
+ this.collection.validate( this.document ) ;
+ }
+ catch ( error ) {
+ error.validatorMessage = error.message ;
+ error.message = '[roots-db] validator error: ' + error.message ;
+ throw error ;
+ }
+
+ // Do not validate again, in case of recursive call
+ options.skipValidation = true ;
+ }
+
// Clear attachments first, then call save() again...
if ( options.clearAttachments && this.collection.attachmentUrl )
{
@@ -231,6 +247,22 @@ DocumentWrapper.prototype.commit = function documentCommit( options , callback )
//if ( this.suspected ) { throw new Error( '[roots-db] cannot save a suspected document - it is on the TODO LIST already' ) ; }
if ( this.deleted ) { throw new Error( 'Current document is deleted' ) ; }
+ // Validation
+ if ( ! ( options.skipValidation !== undefined ? options.skipValidation : this.collection.skipValidation ) )
+ {
+ try {
+ this.collection.validate( this.document ) ;
+ }
+ catch ( error ) {
+ error.validatorMessage = error.message ;
+ error.message = '[roots-db] validator error: ' + error.message ;
+ throw error ;
+ }
+
+ // Do not validate again, in case of recursive call
+ options.skipValidation = true ;
+ }
+
// Save attachments first, then call commit() again...
if ( options.attachmentStreams )
{
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "roots-db",
- "version": "0.5.27",
+ "version": "0.5.28",
"engines": {
"node": ">=4.0.0"
},
|
validation on save()/commit() by default
|
cronvel_roots-db
|
train
|
34c6fcaacfe2f58621ca21996665582e62f173d5
|
diff --git a/km3pipe/dataclasses.py b/km3pipe/dataclasses.py
index <HASH>..<HASH> 100644
--- a/km3pipe/dataclasses.py
+++ b/km3pipe/dataclasses.py
@@ -136,15 +136,21 @@ class HitSeries(object):
if self._hits is None:
self._convert_hits()
self._hits.append(hit)
+ self._pos = None
+ self._dir = None
@property
def pos(self):
+ if self._hits is None:
+ self._convert_hits()
if self._pos is None:
self._pos = np.array([hit.pos for hit in self._hits])
return self._pos
@property
def dir(self):
+ if self._hits is None:
+ self._convert_hits()
if self._dir is None:
self._dir = np.array([hit.dir for hit in self._hits])
return self._dir
|
Safe caching of pos and dir, regarding append
|
tamasgal_km3pipe
|
train
|
a38a0053d31d0285dd1e6ebe6efc28726a9656cc
|
diff --git a/TODO b/TODO
index <HASH>..<HASH> 100644
--- a/TODO
+++ b/TODO
@@ -32,12 +32,11 @@ Object
Config
------
-* Expand .get* methods of GitConfigParser to support default value. If it is not None,
- it will be returned instead of raising. This way the class will be much more usable,
- and ... I truly hate this config reader as it is so 'old' style. Its not even a new-style
- class yet showing that it must be ten years old.
- - If you are at it, why not start a new project that reimplements the ConfigWriter
- properly, honestly. Tune it for usability ... .
+* Cache the config_reader of the repository and check whether they need to
+ update their information as the local file(s) have changed. Currently
+ we re-read all configuration data each time a config-reader is created.
+ In a way this leaves it to the user to actually keep the config-reader for
+ multiple uses, but there are cases when the user can hardly do that.
Diff
----
diff --git a/lib/git/__init__.py b/lib/git/__init__.py
index <HASH>..<HASH> 100644
--- a/lib/git/__init__.py
+++ b/lib/git/__init__.py
@@ -20,6 +20,7 @@ from git.repo import Repo
from git.stats import Stats
from git.remote import *
from git.index import *
+from git.utils import LockFile, BlockingLockFile
__all__ = [ name for name, obj in locals().items()
if not (name.startswith('_') or inspect.ismodule(obj)) ]
diff --git a/lib/git/cmd.py b/lib/git/cmd.py
index <HASH>..<HASH> 100644
--- a/lib/git/cmd.py
+++ b/lib/git/cmd.py
@@ -218,6 +218,8 @@ class Git(object):
# Wait for the process to return
status = 0
+ stdout_value = ''
+ stderr_value = ''
try:
if output_stream is None:
stdout_value = proc.stdout.read().rstrip() # strip trailing "\n"
@@ -232,6 +234,7 @@ class Git(object):
stdout_value = output_stream
# END stdout handling
stderr_value = proc.stderr.read().rstrip() # strip trailing "\n"
+
# waiting here should do nothing as we have finished stream reading
status = proc.wait()
finally:
diff --git a/lib/git/index.py b/lib/git/index.py
index <HASH>..<HASH> 100644
--- a/lib/git/index.py
+++ b/lib/git/index.py
@@ -21,7 +21,7 @@ import git.diff as diff
from errors import GitCommandError
from git.objects import Blob, Tree, Object, Commit
-from git.utils import SHA1Writer, LazyMixin, ConcurrentWriteOperation, join_path_native, BlockingLockFile
+from git.utils import SHA1Writer, LazyMixin, ConcurrentWriteOperation, join_path_native
class CheckoutError( Exception ):
@@ -914,6 +914,7 @@ class IndexFile(LazyMixin, diff.Diffable):
entries_added = list()
paths, entries = self._preprocess_add_items(items)
+
# HANDLE PATHS
if paths:
# to get suitable progress information, pipe paths to stdin
diff --git a/lib/git/remote.py b/lib/git/remote.py
index <HASH>..<HASH> 100644
--- a/lib/git/remote.py
+++ b/lib/git/remote.py
@@ -29,7 +29,7 @@ class _SectionConstraint(object):
def __getattr__(self, attr):
if attr in self._valid_attrs_:
- return lambda *args: self._call_config(attr, *args)
+ return lambda *args, **kwargs: self._call_config(attr, *args, **kwargs)
return super(_SectionConstraint,self).__getattribute__(attr)
def _call_config(self, method, *args, **kwargs):
|
Added imports for standard locking file classes into the git module
|
gitpython-developers_GitPython
|
train
|
065c6a4429d919bdeb35d9fbc1e7de491aff2f90
|
diff --git a/client/my-sites/comments/controller.js b/client/my-sites/comments/controller.js
index <HASH>..<HASH> 100644
--- a/client/my-sites/comments/controller.js
+++ b/client/my-sites/comments/controller.js
@@ -49,7 +49,7 @@ const changePage = path => pageNumber => {
};
export const siteComments = context => {
- const { params, path, query, store } = context;
+ const { params, path, query } = context;
const siteFragment = route.getSiteFragment( path );
if ( ! siteFragment ) {
@@ -71,11 +71,12 @@ export const siteComments = context => {
status={ status }
/>,
'primary',
- store
+ context.store
);
};
-export const postComments = ( { params, path, query, store } ) => {
+export const postComments = context => {
+ const { params, path, query } = context;
const siteFragment = route.getSiteFragment( path );
if ( ! siteFragment ) {
@@ -103,11 +104,12 @@ export const postComments = ( { params, path, query, store } ) => {
status={ status }
/>,
'primary',
- store
+ context.store
);
};
-export const comment = ( { query, params, path, store } ) => {
+export const comment = context => {
+ const { params, path, query } = context;
const siteFragment = route.getSiteFragment( path );
const commentId = sanitizeInt( params.comment );
@@ -122,7 +124,7 @@ export const comment = ( { query, params, path, store } ) => {
renderWithReduxStore(
<CommentView { ...{ action, commentId, siteFragment } } />,
'primary',
- store
+ context.store
);
};
|
Comments: unwrap object matching shorthands (#<I>)
Unwrap object matching shorthands to `context` for clarity and easier codemodding.
|
Automattic_wp-calypso
|
train
|
fd441a498b3fde67e4e2d5ebb2eaa6e5b6eea4b5
|
diff --git a/tests/pytests/unit/modules/test_aptpkg.py b/tests/pytests/unit/modules/test_aptpkg.py
index <HASH>..<HASH> 100644
--- a/tests/pytests/unit/modules/test_aptpkg.py
+++ b/tests/pytests/unit/modules/test_aptpkg.py
@@ -838,6 +838,50 @@ def test__skip_source():
assert ret is False
+def test__parse_source():
+ cases = (
+ {"ok": False, "line": "", "invalid": True, "disabled": False},
+ {"ok": False, "line": "#", "invalid": True, "disabled": True},
+ {"ok": False, "line": "##", "invalid": True, "disabled": True},
+ {"ok": False, "line": "# comment", "invalid": True, "disabled": True},
+ {"ok": False, "line": "## comment", "invalid": True, "disabled": True},
+ {"ok": False, "line": "deb #", "invalid": True, "disabled": False},
+ {"ok": False, "line": "# deb #", "invalid": True, "disabled": True},
+ {"ok": False, "line": "deb [ invalid line", "invalid": True, "disabled": False},
+ {
+ "ok": True,
+ "line": "# deb http://debian.org/debian/ stretch main\n",
+ "invalid": False,
+ "disabled": True,
+ },
+ {
+ "ok": True,
+ "line": "deb http://debian.org/debian/ stretch main # comment\n",
+ "invalid": False,
+ "disabled": False,
+ },
+ {
+ "ok": True,
+ "line": "deb [trusted=yes] http://debian.org/debian/ stretch main\n",
+ "invalid": False,
+ "disabled": False,
+ },
+ )
+ with patch.dict("sys.modules", {"aptsources.sourceslist": None}):
+ import importlib
+ import salt.modules.aptpkg as _aptpkg
+
+ importlib.reload(_aptpkg)
+
+ for case in cases:
+ source = _aptpkg.SourceEntry(case["line"])
+ ok = source._parse_sources(case["line"])
+
+ assert ok is case["ok"]
+ assert source.invalid is case["invalid"]
+ assert source.disabled is case["disabled"]
+
+
def test_normalize_name():
"""
Test that package is normalized only when it should be
|
add tests for aptpkg.SourceEntry with HAS_APT=False
|
saltstack_salt
|
train
|
0d75e128ecbef2cc7e4cf9bf7af31b4b208469b1
|
diff --git a/lib/runner/util.js b/lib/runner/util.js
index <HASH>..<HASH> 100644
--- a/lib/runner/util.js
+++ b/lib/runner/util.js
@@ -70,6 +70,16 @@ module.exports = {
return dest;
},
+ /**
+ * Create readable stream for given file as well as detect possible file
+ * read issues.
+ *
+ * @param {Object} resolver - External file resolver module
+ * @param {Function} resolver.stat - Resolver method to check for existence and permissions of file
+ * @param {Function} resolver.createReadStream - Resolver method for creating read stream
+ * @param {String} fileSrc - File path
+ * @param {Function} callback - Final callback
+ */
createReadStream: function (resolver, fileSrc, callback) {
// bail out if resolver not found.
if (!resolver) {
@@ -86,6 +96,9 @@ module.exports = {
return callback(new Error('invalid or missing file source'));
}
+ var self = this,
+ readStream;
+
// check for the existence of the file before creating read stream.
// eslint-disable-next-line security/detect-non-literal-fs-filename
resolver.stat(fileSrc, function(err, stats) {
@@ -112,7 +125,19 @@ module.exports = {
// listening on error requires listening on end event as well. which will make this sync.
// @note In form-data mode stream error will be handled in postman-request but bails out ongoing request.
// eslint-disable-next-line security/detect-non-literal-fs-filename
- callback(null, resolver.createReadStream(fileSrc));
+ readStream = resolver.createReadStream(fileSrc);
+
+ // We might have to read the file before making the actual request
+ // e.g, while calculating body hash during AWS auth or redirecting form-data params
+ // So, this method wraps the `createReadStream` function with fixed arguments.
+ // This makes sure that we don't have to pass `fileResolver` to
+ // internal modules (like auth plugins) for security reasons.
+ readStream.cloneReadStream = function (cb) {
+ // eslint-disable-next-line security/detect-non-literal-fs-filename
+ return self.createReadStream(resolver, fileSrc, cb);
+ };
+
+ callback(null, readStream);
});
}
};
|
util.createReadStream: Add ability to clone read stream
|
postmanlabs_postman-runtime
|
train
|
c4106d0c08954b0761726e0015ec601b7bc7ea4b
|
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -1403,9 +1403,10 @@ module ActionDispatch
def add_route(action, options) # :nodoc:
path = path_for_action(action, options.delete(:path))
+ action = action.to_s.dup
- if action.to_s =~ /^[\w\/]+$/
- options[:action] ||= action unless action.to_s.include?("/")
+ if action =~ /^[\w\/]+$/
+ options[:action] ||= action unless action.include?("/")
else
action = nil
end
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index <HASH>..<HASH> 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -2678,6 +2678,15 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
assert_equal '0c0c0b68-d24b-11e1-a861-001ff3fffe6f', @request.params[:download]
end
+ def test_action_from_path_is_not_frozen
+ draw do
+ get 'search' => 'search'
+ end
+
+ get '/search'
+ assert !@request.params[:action].frozen?
+ end
+
private
def draw(&block)
|
Duplicate possible frozen string from route
Ruby <I> freezes Hash string keys by default so where a route is
defined like this:
get 'search' => 'search'
then the Mapper will derive the action from the key. This blows up
later when the action is added to the parameters hash and the
encoding is forced.
Closes #<I>
|
rails_rails
|
train
|
3b548073cf53d90215e5d8c06d3499cc1157db6b
|
diff --git a/driver/src/test/functional/com/mongodb/client/CrudTest.java b/driver/src/test/functional/com/mongodb/client/CrudTest.java
index <HASH>..<HASH> 100644
--- a/driver/src/test/functional/com/mongodb/client/CrudTest.java
+++ b/driver/src/test/functional/com/mongodb/client/CrudTest.java
@@ -48,6 +48,7 @@ import static com.mongodb.ClusterFixture.serverVersionAtLeast;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeFalse;
+import static org.junit.Assume.assumeTrue;
// See https://github.com/mongodb/specifications/tree/master/source/crud/tests
@RunWith(Parameterized.class)
@@ -104,9 +105,11 @@ public class CrudTest extends DatabaseTestCase {
private boolean checkResult() {
if (filename.contains("insert")) {
+ // We don't return any id's for insert commands
return false;
} else if (!serverVersionAtLeast(asList(3, 0, 0))
&& description.contains("when no documents match with upsert returning the document before modification")) {
+ // Pre 3.0 versions of MongoDB return an empty document rather than a null
return false;
}
return true;
@@ -150,6 +153,7 @@ public class CrudTest extends DatabaseTestCase {
return toResult(new BsonDocument(key, value));
}
private BsonDocument toResult(final UpdateResult updateResult) {
+ assumeTrue(serverVersionAtLeast(asList(2, 6, 0))); // ModifiedCount is not accessible pre 2.6
BsonDocument resultDoc = new BsonDocument("matchedCount", new BsonInt32((int) updateResult.getMatchedCount()))
.append("modifiedCount", new BsonInt32((int) updateResult.getModifiedCount()));
if (updateResult.getUpsertedId() != null) {
@@ -224,6 +228,7 @@ public class CrudTest extends DatabaseTestCase {
}
private BsonDocument getFindOneAndReplaceResult(final BsonDocument arguments) {
+ assumeTrue(serverVersionAtLeast(asList(2, 6, 0))); // in 2.4 the server can ignore the supplied _id and creates an ObjectID
FindOneAndReplaceOptions options = new FindOneAndReplaceOptions();
if (arguments.containsKey("projection")) {
options.projection(arguments.getDocument("projection"));
|
Added extra checks for Crud tests on Mongo <I> & <I>
|
mongodb_mongo-java-driver
|
train
|
ead61d5cb408b0efbde95c32bee7044caff5d702
|
diff --git a/groupstage.js b/groupstage.js
index <HASH>..<HASH> 100644
--- a/groupstage.js
+++ b/groupstage.js
@@ -104,26 +104,26 @@ GroupStage.prototype.initResult = function (seed) {
GroupStage.prototype.stats = function (res) {
// compute stats based on completed matches
this.matches.filter($.get('m')).forEach(function (m) {
- var p0 = m.p[0] - 1
- , p1 = m.p[1] - 1;
+ var p0 = Base.resultEntry(res, m.p[0]);
+ var p1 = Base.resultEntry(res, m.p[1]);
if (m.m[0] === m.m[1]) {
- res[p0].pts += this.tiePoints;
- res[p1].pts += this.tiePoints;
- res[p0].draws += 1;
- res[p1].draws += 1;
+ p0.pts += this.tiePoints;
+ p1.pts += this.tiePoints;
+ p0.draws += 1;
+ p1.draws += 1;
}
else {
var w = (m.m[0] > m.m[1]) ? p0 : p1;
var l = (m.m[0] > m.m[1]) ? p1 : p0;
- res[w].wins += 1;
- res[w].pts += this.winPoints;
- res[l].losses += 1;
+ w.wins += 1;
+ w.pts += this.winPoints;
+ l.losses += 1;
}
- res[p0].for += m.m[0];
- res[p1].for += m.m[1];
- res[p0].against += m.m[1];
- res[p1].against += m.m[0];
+ p0.for += m.m[0];
+ p1.for += m.m[1];
+ p0.against += m.m[1];
+ p1.against += m.m[0];
}.bind(this));
var scoresBreak = this.scoresBreak;
|
dont use res as a lookup map anymore
|
clux_groupstage
|
train
|
05d4de2b34463d3aa3f714ddb2bdf9b703aa005f
|
diff --git a/lib/dugway/liquid/filters/default_pagination.rb b/lib/dugway/liquid/filters/default_pagination.rb
index <HASH>..<HASH> 100755
--- a/lib/dugway/liquid/filters/default_pagination.rb
+++ b/lib/dugway/liquid/filters/default_pagination.rb
@@ -7,22 +7,22 @@ module Dugway
prev_label = prev_label.blank? ? paginate['previous']['title'] : prev_label
if paginate['previous']['is_link']
- html << %(<a class="previous" href="#{ paginate['previous']['url'] }">#{ prev_label }</a>)
+ html << %(<a class="previous" href="#{ paginate['previous']['url'] }" aria-label="Go to previous page">#{ prev_label }</a>)
else
html << %(<span class="previous disabled">#{ prev_label }</span>)
end
paginate['parts'].each do |part|
if part['is_link']
- html << %(<a href="#{ part['url'] }">#{ part['title'] }</a>)
+ html << %(<a href="#{ part['url'] }" aria-label="Go to page #{part['title']}">#{ part['title'] }</a>)
else
- html << %(<span class="#{ part['title'] == paginate['current_page'].to_s ? 'current' : 'gap' }">#{ part['title'] }</span>)
+ html << build_non_link_span(part, paginate)
end
end
next_label = next_label.blank? ? paginate['next']['title'] : next_label
if paginate['next']['is_link']
- html << %(<a class="next" href="#{ paginate['next']['url'] }">#{ next_label }</a>)
+ html << %(<a class="next" href="#{ paginate['next']['url'] }" aria-label="Go to next page">#{ next_label }</a>)
else
html << %(<span class="next disabled">#{ next_label }</span>)
end
@@ -30,6 +30,24 @@ module Dugway
html << %(</div>)
}.join(' ')
end
+
+ private
+
+ def build_non_link_span(part, paginate)
+ is_current = is_current_page?(part, paginate)
+ span_class = is_current ? 'current' : 'gap'
+
+ span = %(<span )
+ span << %(class="#{span_class}" )
+ span << %(aria-label="Current page, page #{part['title']}") if is_current
+ span << %(>)
+ span << %(#{ part['title'] }</span>)
+ span
+ end
+
+ def is_current_page?(part, paginate)
+ part['title'] == paginate['current_page'].to_s
+ end
end
end
end
|
Add ARIA attributes to pagination
I opted for aria-label instead of aria-current on the current page span.
VO was not picking up aria-current.
Resources consulted:
<URL>
|
bigcartel_dugway
|
train
|
e78a13f7174fc17b8bfc464e19c8c1e33c06e05c
|
diff --git a/src/Symfony/Component/Workflow/StateMachine.php b/src/Symfony/Component/Workflow/StateMachine.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Workflow/StateMachine.php
+++ b/src/Symfony/Component/Workflow/StateMachine.php
@@ -1,5 +1,14 @@
<?php
+/*
+ * This file is part of the Symfony package.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
namespace Symfony\Component\Workflow;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
|
[Workflow] Added missing license header
|
symfony_symfony
|
train
|
c82667f6bee35b835ce7522ec2b60b87fccd8540
|
diff --git a/VERSION b/VERSION
index <HASH>..<HASH> 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.5.5
+0.6.0
diff --git a/docs/conf.py b/docs/conf.py
index <HASH>..<HASH> 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -50,9 +50,9 @@ copyright = u'2011, andrews medina'
# built documents.
#
# The short X.Y version.
-version = '0.5.5'
+version = '0.6.0'
# The full version, including alpha/beta/rc tags.
-release = '0.5.5'
+release = '0.6.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -11,7 +11,7 @@ README = codecs.open('README.rst', encoding='utf-8').read()
setup(
name='splinter',
- version='0.5.5',
+ version='0.6.0',
description='browser abstraction for web acceptance testing',
long_description=README,
author='CobraTeam',
diff --git a/splinter/__init__.py b/splinter/__init__.py
index <HASH>..<HASH> 100644
--- a/splinter/__init__.py
+++ b/splinter/__init__.py
@@ -2,5 +2,5 @@
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-__version__ = '0.5.5'
+__version__ = '0.6.0'
from splinter.browser import Browser
|
setup: bump to <I>
|
cobrateam_splinter
|
train
|
d6615a716bd4cb0f8825989c2fe9add6d411b999
|
diff --git a/import_export/widgets.py b/import_export/widgets.py
index <HASH>..<HASH> 100644
--- a/import_export/widgets.py
+++ b/import_export/widgets.py
@@ -376,7 +376,7 @@ class ManyToManyWidget(Widget):
ids = [int(value)]
else:
ids = value.split(self.separator)
- ids = filter(None, [i.strip() for i in ids])
+ ids = filter(None, [i.strip() for i in ids])
return self.model.objects.filter(**{
'%s__in' % self.field: ids
})
|
Fixes error introduced in 5af<I>b<I>add<I>a<I>ddfc3fa<I>e0a1d4f<I>
ManyToManyWidget should strip only string items
|
django-import-export_django-import-export
|
train
|
0e07926ddedf767ed0ddc7148eb911b6fa2b3ea7
|
diff --git a/qunit/qunit.js b/qunit/qunit.js
index <HASH>..<HASH> 100644
--- a/qunit/qunit.js
+++ b/qunit/qunit.js
@@ -11,6 +11,35 @@
(function(window) {
var QUnit = {
+
+ // Initialize the configuration options
+ init: function init() {
+ config = {
+ stats: { all: 0, bad: 0 },
+ started: +new Date,
+ blocking: false,
+ assertions: [],
+ pollution: [],
+ filters: [],
+ queue: []
+ };
+
+ var tests = id("qunit-tests"),
+ banner = id("qunit-banner"),
+ result = id("qunit-testresult");
+
+ if ( tests ) {
+ tests.innerHTML = "";
+ }
+
+ if ( banner ) {
+ banner.className = "";
+ }
+
+ if ( result ) {
+ result.parentNode.removeChild( result );
+ }
+ },
// call on start of module test to prepend name to all tests
module: function module(name, lifecycle) {
@@ -271,20 +300,8 @@ var QUnit = {
// Maintain internal state
var config = {
- // Logging the passes and failures
- stats: {
- all: 0,
- bad: 0
- },
-
// The queue of tests to run
queue: [],
-
- // The log of global variables to check against
- pollution: [],
-
- // queue of test assertions
- assertions: [],
// block until document ready
blocking: true
@@ -322,6 +339,11 @@ if ( typeof exports === "undefined" || typeof require === "undefined" ) {
}
addEvent(window, "load", function() {
+ // Initialize the config, saving the execution queue
+ var queue = config.queue;
+ QUnit.init();
+ config.queue = queue;
+
var userAgent = id("qunit-userAgent");
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
@@ -370,8 +392,6 @@ addEvent(window, "load", function() {
toolbar.appendChild( label );
}
- config.started = +new Date;
-
var main = id('main');
if ( main ) {
config.fixture = main.innerHTML;
|
Made it so that you can reset the suite to an initial state (at which point tests can be dynamically loaded and run, for example).
|
JamesMGreene_qunit-assert-html
|
train
|
c4992a2a76f16cb62e5dff1d835098cd6d6e2189
|
diff --git a/dev/com.ibm.ws.webcontainer.security.jacc.1.5_fat/fat/src/com/ibm/ws/webcontainer/security/jacc15/fat/BasicAuthTest.java b/dev/com.ibm.ws.webcontainer.security.jacc.1.5_fat/fat/src/com/ibm/ws/webcontainer/security/jacc15/fat/BasicAuthTest.java
index <HASH>..<HASH> 100644
--- a/dev/com.ibm.ws.webcontainer.security.jacc.1.5_fat/fat/src/com/ibm/ws/webcontainer/security/jacc15/fat/BasicAuthTest.java
+++ b/dev/com.ibm.ws.webcontainer.security.jacc.1.5_fat/fat/src/com/ibm/ws/webcontainer/security/jacc15/fat/BasicAuthTest.java
@@ -104,7 +104,7 @@ public class BasicAuthTest extends CommonServletTestScenarios {
@AfterClass
public static void tearDown() throws Exception {
try {
- myServer.stopServer("CWWKS5524E");
+ myServer.stopServer("CWWKZ0013E");
} finally {
JACCFatUtils.uninstallJaccUserFeature(myServer);
}
|
Ignore error messages when the same application tries to to come up twice. This can occur when we are doing dynamic server configuration updates.
|
OpenLiberty_open-liberty
|
train
|
4c18ece95da9eae8335b206c0a30bbb536d65919
|
diff --git a/client/my-sites/checkout/composite-checkout/wpcom/components/wp-checkout.js b/client/my-sites/checkout/composite-checkout/wpcom/components/wp-checkout.js
index <HASH>..<HASH> 100644
--- a/client/my-sites/checkout/composite-checkout/wpcom/components/wp-checkout.js
+++ b/client/my-sites/checkout/composite-checkout/wpcom/components/wp-checkout.js
@@ -130,7 +130,7 @@ export default function WPCheckout( {
const validateContactDetailsAndDisplayErrors = async () => {
debug( 'validating contact details with side effects' );
- if ( shouldShowDomainContactFields ) {
+ if ( areThereDomainProductsInCart ) {
const validationResult = await getDomainValidationResult( items, contactInfo );
debug( 'validating contact details result', validationResult );
handleContactValidationResult( {
@@ -157,7 +157,7 @@ export default function WPCheckout( {
};
const validateContactDetails = async () => {
debug( 'validating contact details' );
- if ( shouldShowDomainContactFields ) {
+ if ( areThereDomainProductsInCart ) {
const validationResult = await getDomainValidationResult( items, contactInfo );
debug( 'validating contact details result', validationResult );
return isContactValidationResponseValid( validationResult, contactInfo );
|
Do not run domain validation for GSuite (#<I>)
|
Automattic_wp-calypso
|
train
|
58604849c5cc05603e2619b153673458b6c7960b
|
diff --git a/versionner/cli.py b/versionner/cli.py
index <HASH>..<HASH> 100755
--- a/versionner/cli.py
+++ b/versionner/cli.py
@@ -205,9 +205,14 @@ def command_up(cfg, args):
:param args:
:return:
"""
+
version_file = version.VersionFile(args.version_file)
- current = version_file.read()
+ try:
+ current = version_file.read()
+ except FileNotFoundError:
+ print('Version file not found', file=sys.stderr)
+ sys.exit(1)
if args.major:
new = current.up('major', args.value)
@@ -234,9 +239,14 @@ def command_set(cfg, args):
:param args:
:return:
"""
+
version_file = version.VersionFile(args.version_file)
- current = version_file.read()
+ try:
+ current = version_file.read()
+ except FileNotFoundError:
+ print('Version file not found', file=sys.stderr)
+ sys.exit(1)
if args.value:
parsed = semver.parse(args.value)
|
if version file does not exists, then fail with noce message instead of python exception on stderr
|
msztolcman_versionner
|
train
|
6bab61754d4b7571c3cad4167197e21aeece02e3
|
diff --git a/lib/File.js b/lib/File.js
index <HASH>..<HASH> 100644
--- a/lib/File.js
+++ b/lib/File.js
@@ -466,7 +466,7 @@ module.exports = class File {
if (err) return fn(err);
mkdir(filepath);
- writeFile(filepath, this.content, 'utf8');
+ writeFile(filepath, this.content, this.encoding);
fn(null, {
filepath,
|
fix missing encoding type on write
|
popeindustries_buddy
|
train
|
304bd939cec27d60bd3e24426c5d4182fc835367
|
diff --git a/consoleprinter/__init__.py b/consoleprinter/__init__.py
index <HASH>..<HASH> 100644
--- a/consoleprinter/__init__.py
+++ b/consoleprinter/__init__.py
@@ -1076,7 +1076,8 @@ def console(*args, **kwargs):
print(s)
return
global g_start_time
- runtime = "%0.2f" % float(time.time() - g_start_time)
+
+ runtime = "%0.2f" % (1000*float(time.time() - g_start_time))
arglist = list(args)
line_num_only = 3
once = False
@@ -1095,7 +1096,7 @@ def console(*args, **kwargs):
plainprint = check_for_positional_arguments(kwargs, ["plaintext", "plain_text", "plainprint", "plain_print"])
return_string = check_for_positional_arguments(kwargs, ["ret_str", "retval", "ret_val"])
newline = check_for_positional_argument(kwargs, "newline", default=True)
- fileref = check_for_positional_argument(kwargs, "fileref", default=True)
+ fileref = check_for_positional_argument(kwargs, "fileref", default=False)
indent = ""
if prefix is not None:
@@ -1198,7 +1199,7 @@ def console(*args, **kwargs):
source_code_link_msg += "\n\t"
- if not print_stack and fileref is False:
+ if not print_stack and fileref is True:
if line_num_only >= 0:
if return_string is False:
subs = " | " + colors[color] + source_code_link_msg + colors[color]
|
Tyler Perry: War is Gods way of teaching Americans geography.
Thursday <I> June <I> (week:<I> day:<I>), <I>:<I>:<I>
|
erikdejonge_consoleprinter
|
train
|
137ee6695548d7e5c0de2938377a3492a7990025
|
diff --git a/src/json-patch-ot-agent.js b/src/json-patch-ot-agent.js
index <HASH>..<HASH> 100644
--- a/src/json-patch-ot-agent.js
+++ b/src/json-patch-ot-agent.js
@@ -17,7 +17,7 @@ var JSONPatchOTAgent = function(transform, versionPaths, apply, purity){
*/
this.apply = JSONPatchOTAgent.applyOT( apply );
/**
- * History of performed JSON Patch sequences that maight not yet be acknowledged by Peer
+ * History of performed JSON Patch sequences that might not yet be acknowledged by Peer
* @type {Array<JSONPatch>}
*/
this.pending = [];
@@ -73,3 +73,14 @@ JSONPatchOTAgent.applyOT = function(callback){
callback(obj, consecutivePatch);
};
};
+
+/**
+ * Reset queue internals and object to new, given state
+ * @param obj object to apply new state to
+ * @param newState versioned object representing desired state along with versions
+ */
+JSONPatchOTAgent.prototype.reset = function(obj, newState){
+ this.ackLocalVersion = newState[this.localPath.replace(/^\//, '')];
+ this.pending = [];
+ JSONPatchQueue.prototype.reset.call(this, obj, newState);
+};
\ No newline at end of file
|
Add reset function to support reconnection in puppetjs/puppetjs#<I>
|
Palindrom_JSON-Patch-OT-agent
|
train
|
74fe279cee8f31b960b0a8d760f79e8b3167c51c
|
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -23,7 +23,10 @@ end
RSpec.configure do |c|
c.include PortalCleanup
- c.before(:all) { configure_test_portal }
+ c.before(:all) do
+ DATA_COLLECTOR.clear
+ configure_test_portal
+ end
end
shared_examples_for 'an api request' do |*flags|
|
Clean test data for separate spec (#<I>)
Before DATA_COLLECTOR keep same between
several spec if run at once
It was messed up
|
ONLYOFFICE_onlyoffice_api_gem
|
train
|
8c3648b1d5e6591f8cfacb72e2cb9bf0a5f4b593
|
diff --git a/moco-runner/src/main/java/com/github/dreamhead/moco/parser/model/SessionSetting.java b/moco-runner/src/main/java/com/github/dreamhead/moco/parser/model/SessionSetting.java
index <HASH>..<HASH> 100644
--- a/moco-runner/src/main/java/com/github/dreamhead/moco/parser/model/SessionSetting.java
+++ b/moco-runner/src/main/java/com/github/dreamhead/moco/parser/model/SessionSetting.java
@@ -156,7 +156,7 @@ public final class SessionSetting {
return server;
}
- ActualHttpServer server = ActualHttpServer.createHttpServer(port, quiet);
+ ActualHttpServer server = ActualHttpServer.createHttpServer(port, quiet, configs);
bindTo(server);
return server;
}
|
fixed build for missing configs in session setting
|
dreamhead_moco
|
train
|
6e4ad144e1220a7d62bc67013151a7ad6b932fe0
|
diff --git a/functional_consumer_group_test.go b/functional_consumer_group_test.go
index <HASH>..<HASH> 100644
--- a/functional_consumer_group_test.go
+++ b/functional_consumer_group_test.go
@@ -146,12 +146,81 @@ func TestFuncConsumerGroupFuzzy(t *testing.T) {
}
}
+func TestFuncConsumerGroupOffsetDeletion(t *testing.T) {
+ checkKafkaVersion(t, "2.4.0")
+ setupFunctionalTest(t)
+ defer teardownFunctionalTest(t)
+ // create a client with 2.4.0 version as it is the minimal version
+ // that supports DeleteOffsets request
+ config := NewTestConfig()
+ config.Version = V2_4_0_0
+ client, err := NewClient(FunctionalTestEnv.KafkaBrokerAddrs, config)
+ defer safeClose(t, client)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // create a consumer group with offsets on
+ // - topic test.1 partition 0
+ // - topic test.4 partition 0
+ groupID := testFuncConsumerGroupID(t)
+ consumerGroup, err := NewConsumerGroupFromClient(groupID, client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer safeClose(t, consumerGroup)
+
+ offsetMgr, _ := NewOffsetManagerFromClient(groupID, client)
+ defer safeClose(t, offsetMgr)
+ markOffset(t, offsetMgr, "test.1", 0, 1)
+ markOffset(t, offsetMgr, "test.4", 0, 2)
+ offsetMgr.Commit()
+
+ admin, err := NewClusterAdminFromClient(client)
+ if err != nil {
+ t.Fatal(err)
+ }
+ offsetFetch, err := admin.ListConsumerGroupOffsets(groupID, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(offsetFetch.Blocks) != 2 {
+ t.Fatal("Expected offsets on two topics. Found offsets on ", len(offsetFetch.Blocks), "topics.")
+ }
+
+ // Delete offset for partition topic test.4 partition 0
+ err = admin.DeleteConsumerGroupOffset(groupID, "test.4", 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ offsetFetch, err = admin.ListConsumerGroupOffsets(groupID, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(offsetFetch.Blocks) != 1 {
+ t.Fatal("Expected offsets on one topic. Found offsets on ", len(offsetFetch.Blocks), "topics.")
+ }
+ if offsetFetch.Blocks["test.4"] != nil {
+ t.Fatal("Offset still exists for topic 'topic.4'. It should have been deleted.")
+ }
+}
+
// --------------------------------------------------------------------
func testFuncConsumerGroupID(t *testing.T) string {
return fmt.Sprintf("sarama.%s%d", t.Name(), time.Now().UnixNano())
}
+func markOffset(t *testing.T, offsetMgr OffsetManager, topic string, partition int32, offset int64) {
+ partitionOffsetManager, err := offsetMgr.ManagePartition(topic, partition)
+ defer safeClose(t, partitionOffsetManager)
+ if err != nil {
+ t.Fatal(err)
+ }
+ partitionOffsetManager.MarkOffset(offset, "")
+}
+
func testFuncConsumerGroupFuzzySeed(topic string) error {
client, err := NewClient(FunctionalTestEnv.KafkaBrokerAddrs, NewTestConfig())
if err != nil {
|
Add functional test for DeleteOffsetsRequest
|
Shopify_sarama
|
train
|
d709eee8276f3141aa279fbcfad447b89dba3885
|
diff --git a/src/Event/ValueObjects/AudienceType.php b/src/Event/ValueObjects/AudienceType.php
index <HASH>..<HASH> 100644
--- a/src/Event/ValueObjects/AudienceType.php
+++ b/src/Event/ValueObjects/AudienceType.php
@@ -17,4 +17,4 @@ class AudienceType extends Enum
const EVERYONE = 'everyone';
const MEMBERS = 'members';
const EDUCATION = 'education';
-}
\ No newline at end of file
+}
|
III-<I> Fixed coding standards.
|
cultuurnet_udb3-php
|
train
|
7b378da7c3d8cbf71f09316b21680a468f7e508c
|
diff --git a/src/main/java/net/entropysoft/transmorph/converters/beans/BeanToBean.java b/src/main/java/net/entropysoft/transmorph/converters/beans/BeanToBean.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/entropysoft/transmorph/converters/beans/BeanToBean.java
+++ b/src/main/java/net/entropysoft/transmorph/converters/beans/BeanToBean.java
@@ -36,8 +36,6 @@ import net.entropysoft.transmorph.type.Type;
*
*/
public class BeanToBean extends AbstractContainerConverter {
-
- private JavaTypeToTypeSignature javaTypeSignature = new JavaTypeToTypeSignature();
private IBeanPropertyTypeProvider beanDestinationPropertyTypeProvider;
private Map<ClassPair, BeanToBeanMapping> beanToBeanMappings = new HashMap<ClassPair, BeanToBeanMapping>();
@@ -120,10 +118,7 @@ public class BeanToBean extends AbstractContainerConverter {
java.lang.reflect.Type parameterType = destinationMethod
.getGenericParameterTypes()[0];
- TypeSignature parameterTypeSignature = javaTypeSignature
- .getTypeSignature(parameterType);
- Type originalType = destinationType.getTypeFactory().getType(
- parameterTypeSignature);
+ Type originalType = destinationType.getTypeFactory().getType(parameterType);
Type propertyDestinationType = getBeanPropertyType(resultBean
.getClass(), destinationPropertyName, originalType);
diff --git a/src/main/java/net/entropysoft/transmorph/converters/beans/MapToBean.java b/src/main/java/net/entropysoft/transmorph/converters/beans/MapToBean.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/entropysoft/transmorph/converters/beans/MapToBean.java
+++ b/src/main/java/net/entropysoft/transmorph/converters/beans/MapToBean.java
@@ -37,14 +37,12 @@ import net.entropysoft.transmorph.type.Type;
*
*/
public class MapToBean extends AbstractContainerConverter {
-
- private JavaTypeToTypeSignature javaTypeSignature = new JavaTypeToTypeSignature();
private IBeanPropertyTypeProvider beanDestinationPropertyTypeProvider;
public MapToBean() {
this.useObjectPool = true;
}
-
+
public IBeanPropertyTypeProvider getBeanDestinationPropertyTypeProvider() {
return beanDestinationPropertyTypeProvider;
}
@@ -59,7 +57,8 @@ public class MapToBean extends AbstractContainerConverter {
this.beanDestinationPropertyTypeProvider = beanDestinationPropertyTypeProvider;
}
- public Object doConvert(ConversionContext context, Object sourceObject, Type destinationType) throws ConverterException {
+ public Object doConvert(ConversionContext context, Object sourceObject,
+ Type destinationType) throws ConverterException {
if (sourceObject == null) {
return null;
}
@@ -82,9 +81,10 @@ public class MapToBean extends AbstractContainerConverter {
.getName()), e);
}
if (useObjectPool) {
- context.getConvertedObjectPool().add(this, sourceObject, destinationType, resultBean);
+ context.getConvertedObjectPool().add(this, sourceObject,
+ destinationType, resultBean);
}
-
+
for (String key : sourceMap.keySet()) {
Object value = sourceMap.get(key);
Method method = getSetterMethod(setterMethods, key);
@@ -95,15 +95,13 @@ public class MapToBean extends AbstractContainerConverter {
}
java.lang.reflect.Type parameterType = method
.getGenericParameterTypes()[0];
- TypeSignature parameterTypeSignature = javaTypeSignature
- .getTypeSignature(parameterType);
Type originalType = destinationType.getTypeFactory().getType(
- parameterTypeSignature);
- Type propertyDestinationType = getBeanPropertyType(
- resultBean.getClass(), key, originalType);
+ parameterType);
+ Type propertyDestinationType = getBeanPropertyType(resultBean
+ .getClass(), key, originalType);
- Object valueConverterd = elementConverter.convert(context,
- value, propertyDestinationType);
+ Object valueConverterd = elementConverter.convert(context, value,
+ propertyDestinationType);
try {
method.invoke(resultBean, valueConverterd);
@@ -121,8 +119,7 @@ public class MapToBean extends AbstractContainerConverter {
Type propertyDestinationType = null;
if (beanDestinationPropertyTypeProvider != null) {
propertyDestinationType = beanDestinationPropertyTypeProvider
- .getPropertyType(clazz, propertyName,
- originalType);
+ .getPropertyType(clazz, propertyName, originalType);
}
if (propertyDestinationType == null) {
propertyDestinationType = originalType;
@@ -132,7 +129,8 @@ public class MapToBean extends AbstractContainerConverter {
protected Method getSetterMethod(Map<String, Method> setterMethods,
String propertyName) {
- String methodName = "set" + BeanUtils.capitalizePropertyName(propertyName);
+ String methodName = "set"
+ + BeanUtils.capitalizePropertyName(propertyName);
return setterMethods.get(methodName);
}
|
removed javaTypeSignature instance from BeanToBean and MapToBean
|
cchabanois_transmorph
|
train
|
b91d59057031d71d9f51f017d2962b8ec5a90a93
|
diff --git a/src/Dexie.js b/src/Dexie.js
index <HASH>..<HASH> 100644
--- a/src/Dexie.js
+++ b/src/Dexie.js
@@ -1463,8 +1463,8 @@ export default function Dexie(dbName, options) {
if (this._locked()) {
return new Promise((resolve, reject) => {
- self._blockedFuncs.push([() => {
- self._promise(mode, fn, bWriteLock).then(resolve, reject);
+ this._blockedFuncs.push([() => {
+ this._promise(mode, fn, bWriteLock).then(resolve, reject);
}, PSD]);
});
|
Whoops, used self instead of this.
|
dfahlander_Dexie.js
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.