hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
72405aaebc69b407112899a54a840f0d8c62930b
|
diff --git a/Classes/Configuration/ConfigurationRegistry.php b/Classes/Configuration/ConfigurationRegistry.php
index <HASH>..<HASH> 100644
--- a/Classes/Configuration/ConfigurationRegistry.php
+++ b/Classes/Configuration/ConfigurationRegistry.php
@@ -201,7 +201,9 @@ class ConfigurationRegistry
/** @var TemplateService $template */
$template = GeneralUtility::makeInstance(TemplateService::class);
$template->tt_track = 0;
- $template->init();
+ if (Typo3Version::isNotHigherThan(8)) {
+ $template->init();
+ }
/** @var PageRepository $page */
$page = GeneralUtility::makeInstance(PageRepository::class);
diff --git a/Classes/Templating/TemplateHelper.php b/Classes/Templating/TemplateHelper.php
index <HASH>..<HASH> 100644
--- a/Classes/Templating/TemplateHelper.php
+++ b/Classes/Templating/TemplateHelper.php
@@ -245,7 +245,9 @@ class TemplateHelper extends SalutationSwitcher
$template = GeneralUtility::makeInstance(TemplateService::class);
// Disables the logging of time-performance information.
$template->tt_track = 0;
- $template->init();
+ if (Typo3Version::isNotHigherThan(8)) {
+ $template->init();
+ }
/** @var PageRepository $page */
$page = GeneralUtility::makeInstance(PageRepository::class);
|
[CLEANUP] Stop calling $template->init in TYPO3 V9 (#<I>)
Closes #<I>
|
oliverklee_ext-oelib
|
train
|
4e8a391d2df2a34fd99a5f6ddc615716addd8550
|
diff --git a/src/animation.js b/src/animation.js
index <HASH>..<HASH> 100644
--- a/src/animation.js
+++ b/src/animation.js
@@ -56,6 +56,10 @@ Crafty.c("SpriteAnimation", {
if (y === -1) this._frame.repeatInfinitly = true;
else this._frame.repeat = y;
}
+ var pos = this._frame.reel[0];
+ this.__coord[0] = pos[0];
+ this.__coord[1] = pos[1];
+
this.bind("enterframe", this.drawFrame);
return this;
}
|
Make sure the animation is started right away
ref: <URL>
|
craftyjs_Crafty
|
train
|
ac0d89c38b55f772f0016ebbcb7e70b8cb1bde17
|
diff --git a/php/commands/db.php b/php/commands/db.php
index <HASH>..<HASH> 100644
--- a/php/commands/db.php
+++ b/php/commands/db.php
@@ -64,7 +64,7 @@ class DB_Command extends WP_CLI_Command {
* @synopsis [--str]
*/
function optimize( $_, $assoc_args ) {
- self::run( $assoc_args, self::create_cmd(
+ self::run( $assoc_args, \WP_CLI\Utils\create_cmd(
'mysqlcheck --optimize --host=%s --user=%s --password=%s %s',
DB_HOST, DB_USER, DB_PASSWORD, DB_NAME
) );
@@ -78,7 +78,7 @@ class DB_Command extends WP_CLI_Command {
* @synopsis [--str]
*/
function repair( $_, $assoc_args ) {
- self::run( $assoc_args, self::create_cmd(
+ self::run( $assoc_args, \WP_CLI\Utils\create_cmd(
'mysqlcheck --repair --host=%s --user=%s --password=%s %s',
DB_HOST, DB_USER, DB_PASSWORD, DB_NAME
) );
@@ -105,7 +105,7 @@ class DB_Command extends WP_CLI_Command {
function query( $args, $assoc_args ) {
list( $query ) = $args;
- self::run( $assoc_args, $this->connect_string() . self::create_cmd(
+ self::run( $assoc_args, $this->connect_string() . \WP_CLI\Utils\create_cmd(
' --execute=%s', $query ) );
}
@@ -118,7 +118,7 @@ class DB_Command extends WP_CLI_Command {
function export( $args, $assoc_args ) {
$result_file = $this->get_file_name( $args );
- self::run( $assoc_args, self::create_cmd(
+ self::run( $assoc_args, \WP_CLI\Utils\create_cmd(
'mysqldump %s --user=%s --password=%s --host=%s --result-file %s',
DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, $result_file ) );
@@ -133,7 +133,7 @@ class DB_Command extends WP_CLI_Command {
function import( $args, $assoc_args ) {
$result_file = $this->get_file_name( $args );
- self::run( $assoc_args, self::create_cmd(
+ self::run( $assoc_args, \WP_CLI\Utils\create_cmd(
'mysql %s --user=%s --password=%s --host=%s < %s',
DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, $result_file ) );
@@ -141,7 +141,7 @@ class DB_Command extends WP_CLI_Command {
}
private function connect_string() {
- return self::create_cmd( 'mysql --host=%s --user=%s --password=%s --database=%s',
+ return \WP_CLI\Utils\create_cmd( 'mysql --host=%s --user=%s --password=%s --database=%s',
DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
}
@@ -153,24 +153,12 @@ class DB_Command extends WP_CLI_Command {
}
private static function create_execute_cmd( $execute_statement ) {
- return self::create_cmd(
+ return \WP_CLI\Utils\create_cmd(
'mysql --host=%s --user=%s --password=%s --execute=%s',
DB_HOST, DB_USER, DB_PASSWORD, $execute_statement
);
}
- /**
- * Given a formatted string and an arbitrary number of arguments,
- * returns the final command, with the parameters escaped
- */
- private static function create_cmd( $cmd ) {
- $args = func_get_args();
-
- $cmd = array_shift( $args );
-
- return vsprintf( $cmd, array_map( 'escapeshellarg', $args ) );
- }
-
private static function run( $assoc_args, $cmd ) {
if ( isset( $assoc_args['str'] ) ) {
WP_CLI::line( $cmd );
diff --git a/php/utils.php b/php/utils.php
index <HASH>..<HASH> 100644
--- a/php/utils.php
+++ b/php/utils.php
@@ -100,6 +100,18 @@ function assoc_args_to_str( $assoc_args ) {
return $str;
}
+/**
+ * Given a template string and an arbitrary number of arguments,
+ * returns the final command, with the parameters escaped.
+ */
+function create_cmd( $cmd ) {
+ $args = func_get_args();
+
+ $cmd = array_shift( $args );
+
+ return vsprintf( $cmd, array_map( 'escapeshellarg', $args ) );
+}
+
function get_command_file( $command ) {
$path = WP_CLI_ROOT . "/commands/$command.php";
|
move create_cmd() utility out of DB_Command
|
wp-cli_extension-command
|
train
|
874ce8e13860105fbab556354c718a632cabb189
|
diff --git a/jqm-all/jqm-client/jqm-api-client-jersey/src/test/java/com/enioka/jqm/tools/BasicTest.java b/jqm-all/jqm-client/jqm-api-client-jersey/src/test/java/com/enioka/jqm/tools/BasicTest.java
index <HASH>..<HASH> 100644
--- a/jqm-all/jqm-client/jqm-api-client-jersey/src/test/java/com/enioka/jqm/tools/BasicTest.java
+++ b/jqm-all/jqm-client/jqm-api-client-jersey/src/test/java/com/enioka/jqm/tools/BasicTest.java
@@ -206,9 +206,10 @@ public class BasicTest
Assert.assertEquals(State.RUNNING, JqmClientFactory.getClient().getJob(i).getState());
JqmClientFactory.getClient().killJob(i);
Assert.assertTrue(JqmClientFactory.getClient().getJob(i).getState().equals(State.KILLED));
+ Thread.sleep(500);
// Get messages too
- Assert.assertEquals(3, JqmClientFactory.getClient().getJobMessages(i).size());
+ Assert.assertEquals(4, JqmClientFactory.getClient().getJobMessages(i).size());
// Finally, a query
Assert.assertEquals(1, Query.create().setApplicationName("MarsuApplication").run().size());
|
Testfix: wrong number of messages in WS test
Was often hidden by: test did not wait enough for job completion.
|
enioka_jqm
|
train
|
5ce85519a0553fa14d09fb78398d16dcdef19d95
|
diff --git a/packages/core/src/combinator/delay.js b/packages/core/src/combinator/delay.js
index <HASH>..<HASH> 100644
--- a/packages/core/src/combinator/delay.js
+++ b/packages/core/src/combinator/delay.js
@@ -35,7 +35,7 @@ class DelaySink extends Pipe {
}
dispose () {
- cancelAllTasks(task => task.sink === this.sink, this.scheduler)
+ cancelAllTasks(({ task }) => task.sink === this.sink, this.scheduler)
}
event (t, x) {
|
fix(delay) fixes the cancelAll predicate within DelaySink dispose
|
mostjs_core
|
train
|
3d74e8db0cf359321697913cf949dd7a24203a97
|
diff --git a/lib/arid_cache/helpers.rb b/lib/arid_cache/helpers.rb
index <HASH>..<HASH> 100644
--- a/lib/arid_cache/helpers.rb
+++ b/lib/arid_cache/helpers.rb
@@ -64,22 +64,16 @@ module AridCache
private
def method_for_cached(object, key, fetch_method=:fetch, method_name=nil)
- method_name = "cached_" + (method_name || key)
- if object.is_a?(Class)
- (class << object; self; end).instance_eval do
- define_method(method_name) do |*args, &block|
- opts = args.empty? ? {} : args.first
- AridCache.cache.send(fetch_method, self, key, opts, &block)
- end
+ method_name = ("cached_" + (method_name || key)).gsub(/[^\w\!\?]/, '_')
+ method_body = <<-END
+ def #{method_name}(*args, &block)
+ opts = args.empty? ? {} : args.first
+ AridCache.cache.send(#{fetch_method.inspect}, self, #{key.inspect}, opts, &block)
end
- else
- object.class_eval do
- define_method(method_name) do |*args, &block|
- opts = args.empty? ? {} : args.first
- AridCache.cache.send(fetch_method, self, key, opts, &block)
- end
- end
- end
+ END
+ # Get the correct object
+ object = (class << object; self; end) if object.is_a?(Class)
+ object.class_eval(method_body, __FILE__, __LINE__)
end
end
end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index <HASH>..<HASH> 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -54,4 +54,4 @@ require 'db/prepare'
ActiveRecord::Base.logger.info("#{"="*25} RUNNING UNIT TESTS #{"="*25}\n\t\t\t#{Time.now.to_s}\n#{"="*70}")
-
+Array.class_eval { alias count size } if RUBY_VERSION < '1.8.7'
\ No newline at end of file
|
Refactor to use instance / class eval with a string as ruby < <I> doesn't support passing blocks to blocks.
|
kjvarga_arid_cache
|
train
|
0cd43aefee6a5a4228c72fd5322bdb4b175315f4
|
diff --git a/source/rafcon/mvc/history.py b/source/rafcon/mvc/history.py
index <HASH>..<HASH> 100755
--- a/source/rafcon/mvc/history.py
+++ b/source/rafcon/mvc/history.py
@@ -95,6 +95,7 @@ def get_state_tuple(state, state_m=None):
class NotificationOverview(dict):
+ # TODO generalize and include into utils
def __init__(self, info, with_prints=False):
@@ -982,14 +983,19 @@ class AddObjectAction(Action):
class CoreObjectIdentifier:
-
- type_related_list_name_dict = {'InputDataPort': 'input_data_ports', 'OutputDataPort': 'output_data_ports',
- 'ScopedVariable': 'scoped_variables', 'DataFlow': 'data_flows',
- 'Outcome': 'outcomes', 'Transition': 'transitions', 'State': 'states'}
-
- def __init__(self, core_obj_cls):
- assert type(core_obj_cls) in core_object_list or core_obj_cls in core_object_list
- print core_obj_cls
+ # TODO generalize and include into utils
+
+ type_related_list_name_dict = {InputDataPort.__name__: 'input_data_ports',
+ OutputDataPort.__name__: 'output_data_ports',
+ ScopedVariable.__name__: 'scoped_variables',
+ DataFlow.__name__: 'data_flows',
+ Outcome.__name__: 'outcomes',
+ Transition.__name__: 'transitions',
+ State.__name__: 'states'}
+
+ def __init__(self, core_obj_or_cls):
+ assert type(core_obj_or_cls) in core_object_list or core_obj_or_cls in core_object_list
+ print core_obj_or_cls
self._sm_id = None
self._path = None
# type can be, object types (of type Transition e.g.) or class
@@ -997,35 +1003,34 @@ class CoreObjectIdentifier:
self._id = None
self._list_name = None
- if type(core_obj_cls) in core_object_list:
- self._type = str(type(core_obj_cls)).split("'")[-2].split('.')[-1]
+ if type(core_obj_or_cls) in core_object_list:
+ self._type = type(core_obj_or_cls).__name__
else:
self._type = 'class'
if not self._type == 'class':
if self._type in ['ExecutionState', 'HierarchyState', 'BarrierConcurrencyState', 'PreemptiveConcurrencyState']:
- self._path = core_obj_cls.get_path()
- self._id = core_obj_cls.state_id
- self._sm_id = core_obj_cls.get_sm_for_state().state_machine_id
+ self._path = core_obj_or_cls.get_path()
+ self._id = core_obj_or_cls.state_id
+ self._sm_id = core_obj_or_cls.get_sm_for_state().state_machine_id
else:
- if core_obj_cls.parent:
- self._path = core_obj_cls.parent.get_path()
- self._sm_id = core_obj_cls.parent.get_sm_for_state().state_machine_id
+ if isinstance(core_obj_or_cls.parent, State):
+ self._path = core_obj_or_cls.parent.get_path()
+ self._sm_id = core_obj_or_cls.parent.get_sm_for_state().state_machine_id
else:
logger.warning("identifier of core object {0} without parent is mostly useless".format(self._type))
if self._type in ['InputDataPort', 'OutputDataPort', 'ScopedVariable']:
- self._id = core_obj_cls.data_port_id
+ self._id = core_obj_or_cls.data_port_id
self._list_name = self.type_related_list_name_dict[self._type]
elif self._type == 'Transition':
- print "get transition id of: " + str(core_obj_cls)
- self._id = core_obj_cls.transition_id
+ self._id = core_obj_or_cls.transition_id
self._list_name = self.type_related_list_name_dict[self._type]
elif self._type == 'DataFlow':
- self._id = core_obj_cls.data_flow_id
+ self._id = core_obj_or_cls.data_flow_id
self._list_name = self.type_related_list_name_dict[self._type]
elif self._type == 'Outcome':
- self._id = core_obj_cls.outcome_id
+ self._id = core_obj_or_cls.outcome_id
self._list_name = self.type_related_list_name_dict[self._type]
elif self._type == 'StateMachine':
# self.__sm_id = core_obj_cls.state_machine_id
|
modify mvc/history CoreObjectIdentifier for better understanding and some TODOs
|
DLR-RM_RAFCON
|
train
|
08fdf3a458d04b0f013fb94f4ec3088146f4a336
|
diff --git a/js/coinexchange.js b/js/coinexchange.js
index <HASH>..<HASH> 100644
--- a/js/coinexchange.js
+++ b/js/coinexchange.js
@@ -543,6 +543,7 @@ module.exports = class coinexchange extends Exchange {
'GDC': 'GoldenCryptoCoin',
'HNC': 'Huncoin',
'MARS': 'MarsBux',
+ 'MER': 'TheMermaidCoin',
'RUB': 'RubbleCoin',
},
});
|
coinexchange MER → TheMermaidCoin fix #<I>
|
ccxt_ccxt
|
train
|
a7616859d00e9926c88281bbe94ff1ac5242944e
|
diff --git a/spec/operators/sampleTime-spec.js b/spec/operators/sampleTime-spec.js
index <HASH>..<HASH> 100644
--- a/spec/operators/sampleTime-spec.js
+++ b/spec/operators/sampleTime-spec.js
@@ -1,48 +1,73 @@
-/* globals describe, it, expect, expectObservable, hot, rxTestScheduler */
+/* globals describe, it, expect, expectObservable, expectSubscriptions, cold, hot, rxTestScheduler */
var Rx = require('../../dist/cjs/Rx');
var Observable = Rx.Observable;
describe('Observable.prototype.sampleTime', function () {
it('should get samples on a delay', function () {
var e1 = hot('----a-^--b----c----d----e----f----|');
+ var e1subs = '^ !';
var expected = '-----------c----------e-----|';
// timer -----------!----------!---------
+
expectObservable(e1.sampleTime(110, rxTestScheduler)).toBe(expected);
+ expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should sample nothing if source has not nexted by time of sample', function () {
var e1 = hot('----a-^-------------b-------------|');
+ var e1subs = '^ !';
var expected = '----------------------b-----|';
// timer -----------!----------!---------
+
expectObservable(e1.sampleTime(110, rxTestScheduler)).toBe(expected);
+ expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should raise error if source raises error', function () {
var e1 = hot('----a-^--b----c----d----#');
+ var e1subs = '^ !';
var expected = '-----------c------#';
// timer -----------!----------!---------
expectObservable(e1.sampleTime(110, rxTestScheduler)).toBe(expected);
+ expectSubscriptions(e1.subscriptions).toBe(e1subs);
+ });
+
+ it('should allow unsubscribing explicitly and early', function () {
+ var e1 = hot('----a-^--b----c----d----e----f----|');
+ var unsub = ' ! ';
+ var e1subs = '^ ! ';
+ var expected = '-----------c----- ';
+ // timer -----------!----------!---------
+
+ expectObservable(e1.sampleTime(110, rxTestScheduler), unsub).toBe(expected);
+ expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should completes if source does not emits', function () {
- var e1 = Observable.empty();
+ var e1 = cold('|');
+ var e1subs = '(^!)';
var expected = '|';
expectObservable(e1.sampleTime(60, rxTestScheduler)).toBe(expected);
+ expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should raise error if source throws immediately', function () {
- var e1 = Observable.throw('error');
+ var e1 = cold('#');
+ var e1subs = '(^!)';
var expected = '#';
expectObservable(e1.sampleTime(60, rxTestScheduler)).toBe(expected);
+ expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
it('should not completes if source does not complete', function () {
- var e1 = Observable.never();
+ var e1 = cold('-');
+ var e1subs = '^';
var expected = '-';
expectObservable(e1.sampleTime(60, rxTestScheduler)).toBe(expected);
+ expectSubscriptions(e1.subscriptions).toBe(e1subs);
});
});
\ No newline at end of file
|
test(sampleTime): add subscription assertions on sampleTime tests
|
ReactiveX_rxjs
|
train
|
ddfe7773d4689473525e2925d232889b4d6d6f90
|
diff --git a/spec/app/models/definition.rb b/spec/app/models/definition.rb
index <HASH>..<HASH> 100644
--- a/spec/app/models/definition.rb
+++ b/spec/app/models/definition.rb
@@ -4,5 +4,6 @@ class Definition
field :p, as: :part, type: String
field :regular, type: Boolean
field :syn, as: :synonyms, localize: true, type: String
+ field :active, type: Boolean, localize: true, default: true
embedded_in :word
end
diff --git a/spec/mongoid/fields_spec.rb b/spec/mongoid/fields_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/mongoid/fields_spec.rb
+++ b/spec/mongoid/fields_spec.rb
@@ -1226,4 +1226,18 @@ describe Mongoid::Fields do
end
end
end
+
+ context "when a localized field is a boolean" do
+
+ context "when the default is true" do
+
+ let(:definition) do
+ Definition.new
+ end
+
+ it "returns the proper predicate result" do
+ expect(definition).to be_active
+ end
+ end
+ end
end
|
Adding spec for #<I>
|
mongodb_mongoid
|
train
|
7df049f38f8ade43ca2df91a00856dfe2bf9993c
|
diff --git a/src/js/justifiedGallery.js b/src/js/justifiedGallery.js
index <HASH>..<HASH> 100755
--- a/src/js/justifiedGallery.js
+++ b/src/js/justifiedGallery.js
@@ -321,6 +321,15 @@
};
/**
+ * Clear the building row data to be used for a new row
+ */
+ JustifiedGallery.prototype.clearBuildingRow = function () {
+ this.buildingRow.entriesBuff = [];
+ this.buildingRow.aspectRatio = 0;
+ this.buildingRow.width = 0;
+ };
+
+ /**
* Justify the building row, preparing it to
*
* @param isLastRow
@@ -382,15 +391,6 @@
};
/**
- * Clear the building row data to be used for a new row
- */
- JustifiedGallery.prototype.clearBuildingRow = function () {
- this.buildingRow.entriesBuff = [];
- this.buildingRow.aspectRatio = 0;
- this.buildingRow.width = 0;
- };
-
- /**
* Flush a row: justify it, modify the gallery height accordingly to the row height
*
* @param isLastRow
|
move clearBuildingRow() down
|
miromannino_Justified-Gallery
|
train
|
acacf891b268424d25bae196c077c6f95b7b8116
|
diff --git a/go/vt/vttablet/onlineddl/executor.go b/go/vt/vttablet/onlineddl/executor.go
index <HASH>..<HASH> 100644
--- a/go/vt/vttablet/onlineddl/executor.go
+++ b/go/vt/vttablet/onlineddl/executor.go
@@ -227,14 +227,14 @@ func (e *Executor) initSchema(ctx context.Context) error {
defer e.env.LogError()
- conn, err := e.pool.Get(ctx)
+ conn, err := dbconnpool.NewDBConnection(ctx, e.env.Config().DB.DbaConnector())
if err != nil {
return err
}
- defer conn.Recycle()
+ defer conn.Close()
for _, ddl := range ApplyDDL {
- _, err := conn.Exec(ctx, ddl, math.MaxInt32, false)
+ _, err := conn.ExecuteFetch(ddl, math.MaxInt32, false)
if mysql.IsSchemaApplyError(err) {
continue
}
|
onlineddl Executor: build schema with DBA user
|
vitessio_vitess
|
train
|
c27bba2b1d9f5416583b82d2d0d643c61aca1002
|
diff --git a/MesoPy.py b/MesoPy.py
index <HASH>..<HASH> 100755
--- a/MesoPy.py
+++ b/MesoPy.py
@@ -468,6 +468,9 @@ class Meso(object):
GACC abbreviations
subgacc: string, optional
Name of Sub GACC e.g. subgacc='EB07'
+ network: string, optional
+ Single or comma separated list of network IDs. The ID may be found by using the /networks web service.
+ e.g. network='1,2'
Returns:
Dictionary of stations through the get_response() method.
@@ -476,7 +479,6 @@ class Meso(object):
None.
"""
- kwargs['network'] = '1,2'
kwargs['token'] = self.api_token
return self._get_response('stations/metadata', kwargs)
@@ -498,3 +500,5 @@ class Meso(object):
"""
return self._get_response('variables', {'token': self.api_token})
+
+
|
resolves issue #9
Fixes issue #9 where there existed a hardcoded filter for the network
type of stations. Removed this and updated doctoring.
|
mesowx_MesoPy
|
train
|
83d1bae3f6418c09b2a899e056383b6d60284b87
|
diff --git a/sources/scalac/transformer/AddInterfacesPhase.java b/sources/scalac/transformer/AddInterfacesPhase.java
index <HASH>..<HASH> 100644
--- a/sources/scalac/transformer/AddInterfacesPhase.java
+++ b/sources/scalac/transformer/AddInterfacesPhase.java
@@ -40,7 +40,8 @@ public class AddInterfacesPhase extends Phase {
// removed.
return removeValueParams(tp);
} else if (sym.isClass() && !sym.isJava()) {
- Definitions definitions = Global.instance.definitions;
+ Definitions definitions = global.definitions;
+ if (sym == definitions.ANY_CLASS) return tp;
Type[] oldParents = tp.parents();
assert oldParents.length > 0 : Debug.show(sym);
for (int i = 1; i < oldParents.length; ++i) {
@@ -81,17 +82,7 @@ public class AddInterfacesPhase extends Phase {
newMembers.enterOrOverload(member);
}
- Symbol oldSym = oldParents[0].symbol();
- if (oldSym.isJava()
- && !oldSym.isInterface()
- && oldSym != definitions.ANY_CLASS
- && oldSym != definitions.ANYREF_CLASS) {
- newParents = new Type[oldParents.length];
- newParents[0] = definitions.ANYREF_TYPE();
- for (int i = 1; i < oldParents.length; ++i)
- newParents[i] = oldParents[i];
- } else
- newParents = oldParents;
+ newParents = oldParents;
} else {
// The symbol is the one of a class which doesn't need
// an interface. We need to fix its parents to use
@@ -161,10 +152,10 @@ public class AddInterfacesPhase extends Phase {
|| classSym.isModuleClass()
|| classSym.isAnonymousClass()
|| hasInterfaceSymbol(classSym)
- || classSym == Global.instance.definitions.ANY_CLASS
- || classSym == Global.instance.definitions.ANYREF_CLASS
- || classSym == Global.instance.definitions.ALL_CLASS
- || classSym == Global.instance.definitions.ALLREF_CLASS);
+ || classSym == global.definitions.ANY_CLASS
+ || classSym == global.definitions.ANYREF_CLASS
+ || classSym == global.definitions.ALL_CLASS
+ || classSym == global.definitions.ALLREF_CLASS);
}
protected final static String CLASS_SUFFIX = "$class";
diff --git a/sources/scalac/transformer/ErasurePhase.java b/sources/scalac/transformer/ErasurePhase.java
index <HASH>..<HASH> 100644
--- a/sources/scalac/transformer/ErasurePhase.java
+++ b/sources/scalac/transformer/ErasurePhase.java
@@ -21,6 +21,7 @@ import scalac.checkers.CheckSymbols;
import scalac.checkers.CheckTypes;
import scalac.checkers.CheckNames;
import scalac.symtab.Definitions;
+import scalac.symtab.Scope;
import scalac.symtab.Symbol;
import scalac.symtab.Type;
import scalac.util.Debug;
@@ -52,9 +53,30 @@ public class ErasurePhase extends Phase {
}
public Type transformInfo(Symbol sym, Type tp) {
- if (sym.isClass() && sym.isSubClass(definitions.ANYVAL_CLASS) && sym != definitions.ANYVAL_CLASS) return tp;
if (sym.isConstructor() && sym.constructorClass().isSubClass(definitions.ANYVAL_CLASS)) return tp;
- if (sym.isClass()) return Type.erasureMap.map(tp);
+ if (sym.isClass()) {
+ if (sym == definitions.ANY_CLASS) return tp;
+ if (sym.isJava() && sym.isModuleClass()) return tp;
+ if (sym.isSubClass(definitions.ANYVAL_CLASS))
+ if (sym != definitions.ANYVAL_CLASS) return tp;
+ switch (tp) {
+ case CompoundType(Type[] parents, Scope members):
+ assert parents.length != 0: Debug.show(sym) + " -- " + tp;
+ if (sym.isInterface()) {
+ Symbol superclass = parents[0].symbol();
+ if (superclass.isJava() && !superclass.isInterface()) {
+ if (superclass != definitions.ANY_CLASS) {
+ parents = Type.cloneArray(parents);
+ parents[0] = definitions.ANYREF_TYPE();
+ tp = Type.compoundType(parents, members, sym);
+ }
+ }
+ }
+ return Type.erasureMap.map(tp);
+ default:
+ throw Debug.abort("illegal case", tp);
+ }
+ }
if (sym.isType()) return tp;
// if (sym == definitions.NULL) return tp.resultType().erasure();
switch (primitives.getPrimitive(sym)) {
|
- Moved erasure of superclasses of interfaces f...
- Moved erasure of superclasses of interfaces from AddInterfaces into
Erasure
|
scala_scala
|
train
|
cefec2cb94b83e01109d20c16fabcb1ed6448814
|
diff --git a/src/components/scroll-area/QScrollArea.js b/src/components/scroll-area/QScrollArea.js
index <HASH>..<HASH> 100644
--- a/src/components/scroll-area/QScrollArea.js
+++ b/src/components/scroll-area/QScrollArea.js
@@ -193,18 +193,15 @@ export default {
}, [
this.$slots.default,
h(QResizeObservable, {
- staticClass: 'resize-obs',
on: { resize: this.__updateScrollHeight }
})
]),
h(QScrollObservable, {
- staticClass: 'scroll-obs',
on: { scroll: this.__updateScroll }
})
]),
h(QResizeObservable, {
- staticClass: 'main-resize-obs',
on: { resize: this.__updateContainer }
}),
|
chore: Remove obsolete class definitions in QScrollArea
|
quasarframework_quasar
|
train
|
8d831194cafe2e02a36d7bd9592002b9b6fdecf1
|
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
index <HASH>..<HASH> 100644
--- a/tests/bootstrap.php
+++ b/tests/bootstrap.php
@@ -5,8 +5,12 @@
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
-if (file_exists($file = __DIR__.'/autoload.php')) {
- require_once $file;
-} elseif (file_exists($file = __DIR__.'/autoload.php.dist')) {
- require_once $file;
-}
\ No newline at end of file
+
+if (!@include __DIR__ . '/../vendor/autoload.php') {
+ die(<<<'EOT'
+You must set up the project dependencies, run the following commands:
+wget http://getcomposer.org/composer.phar
+php composer.phar install
+EOT
+ );
+}
|
Update the test bootstrap to use composer vendor
|
vespolina_commerce
|
train
|
8a5a33a9b9538400a6bb350e652452c2fc4b44e3
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -69,6 +69,8 @@ If you'd like to add a new dependency just `gvt fetch`
You must set an environment variable `$CONFIG` which points to a JSON file that contains several pieces of data that will be used to configure the acceptance tests, e.g. telling the tests how to target your running Cloud Foundry deployment and what tests to run.
+You can see all available config keys [here](https://github.com/cloudfoundry/cf-acceptance-tests/blob/master/helpers/config/config_struct.go#L15-L76) and their defaults [here](https://github.com/cloudfoundry/cf-acceptance-tests/blob/master/helpers/config/config_struct.go#L96-L149).
+
The following can be pasted into a terminal and will set up a sufficient `$CONFIG` to run the core test suites against a [BOSH-Lite](https://github.com/cloudfoundry/bosh-lite) deployment of CF.
```bash
diff --git a/helpers/config/config_struct.go b/helpers/config/config_struct.go
index <HASH>..<HASH> 100644
--- a/helpers/config/config_struct.go
+++ b/helpers/config/config_struct.go
@@ -111,20 +111,21 @@ func getDefaults() config {
defaults.StaticFileBuildpackName = ptrToString("staticfile_buildpack")
defaults.IncludeApps = ptrToBool(true)
- defaults.IncludeBackendCompatiblity = ptrToBool(true)
defaults.IncludeDetect = ptrToBool(true)
- defaults.IncludeDocker = ptrToBool(true)
- defaults.IncludeInternetDependent = ptrToBool(true)
- defaults.IncludeRouteServices = ptrToBool(true)
defaults.IncludeRouting = ptrToBool(true)
- defaults.IncludeSecurityGroups = ptrToBool(true)
- defaults.IncludeServices = ptrToBool(true)
- defaults.IncludeSsh = ptrToBool(true)
- defaults.IncludeV3 = ptrToBool(true)
- defaults.IncludePrivilegedContainerSupport = ptrToBool(true)
- defaults.IncludeZipkin = ptrToBool(true)
- defaults.IncludeSSO = ptrToBool(true)
- defaults.IncludeTasks = ptrToBool(true)
+
+ defaults.IncludeBackendCompatiblity = ptrToBool(false)
+ defaults.IncludeDocker = ptrToBool(false)
+ defaults.IncludeInternetDependent = ptrToBool(false)
+ defaults.IncludeRouteServices = ptrToBool(false)
+ defaults.IncludeSecurityGroups = ptrToBool(false)
+ defaults.IncludeServices = ptrToBool(false)
+ defaults.IncludeSsh = ptrToBool(false)
+ defaults.IncludeV3 = ptrToBool(false)
+ defaults.IncludePrivilegedContainerSupport = ptrToBool(false)
+ defaults.IncludeZipkin = ptrToBool(false)
+ defaults.IncludeSSO = ptrToBool(false)
+ defaults.IncludeTasks = ptrToBool(false)
defaults.UseHttp = ptrToBool(false)
defaults.UseExistingUser = ptrToBool(false)
diff --git a/helpers/config/config_test.go b/helpers/config/config_test.go
index <HASH>..<HASH> 100644
--- a/helpers/config/config_test.go
+++ b/helpers/config/config_test.go
@@ -181,20 +181,21 @@ var _ = Describe("Config", func() {
Expect(config.GetPersistentAppSpace()).To(Equal("CATS-persistent-space"))
Expect(config.GetIncludeApps()).To(BeTrue())
- Expect(config.GetIncludeBackendCompatiblity()).To(BeTrue())
Expect(config.GetIncludeDetect()).To(BeTrue())
- Expect(config.GetIncludeDocker()).To(BeTrue())
- Expect(config.GetIncludeInternetDependent()).To(BeTrue())
- Expect(config.GetIncludeRouteServices()).To(BeTrue())
Expect(config.GetIncludeRouting()).To(BeTrue())
- Expect(config.GetIncludeSecurityGroups()).To(BeTrue())
- Expect(config.GetIncludeServices()).To(BeTrue())
- Expect(config.GetIncludeSsh()).To(BeTrue())
- Expect(config.GetIncludeV3()).To(BeTrue())
- Expect(config.GetIncludePrivilegedContainerSupport()).To(BeTrue())
- Expect(config.GetIncludeZipkin()).To(BeTrue())
- Expect(config.GetIncludeSSO()).To(BeTrue())
- Expect(config.GetIncludeTasks()).To(BeTrue())
+
+ Expect(config.GetIncludeBackendCompatiblity()).To(BeFalse())
+ Expect(config.GetIncludeDocker()).To(BeFalse())
+ Expect(config.GetIncludeInternetDependent()).To(BeFalse())
+ Expect(config.GetIncludeRouteServices()).To(BeFalse())
+ Expect(config.GetIncludeSecurityGroups()).To(BeFalse())
+ Expect(config.GetIncludeServices()).To(BeFalse())
+ Expect(config.GetIncludeSsh()).To(BeFalse())
+ Expect(config.GetIncludeV3()).To(BeFalse())
+ Expect(config.GetIncludePrivilegedContainerSupport()).To(BeFalse())
+ Expect(config.GetIncludeZipkin()).To(BeFalse())
+ Expect(config.GetIncludeSSO()).To(BeFalse())
+ Expect(config.GetIncludeTasks()).To(BeFalse())
Expect(config.GetBackend()).To(Equal(""))
|
Change defaults for include_* to false except for Apps, Detect, and Routing; update README [#<I>]
|
cloudfoundry_cf-acceptance-tests
|
train
|
5a672186e579e4d3edf90755eeac828281124cfa
|
diff --git a/ffmpeg_normalize/__main__.py b/ffmpeg_normalize/__main__.py
index <HASH>..<HASH> 100644
--- a/ffmpeg_normalize/__main__.py
+++ b/ffmpeg_normalize/__main__.py
@@ -397,9 +397,11 @@ def main():
for index, input_file in enumerate(cli_args.input):
if cli_args.output is not None and index < len(cli_args.output):
+ if cli_args.output_folder:
+ logger.warning("Output folder {} is ignored for input file {}".format(cli_args.output_folder, input_file))
output_file = cli_args.output[index]
output_dir = os.path.dirname(output_file)
- if not os.path.isdir(output_dir):
+ if output_dir != '' and not os.path.isdir(output_dir):
raise FFmpegNormalizeError("Output file path {} does not exist".format(output_dir))
else:
output_file = os.path.join(
|
fix issue with output folder, fixes #<I>
|
slhck_ffmpeg-normalize
|
train
|
72d10447986db39ac95f3d0980936d9c08428b02
|
diff --git a/instabot/api/api.py b/instabot/api/api.py
index <HASH>..<HASH> 100644
--- a/instabot/api/api.py
+++ b/instabot/api/api.py
@@ -61,7 +61,7 @@ class API(object):
self.uuid = self.generate_UUID(uuid_type=True)
def login(self, username=None, password=None, force=False, proxy=None,
- use_cookie=True, cookie_fname='cookie.txt'):
+ use_cookie=False, cookie_fname='cookie.txt'):
if password is None:
username, password = get_credentials(username=username)
|
set use_cookie=False by default
|
instagrambot_instabot
|
train
|
b0e57838273b3915d877e23d334ecd673bb29574
|
diff --git a/bitex/interfaces/hitbtc.py b/bitex/interfaces/hitbtc.py
index <HASH>..<HASH> 100644
--- a/bitex/interfaces/hitbtc.py
+++ b/bitex/interfaces/hitbtc.py
@@ -55,21 +55,21 @@ class HitBtc(HitBTCREST):
q = kwargs
return self.public_query('%s/trades' % pair, params=q)
- def _place_order(self, pair, amount, price, side, order_id, **kwargs):
- q = {'symbol': pair, 'price': price, 'quantity': amount, 'side': side,
+ def _place_order(self, pair, size, price, side, order_id, **kwargs):
+ q = {'symbol': pair, 'price': price, 'size': size, 'side': side,
'clientOrderId': order_id}
q.update(kwargs)
return self.private_query('trading/new_order', method_verb='POST', params=q)
@return_api_response(fmt.order)
- def bid(self, pair, price, amount, order_id=None, **kwargs):
+ def bid(self, pair, price, size, order_id=None, **kwargs):
order_id = order_id if order_id else str(time.time())
- self._place_order(pair, amount, price, 'buy', order_id, **kwargs)
+ self._place_order(pair, size, price, 'buy', order_id, **kwargs)
@return_api_response(fmt.order)
- def ask(self, pair, price, amount, order_id=None, **kwargs):
+ def ask(self, pair, price, size, order_id=None, **kwargs):
order_id = order_id if order_id else str(time.time())
- self._place_order(pair, amount, price, 'sell', order_id, **kwargs)
+ self._place_order(pair, size, price, 'sell', order_id, **kwargs)
@return_api_response(fmt.cancel)
def cancel_order(self, order_id, all=False, **kwargs):
@@ -91,9 +91,9 @@ class HitBtc(HitBTCREST):
return self.private_query('trading/balance', params=kwargs)
@return_api_response(fmt.withdraw)
- def withdraw(self, amount, tar_addr, currency=None, **kwargs):
+ def withdraw(self, size, tar_addr, currency=None, **kwargs):
currency = 'BTC' if not currency else currency
- q = {'amount': amount, 'currency_code': currency, 'address': tar_addr}
+ q = {'size': size, 'currency_code': currency, 'address': tar_addr}
q.update(kwargs)
return self.private_query('payment/payout', params=q)
|
change 'amount' to 'size' in hitbtc.py #<I>
|
Crypto-toolbox_bitex
|
train
|
d1cf53e2c48659d6d3d4af68287e30397af9c380
|
diff --git a/lib/cucumber/rb_support/rb_group.rb b/lib/cucumber/rb_support/rb_group.rb
index <HASH>..<HASH> 100644
--- a/lib/cucumber/rb_support/rb_group.rb
+++ b/lib/cucumber/rb_support/rb_group.rb
@@ -1,5 +1,13 @@
module Cucumber
module RbSupport
+ # A Group encapsulates data from a regexp match.
+ # A Group instance has to attributes:
+ #
+ # * The value of the group
+ # * The start index from the matched string where the group value starts
+ #
+ # See rb_group_spec.rb for examples
+ #
class RbGroup
attr_reader :val, :start
diff --git a/spec/cucumber/rb_support/rb_group_spec.rb b/spec/cucumber/rb_support/rb_group_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/cucumber/rb_support/rb_group_spec.rb
+++ b/spec/cucumber/rb_support/rb_group_spec.rb
@@ -4,28 +4,37 @@ require 'cucumber/rb_support/rb_step_definition'
module Cucumber
module RbSupport
describe RbGroup do
- it "should format groups with format string" do
- d = RbStepDefinition.new(nil, /I (\w+) (\d+) (\w+) this (\w+)/, lambda{})
- m = d.step_match("I ate 1 egg this morning", nil)
- m.format_args("<span>%s</span>").should == "I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>"
+ context "Creating groups" do
+ it "should create 2 groups" do
+ groups = RbGroup.groups_from(/I (\w+) (\w+)/, "I like fish")
+ groups.map{|group| [group.val, group.start]}.should == [["like", 2], ["fish", 7]]
+ end
end
+
+ context "Formatting arguments" do
+ it "should format groups with format string" do
+ d = RbStepDefinition.new(nil, /I (\w+) (\d+) (\w+) this (\w+)/, lambda{})
+ m = d.step_match("I ate 1 egg this morning", nil)
+ m.format_args("<span>%s</span>").should == "I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>"
+ end
- it "should format groups with format string when there are dupes" do
- d = RbStepDefinition.new(nil, /I (\w+) (\d+) (\w+) this (\w+)/, lambda{})
- m = d.step_match("I bob 1 bo this bobs", nil)
- m.format_args("<span>%s</span>").should == "I <span>bob</span> <span>1</span> <span>bo</span> this <span>bobs</span>"
- end
+ it "should format groups with format string when there are dupes" do
+ d = RbStepDefinition.new(nil, /I (\w+) (\d+) (\w+) this (\w+)/, lambda{})
+ m = d.step_match("I bob 1 bo this bobs", nil)
+ m.format_args("<span>%s</span>").should == "I <span>bob</span> <span>1</span> <span>bo</span> this <span>bobs</span>"
+ end
- it "should format groups with block" do
- d = RbStepDefinition.new(nil, /I (\w+) (\d+) (\w+) this (\w+)/, lambda{})
- m = d.step_match("I ate 1 egg this morning", nil)
- m.format_args(&lambda{|m| "<span>#{m}</span>"}).should == "I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>"
- end
+ it "should format groups with block" do
+ d = RbStepDefinition.new(nil, /I (\w+) (\d+) (\w+) this (\w+)/, lambda{})
+ m = d.step_match("I ate 1 egg this morning", nil)
+ m.format_args(&lambda{|m| "<span>#{m}</span>"}).should == "I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>"
+ end
- it "should format groups with proc object" do
- d = RbStepDefinition.new(nil, /I (\w+) (\d+) (\w+) this (\w+)/, lambda{})
- m = d.step_match("I ate 1 egg this morning", nil)
- m.format_args(lambda{|m| "<span>#{m}</span>"}).should == "I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>"
+ it "should format groups with proc object" do
+ d = RbStepDefinition.new(nil, /I (\w+) (\d+) (\w+) this (\w+)/, lambda{})
+ m = d.step_match("I ate 1 egg this morning", nil)
+ m.format_args(lambda{|m| "<span>#{m}</span>"}).should == "I <span>ate</span> <span>1</span> <span>egg</span> this <span>morning</span>"
+ end
end
end
end
|
Added some RDoc and a better spec
|
cucumber_cucumber-ruby
|
train
|
e1c50a4d6d0cab654904121af271875f7b85ef11
|
diff --git a/Subject/Provider/SubjectProviderInterface.php b/Subject/Provider/SubjectProviderInterface.php
index <HASH>..<HASH> 100644
--- a/Subject/Provider/SubjectProviderInterface.php
+++ b/Subject/Provider/SubjectProviderInterface.php
@@ -16,6 +16,7 @@ interface SubjectProviderInterface
const CONTEXT_ITEM = 'item'; // Sale item subject
const CONTEXT_SALE = 'sale'; // Sale item search
+ const CONTEXT_ACCOUNT = 'account'; // Sale item search from customer account
const CONTEXT_SUPPLIER = 'supplier'; // Supplier item subject
|
[Commerce] Added account context constant to subject provider interface.
|
ekyna_Commerce
|
train
|
397166eda0757827c4df18a4753e3e6f5c75215a
|
diff --git a/lib/faraday/adapter/patron.rb b/lib/faraday/adapter/patron.rb
index <HASH>..<HASH> 100644
--- a/lib/faraday/adapter/patron.rb
+++ b/lib/faraday/adapter/patron.rb
@@ -37,7 +37,7 @@ module Faraday
@app.call env
rescue ::Patron::TimeoutError => err
- if err.message == "Connection time-out"
+ if connection_timed_out_message?(err.message)
raise Faraday::Error::ConnectionFailed, err
else
raise Faraday::Error::TimeoutError, err
@@ -78,6 +78,23 @@ module Faraday
session.insecure = true
end
end
+
+ private
+
+ CURL_TIMEOUT_MESSAGES = [ "Connection time-out",
+ "Connection timed out",
+ "Timed out before name resolve",
+ "server connect has timed out",
+ "Resolving timed out",
+ "name lookup timed out",
+ "timed out before SSL",
+ "connect() timed out"
+ ].freeze
+
+ def connection_timed_out_message?(message)
+ CURL_TIMEOUT_MESSAGES.any? { |curl_message| message.include?(curl_message) }
+ end
+
end
end
end
diff --git a/test/adapters/patron_test.rb b/test/adapters/patron_test.rb
index <HASH>..<HASH> 100644
--- a/test/adapters/patron_test.rb
+++ b/test/adapters/patron_test.rb
@@ -16,7 +16,7 @@ module Adapters
# no support for SSL peer verification
undef :test_GET_ssl_fails_with_bad_cert if ssl_mode?
end
-
+
def test_custom_adapter_config
adapter = Faraday::Adapter::Patron.new do |session|
session.max_redirects = 10
@@ -26,6 +26,13 @@ module Adapters
assert_equal 10, session.max_redirects
end
+
+ def test_connection_timeout
+ conn = create_connection(:request => {:timeout => 10, :open_timeout => 1})
+ assert_raises Faraday::Error::ConnectionFailed do
+ conn.get 'http://8.8.8.8:88'
+ end
+ end
end
end
end
|
Handle all connection timeout messages in Patron (#<I>)
* Include more of cURL's connection timeout messages
|
lostisland_faraday
|
train
|
72de9e21cbe80a4eeea196ab02410b3cd93c0b4e
|
diff --git a/atests/Basic_Server_Client_Functionality.txt b/atests/Basic_Server_Client_Functionality.txt
index <HASH>..<HASH> 100644
--- a/atests/Basic_Server_Client_Functionality.txt
+++ b/atests/Basic_Server_Client_Functionality.txt
@@ -7,6 +7,7 @@ ${expected_string} ismo_rulettaa
${host} localhost
${port} 2010
${physical_interface} lo
+${virtual_host} 1.1.1.1
*** Test Cases ***
Send and Receive string over UDP using physical interface
@@ -25,13 +26,14 @@ Send and Receive string over UDP using virtual interface
*** Keywords ***
Server is started
[Arguments] ${interface}
- Start Server LOCALHOST ${interface} ${port}
+ Start Server ${interface} ${port}
Server Receives String Over UDP
${rcv_string}= receive_packet_over_udp
Should Be Equal ${rcv_string} ${expected_string}
Connect to Server
+ [Arguments] ${host}
Rammbock.connect to server ${host} ${port}
Send string over UDP
@@ -40,11 +42,19 @@ Send string over UDP
Initialize UDP Server and Client to physical interface
use interface PHYSICAL ${physical_interface}
Server is Started PHYSICAL
- Connect to Server
+ Connect to Server ${host}
Close Connections
Close Server
Close Client
Initialize UDP Client and Server to virtual interface
+ use interface VIRTUAL_INTERFACE ${physical_interface} 1.1.1.1 255.255.255.255 True
+ Server is Started VIRTUAL_INTERFACE
+ connect to server ${virtual_host}
+
+Close Connections and remove virtual interface
+ Close Server
+ Close Client
+ Delete Interface VIRTUAL_INTERFACE
diff --git a/src/Rammbock.py b/src/Rammbock.py
index <HASH>..<HASH> 100755
--- a/src/Rammbock.py
+++ b/src/Rammbock.py
@@ -39,8 +39,7 @@ class Rammbock(Server, Client):
print "delete_interface " + ifname
return self.interfaces[ifname].del_interface()
- def start_server(self, if_alias, interface, port):
- self.use_interface(if_alias, interface)
+ def start_server(self, if_alias, port):
Server.server_startup(self, if_alias, port)
def connect_to_server(self, host, port):
@@ -48,6 +47,6 @@ class Rammbock(Server, Client):
def close_server(self):
Server.close_server(self)
-
+
def close_client(self):
Client.close_client(self)
diff --git a/src/Server.py b/src/Server.py
index <HASH>..<HASH> 100644
--- a/src/Server.py
+++ b/src/Server.py
@@ -3,18 +3,22 @@
import socket
import sys
+import time
UDP_PACKET_MAX_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
class Server:
def server_startup(self, interface, port):
- host = self.interfaces[interface].ifIpAddress
+ host = str(self.interfaces[interface].ifIpAddress)
+ print "used host address is: "+host+":"+port
s.bind((host, int(port)))
def receive_packet_over_udp(self):
return s.recv(UDP_PACKET_MAX_SIZE)
def close_server(self):
- s.close()
\ No newline at end of file
+ s.close()
+ del self
\ No newline at end of file
|
both test cases with UDP packet send are working SEPARETLY *sigh*. something to do about server instance which stays haning around between cases. let's see
|
robotframework_Rammbock
|
train
|
e7f554cba70086ad51c8b03b8cc4bfb8b4ac6236
|
diff --git a/lib/Cake/Network/CakeRequest.php b/lib/Cake/Network/CakeRequest.php
index <HASH>..<HASH> 100644
--- a/lib/Cake/Network/CakeRequest.php
+++ b/lib/Cake/Network/CakeRequest.php
@@ -519,20 +519,7 @@ class CakeRequest implements ArrayAccess {
}
/**
- * Gets the accept header from the current request.
- *
- * @return bool Returns an array of accept header values.
- */
- public function getAcceptHeaders() {
- $headers = array();
- if (isset($_SERVER['HTTP_ACCEPT'])) {
- $headers = explode(',', $_SERVER['HTTP_ACCEPT']);
- }
- return $headers;
- }
-
-/**
- * Detects if an URL extension is present.
+ * Detects if a URL extension is present.
*
* @param array $detect Detector options array.
* @return bool Whether or not the request is the type you are checking.
@@ -554,7 +541,7 @@ class CakeRequest implements ArrayAccess {
* @return bool Whether or not the request is the type you are checking.
*/
protected function _acceptHeaderDetector($detect) {
- $acceptHeaders = $this->getAcceptHeaders();
+ $acceptHeaders = explode(',', (string)env('HTTP_ACCEPT'));
foreach ($detect['accept'] as $header) {
if (in_array($header, $acceptHeaders)) {
return true;
@@ -571,12 +558,12 @@ class CakeRequest implements ArrayAccess {
*/
protected function _headerDetector($detect) {
foreach ($detect['header'] as $header => $value) {
- $header = 'HTTP_' . strtoupper($header);
- if (isset($_SERVER[$header])) {
- if (is_callable($value)) {
- return call_user_func($value, $_SERVER[$header]);
+ $header = env('HTTP_' . strtoupper($header));
+ if (!is_null($header)) {
+ if (!is_string($value) && !is_bool($value) && is_callable($value)) {
+ return call_user_func($value, $header);
}
- return ($_SERVER[$header] === $value);
+ return ($header === $value);
}
}
return false;
|
Changing the direct access of super globals in Cake/Network/CakeRequest.php to use env() and fixed a typo.
|
cakephp_cakephp
|
train
|
fed61f6c12ff6ff279b5300d56c255f01ef1d589
|
diff --git a/helper/mfa/duo/duo.go b/helper/mfa/duo/duo.go
index <HASH>..<HASH> 100644
--- a/helper/mfa/duo/duo.go
+++ b/helper/mfa/duo/duo.go
@@ -111,6 +111,11 @@ func duoHandler(duoConfig *DuoConfig, duoAuthClient AuthClient, request *duoAuth
if request.method == "" {
request.method = "auto"
}
+ if request.method == "auto" || request.method == "push" {
+ if duoConfig.PushInfo != "" {
+ options = append(options, authapi.AuthPushinfo(duoConfig.PushInfo))
+ }
+ }
if request.passcode != "" {
request.method = "passcode"
options = append(options, authapi.AuthPasscode(request.passcode))
diff --git a/helper/mfa/duo/path_duo_config.go b/helper/mfa/duo/path_duo_config.go
index <HASH>..<HASH> 100644
--- a/helper/mfa/duo/path_duo_config.go
+++ b/helper/mfa/duo/path_duo_config.go
@@ -20,6 +20,10 @@ func pathDuoConfig() *framework.Path {
Type: framework.TypeString,
Description: "Format string given auth backend username as argument to create Duo username (default '%s')",
},
+ "push_info": &framework.FieldSchema{
+ Type: framework.TypeString,
+ Description: "A string of URL-encoded key/value pairs that provides additional context about the authentication attemmpt in the Duo Mobile app",
+ },
},
Callbacks: map[logical.Operation]framework.OperationFunc{
@@ -50,11 +54,16 @@ func GetDuoConfig(req *logical.Request) (*DuoConfig, error) {
func pathDuoConfigWrite(
req *logical.Request, d *framework.FieldData) (*logical.Response, error) {
username_format := d.Get("username_format").(string)
+ if username_format == "" {
+ username_format = "%s"
+ }
if !strings.Contains(username_format, "%s") {
return nil, errors.New("username_format must include username ('%s')")
}
entry, err := logical.StorageEntryJSON("duo/config", DuoConfig{
UsernameFormat: username_format,
+ UserAgent: d.Get("user_agent").(string),
+ PushInfo: d.Get("push_info").(string),
})
if err != nil {
return nil, err
@@ -81,6 +90,8 @@ func pathDuoConfigRead(
return &logical.Response{
Data: map[string]interface{}{
"username_format": config.UsernameFormat,
+ "user_agent": config.UserAgent,
+ "push_info": config.PushInfo,
},
}, nil
}
@@ -88,6 +99,7 @@ func pathDuoConfigRead(
type DuoConfig struct {
UsernameFormat string `json:"username_format"`
UserAgent string `json:"user_agent"`
+ PushInfo string `json:"push_info"`
}
const pathDuoConfigHelpSyn = `
diff --git a/website/source/docs/auth/mfa.html.md b/website/source/docs/auth/mfa.html.md
index <HASH>..<HASH> 100644
--- a/website/source/docs/auth/mfa.html.md
+++ b/website/source/docs/auth/mfa.html.md
@@ -89,4 +89,7 @@ that is passed the original username as its first argument and outputs
the new username. For example "%s@example.com" would append "@example.com"
to the provided username before connecting to Duo.
+`push_info` is a string of URL-encoded key/value pairs that provides additional
+context about the authentication attemmpt in the Duo Mobile application.
+
More information can be found through the CLI `path-help` command.
|
Add Duo pushinfo capabilities (#<I>)
|
hashicorp_vault
|
train
|
7e5a222e2aca6e66e43308bef6649f78956b7dde
|
diff --git a/hazelcast/src/test/java/com/hazelcast/test/SplitBrainTestSupport.java b/hazelcast/src/test/java/com/hazelcast/test/SplitBrainTestSupport.java
index <HASH>..<HASH> 100644
--- a/hazelcast/src/test/java/com/hazelcast/test/SplitBrainTestSupport.java
+++ b/hazelcast/src/test/java/com/hazelcast/test/SplitBrainTestSupport.java
@@ -418,6 +418,11 @@ public abstract class SplitBrainTestSupport extends HazelcastTestSupport {
return sb.toString();
}
+ public static void assertPi(Object value) {
+ assertInstanceOf(Double.class, value);
+ assertEquals("Expected the value to be PI", Math.PI, (Double) value, 0.00000001d);
+ }
+
public static void assertPiCollection(Collection<Object> collection) {
assertEquals("Expected the collection to be a PI collection", ReturnPiCollectionMergePolicy.PI_COLLECTION, collection);
}
|
Added method assertPi() to SplitBrainTestSupport
|
hazelcast_hazelcast
|
train
|
66c18428982ca2e0b388493cc76d7167c7e62e11
|
diff --git a/src/Storage/Field/Type/FieldTypeBase.php b/src/Storage/Field/Type/FieldTypeBase.php
index <HASH>..<HASH> 100644
--- a/src/Storage/Field/Type/FieldTypeBase.php
+++ b/src/Storage/Field/Type/FieldTypeBase.php
@@ -115,6 +115,9 @@ abstract class FieldTypeBase implements FieldTypeInterface
public function set($entity, $value)
{
$key = $this->mapping['fieldname'];
+ if (!$value) {
+ $value = $this->mapping['data']['default'];
+ }
$entity->$key = $value;
}
|
use the default value if there is nothing set
|
bolt_bolt
|
train
|
875cfd7d4cd90d2b9dfb58c782518f503497687e
|
diff --git a/rxjava-core/src/main/java/rx/schedulers/TrampolineScheduler.java b/rxjava-core/src/main/java/rx/schedulers/TrampolineScheduler.java
index <HASH>..<HASH> 100644
--- a/rxjava-core/src/main/java/rx/schedulers/TrampolineScheduler.java
+++ b/rxjava-core/src/main/java/rx/schedulers/TrampolineScheduler.java
@@ -17,6 +17,7 @@ package rx.schedulers;
import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import rx.Scheduler;
@@ -44,15 +45,20 @@ public final class TrampolineScheduler extends Scheduler {
/* package accessible for unit tests */TrampolineScheduler() {
}
- private static final ThreadLocal<PriorityQueue<TimedAction>> QUEUE = new ThreadLocal<PriorityQueue<TimedAction>>();
+ private static final ThreadLocal<PriorityQueue<TimedAction>> QUEUE = new ThreadLocal<PriorityQueue<TimedAction>>() {
+ @Override
+ protected PriorityQueue<TimedAction> initialValue() {
+ return new PriorityQueue<TimedAction>();
+ }
+ };
volatile int counter;
- static final AtomicIntegerFieldUpdater<TrampolineScheduler> COUNTER_UPDATER
- = AtomicIntegerFieldUpdater.newUpdater(TrampolineScheduler.class, "counter");
+ static final AtomicIntegerFieldUpdater<TrampolineScheduler> COUNTER_UPDATER = AtomicIntegerFieldUpdater.newUpdater(TrampolineScheduler.class, "counter");
private class InnerCurrentThreadScheduler extends Scheduler.Worker implements Subscription {
private final BooleanSubscription innerSubscription = new BooleanSubscription();
+ private final AtomicInteger wip = new AtomicInteger();
@Override
public Subscription schedule(Action0 action) {
@@ -71,24 +77,16 @@ public final class TrampolineScheduler extends Scheduler {
return Subscriptions.empty();
}
PriorityQueue<TimedAction> queue = QUEUE.get();
- boolean exec = queue == null;
-
- if (exec) {
- queue = new PriorityQueue<TimedAction>();
- QUEUE.set(queue);
- }
-
final TimedAction timedAction = new TimedAction(action, execTime, COUNTER_UPDATER.incrementAndGet(TrampolineScheduler.this));
queue.add(timedAction);
- if (exec) {
- while (!queue.isEmpty()) {
+ if (wip.getAndIncrement() == 0) {
+ do {
queue.poll().action.call();
- }
-
- QUEUE.set(null);
+ } while (wip.decrementAndGet() > 0);
return Subscriptions.empty();
} else {
+ // queue wasn't empty, a parent is already processing so we just add to the end of the queue
return Subscriptions.create(new Action0() {
@Override
@@ -118,9 +116,9 @@ public final class TrampolineScheduler extends Scheduler {
private static class TimedAction implements Comparable<TimedAction> {
final Action0 action;
final Long execTime;
- final Integer count; // In case if time between enqueueing took less than 1ms
+ final int count; // In case if time between enqueueing took less than 1ms
- private TimedAction(Action0 action, Long execTime, Integer count) {
+ private TimedAction(Action0 action, Long execTime, int count) {
this.action = action;
this.execTime = execTime;
this.count = count;
@@ -130,10 +128,15 @@ public final class TrampolineScheduler extends Scheduler {
public int compareTo(TimedAction that) {
int result = execTime.compareTo(that.execTime);
if (result == 0) {
- return count.compareTo(that.count);
+ return compare(count, that.count);
}
return result;
}
}
+
+ // because I can't use Integer.compare from Java 7
+ private static int compare(int x, int y) {
+ return (x < y) ? -1 : ((x == y) ? 0 : 1);
+ }
}
|
TrampolineScheduler Cleanup
Remove the null check and lazy creation, build the queue in the ThreadLocal. Fix bugs about "work in progress".
|
ReactiveX_RxJava
|
train
|
ce50f8f108dd0cb398da040c77146aa052dcdebc
|
diff --git a/views/export/tmpl/default.html.php b/views/export/tmpl/default.html.php
index <HASH>..<HASH> 100644
--- a/views/export/tmpl/default.html.php
+++ b/views/export/tmpl/default.html.php
@@ -8,7 +8,7 @@
defined('KOOWA') or die; ?>
<?= helper('ui.bootstrap') ?>
-<?= helper('ui.load') ?>
+<?= helper('ui.load', array('styles' => false)) ?>
<ktml:script src="media://koowa/com_migrator/js/migrator.js" />
<ktml:script src="media://koowa/com_migrator/js/export.js" />
diff --git a/views/import/tmpl/default.html.php b/views/import/tmpl/default.html.php
index <HASH>..<HASH> 100644
--- a/views/import/tmpl/default.html.php
+++ b/views/import/tmpl/default.html.php
@@ -8,7 +8,7 @@
defined('KOOWA') or die; ?>
<?= helper('ui.bootstrap') ?>
-<?= helper('ui.load') ?>
+<?= helper('ui.load', array('styles' => false)) ?>
<ktml:script src="media://koowa/com_migrator/js/uploader.min.js" />
<ktml:script src="media://koowa/com_migrator/js/migrator.js" />
|
Do not load admin.css as the page is not using Flexbox
|
joomlatools_joomlatools-framework
|
train
|
1e5690c7c4aeff2e0381de7a419b0e85153d9114
|
diff --git a/packages/row/src/react/index.js b/packages/row/src/react/index.js
index <HASH>..<HASH> 100644
--- a/packages/row/src/react/index.js
+++ b/packages/row/src/react/index.js
@@ -1,6 +1,6 @@
import * as glamor from 'glamor'
import PropTypes from 'prop-types'
-import React from 'react'
+import React, { useState } from 'react'
import filterReactProps from '@pluralsight/ps-design-system-filter-react-props'
import { elementOfType } from '@pluralsight/ps-design-system-prop-types'
@@ -116,35 +116,28 @@ const ActionBarAction = withTheme(
ActionBarAction.displayName = 'Row.Action'
ActionBarAction.propTypes = { icon: PropTypes.element.isRequired }
-class FullOverlayFocusManager extends React.Component {
- constructor(props) {
- super(props)
- this.state = { isFocused: false }
- this.handleFocus = this.handleFocus.bind(this)
- this.handleBlur = this.handleBlur.bind(this)
- }
+const FullOverlayFocusManager = ({ fullOverlayVisible, fullOverlay }) => {
+ const [isFocused, setFocused] = useState(false);
- handleFocus() {
- this.setState({ isFocused: true })
+ const handleFocus = _ => {
+ setFocused(true)
}
- handleBlur() {
- this.setState({ isFocused: false })
+ const handleBlur = _ => {
+ setFocused(false)
}
- render() {
- return this.props.fullOverlay ? (
- <FullOverlay
- isFocused={this.state.isFocused}
- fullOverlayVisible={this.props.fullOverlayVisible}
- >
- {React.cloneElement(this.props.fullOverlay, {
- onFocus: this.handleFocus,
- onBlur: this.handleBlur
- })}
- </FullOverlay>
- ) : null
- }
+ return fullOverlay ? (
+ <FullOverlay
+ isFocused={isFocused}
+ fullOverlayVisible={fullOverlayVisible}
+ >
+ {React.cloneElement(fullOverlay, {
+ onFocus: handleFocus,
+ onBlur: handleBlur
+ })}
+ </FullOverlay>
+ ) : null
}
FullOverlayFocusManager.propTypes = {
fullOverlay: PropTypes.node,
diff --git a/packages/row/src/react/shave.js b/packages/row/src/react/shave.js
index <HASH>..<HASH> 100644
--- a/packages/row/src/react/shave.js
+++ b/packages/row/src/react/shave.js
@@ -1,51 +1,33 @@
import PropTypes from 'prop-types'
-import React from 'react'
+import React, { useEffect, useRef, useCallback } from 'react'
import shave from 'shave'
import core from '@pluralsight/ps-design-system-core'
-import filterReactProps from '@pluralsight/ps-design-system-filter-react-props'
-class Shave extends React.Component {
- constructor(props) {
- super(props)
-
- this.elRef = React.createRef()
-
- this.reset = this.reset.bind(this)
- this.truncate = this.truncate.bind(this)
- }
-
- componentDidMount() {
- window.addEventListener('resize', this.truncate)
- this.truncate()
- }
-
- componentWillUpdate() {
- this.reset()
- }
-
- componentDidUpdate() {
- this.truncate()
- }
-
- componentWillUnmount() {
- this.reset()
- window.removeEventListener('resize', this.truncate)
- }
-
- reset() {
- this.elRef.current.innerHTML = this.props.children
- }
-
- truncate() {
- const maxHeight = this.props.lineHeight * this.props.lines
- shave(this.elRef.current, maxHeight, { character: this.props.character })
- }
-
- render() {
- return <div ref={this.elRef} {...filterReactProps(this.props)} />
+const reset = (children, current) => {
+ if (current) {
+ current.innerHTML = children
}
}
+const Shave = ({ children, lineHeight, lines, character, ...rest }) => {
+ const elRef = useRef()
+ useEffect(() => {
+ reset(children, elRef.current)
+ }, [children])
+ const truncate = useCallback(() => {
+ const maxHeight = lineHeight * lines
+ shave(elRef.current, maxHeight, { character: character })
+ }, [lineHeight, lines, character])
+ useEffect(() => {
+ window.addEventListener('resize', truncate)
+ truncate()
+ return _ => {
+ window.removeEventListener('resize', truncate)
+ }
+ }, [truncate])
+
+ return <div ref={elRef} children={children} {...rest} />
+}
Shave.defaultProps = {
character: '…',
|
refactor(row): upgrade to functional components
|
pluralsight_design-system
|
train
|
a73177b6390de46f2bb6cfbf463e11e0d5fa0d00
|
diff --git a/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java b/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java
index <HASH>..<HASH> 100755
--- a/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java
+++ b/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java
@@ -1423,7 +1423,7 @@ public class DRFTest extends TestUtil {
parms._seed = 234;
parms._min_rows = 1;
parms._max_depth = 15;
- parms._ntrees = 10;
+ parms._ntrees = 2;
parms._mtries = Math.max(1,(int)(col_sample_rate*(tfr.numCols()-1)));
parms._col_sample_rate_per_tree = col_sample_rate_per_tree;
parms._sample_rate = sample_rate;
|
Speed up testColSamplingPerTree in DRF JUnits.
|
h2oai_h2o-3
|
train
|
594049b24fbfca64d39104ccc4e5d036903c8f06
|
diff --git a/client/client.go b/client/client.go
index <HASH>..<HASH> 100644
--- a/client/client.go
+++ b/client/client.go
@@ -491,21 +491,13 @@ func (r *NotaryRepository) GetTargetByName(name string, roles ...string) (*Targe
meta *data.FileMeta
)
for i := len(roles) - 1; i >= 0; i-- {
- meta, err = c.TargetMeta(roles[i], name, roles...)
- if err != nil {
- // important to error here otherwise there might be malicious
- // behaviour that prevents a legitimate version of a target
- // being found
- return nil, err
- } else if meta != nil {
- break
+ meta = c.TargetMeta(roles[i], name, roles...)
+ if meta != nil {
+ return &Target{Name: name, Hashes: meta.Hashes, Length: meta.Length}, nil
}
}
- if meta == nil {
- return nil, fmt.Errorf("No trust data for %s", name)
- }
+ return nil, fmt.Errorf("No trust data for %s", name)
- return &Target{Name: name, Hashes: meta.Hashes, Length: meta.Length}, nil
}
// GetChangelist returns the list of the repository's unpublished changes
diff --git a/tuf/client/client.go b/tuf/client/client.go
index <HASH>..<HASH> 100644
--- a/tuf/client/client.go
+++ b/tuf/client/client.go
@@ -393,6 +393,11 @@ func (c *Client) downloadTargets(role string) error {
keyIDs := r.KeyIDs
s, err := c.getTargetsFile(role, keyIDs, snap.Meta, root.ConsistentSnapshot, r.Threshold)
if err != nil {
+ if _, ok := err.(store.ErrMetaNotFound); ok {
+ // if the role meta hasn't been published,
+ // that's ok, continue
+ continue
+ }
logrus.Error("Error getting targets file:", err)
return err
}
@@ -520,10 +525,7 @@ func (c Client) RoleTargetsPath(role string, hashSha256 string, consistent bool)
// TargetMeta ensures the repo is up to date. It assumes downloadTargets
// has already downloaded all delegated roles
-func (c Client) TargetMeta(role, path string, excludeRoles ...string) (*data.FileMeta, error) {
- c.Update()
- var meta *data.FileMeta
-
+func (c Client) TargetMeta(role, path string, excludeRoles ...string) *data.FileMeta {
excl := make(map[string]bool)
for _, r := range excludeRoles {
excl[r] = true
@@ -534,7 +536,10 @@ func (c Client) TargetMeta(role, path string, excludeRoles ...string) (*data.Fil
// FIFO list of targets delegations to inspect for target
roles := []string{role}
- var curr string
+ var (
+ meta *data.FileMeta
+ curr string
+ )
for len(roles) > 0 {
// have to do these lines here because of order of execution in for statement
curr = roles[0]
@@ -543,7 +548,7 @@ func (c Client) TargetMeta(role, path string, excludeRoles ...string) (*data.Fil
meta = c.local.TargetMeta(curr, path)
if meta != nil {
// we found the target!
- return meta, nil
+ return meta
}
delegations := c.local.TargetDelegations(role, path, pathHex)
for _, d := range delegations {
@@ -552,7 +557,7 @@ func (c Client) TargetMeta(role, path string, excludeRoles ...string) (*data.Fil
}
}
}
- return meta, nil
+ return meta
}
// DownloadTarget downloads the target to dst from the remote
|
fixing download to continue if we get ErrMetaNotFound
|
theupdateframework_notary
|
train
|
b6dd8661fcb2c18f46f9865ba1513ae4db70cf69
|
diff --git a/lib/shapewear/wsdl.rb b/lib/shapewear/wsdl.rb
index <HASH>..<HASH> 100644
--- a/lib/shapewear/wsdl.rb
+++ b/lib/shapewear/wsdl.rb
@@ -12,6 +12,7 @@ module Shapewear::WSDL
xm.definitions :name => self.name, 'targetNamespace' => namespaces['tns'],
'xmlns' => namespaces['wsdl'],
'xmlns:soap' => namespaces['soap'],
+ 'xmlns:xsd' => namespaces['xsd'],
'xmlns:xsd1' => namespaces['xsd1'],
'xmlns:tns' => namespaces['tns'] do |xdef|
|
The XSD namespace was missing.
|
elementar_shapewear
|
train
|
9df18901541680b36d7d962a2d33cb34d836987f
|
diff --git a/stun/discover.go b/stun/discover.go
index <HASH>..<HASH> 100644
--- a/stun/discover.go
+++ b/stun/discover.go
@@ -136,10 +136,9 @@ func (c *Client) discover(conn net.PacketConn, addr *net.UDPAddr) (NATType, *Hos
resp.serverAddr.Port() != uint16(caddr.Port) {
return NATError, mappedAddr, errors.New("Server error: response IP/port")
}
- if mappedAddr.IP() == resp.mappedAddr.IP() {
- // Perform test2 to see if the client can receive packet sent
+ if mappedAddr.IP() == resp.mappedAddr.IP() && mappedAddr.Port() == resp.mappedAddr.Port() {
+ // Perform test3 to see if the client can receive packet sent
// from another port.
- caddr.Port = addr.Port
c.logger.Debugln("Do Test3")
c.logger.Debugln("Send To:", caddr)
resp, err = c.test3(conn, caddr)
|
Fix two more bugs (fixes #<I>)
|
ccding_go-stun
|
train
|
ba3899e461576a0c77740257d23f97448ef2dd31
|
diff --git a/src/config/environment.js b/src/config/environment.js
index <HASH>..<HASH> 100644
--- a/src/config/environment.js
+++ b/src/config/environment.js
@@ -4,6 +4,7 @@ import { isFunction } from 'utils/is';
const win = typeof window !== 'undefined' ? window : null;
const doc = win ? document : null;
const isClient = !!doc;
+const base = typeof global !== 'undefined' ? global : win;
const hasConsole =
typeof console !== 'undefined' && isFunction(console.warn) && isFunction(console.warn.apply);
@@ -13,4 +14,4 @@ const svg = doc
const vendors = ['o', 'ms', 'moz', 'webkit'];
-export { win, doc, isClient, hasConsole, svg, vendors };
+export { win, doc, isClient, hasConsole, svg, vendors, base };
diff --git a/src/model/specials/SharedModel.js b/src/model/specials/SharedModel.js
index <HASH>..<HASH> 100644
--- a/src/model/specials/SharedModel.js
+++ b/src/model/specials/SharedModel.js
@@ -1,5 +1,6 @@
/* global global */
import Model from '../Model';
+import { base } from 'config/environment';
export const data = {};
@@ -25,7 +26,4 @@ export class SharedModel extends Model {
export default new SharedModel(data, 'shared');
-export const GlobalModel = new SharedModel(
- typeof global !== 'undefined' ? global : window,
- 'global'
-);
+export const GlobalModel = new SharedModel(base, 'global');
diff --git a/src/polyfills/Promise.js b/src/polyfills/Promise.js
index <HASH>..<HASH> 100644
--- a/src/polyfills/Promise.js
+++ b/src/polyfills/Promise.js
@@ -1,12 +1,13 @@
import { isFunction, isObjectType } from 'utils/is';
+import { base } from 'config/environment';
/* istanbul ignore if */
-if (typeof window !== 'undefined' && !window.Promise) {
+if (!base.Promise) {
const PENDING = {};
const FULFILLED = {};
const REJECTED = {};
- const Promise = (window.Promise = function(callback) {
+ const Promise = (base.Promise = function(callback) {
const fulfilledHandlers = [];
const rejectedHandlers = [];
let state = PENDING;
@@ -64,18 +65,30 @@ if (typeof window !== 'undefined' && !window.Promise) {
},
catch(onRejected) {
return this.then(null, onRejected);
+ },
+ finally(callback) {
+ return this.then(
+ v => {
+ callback();
+ return v;
+ },
+ e => {
+ callback();
+ throw e;
+ }
+ );
}
};
});
Promise.all = function(promises) {
- return new Promise((fulfil, reject) => {
+ return new Promise((fulfill, reject) => {
const result = [];
let pending;
let i;
if (!promises.length) {
- fulfil(result);
+ fulfill(result);
return;
}
@@ -83,11 +96,11 @@ if (typeof window !== 'undefined' && !window.Promise) {
if (promise && isFunction(promise.then)) {
promise.then(value => {
result[i] = value;
- --pending || fulfil(result);
+ --pending || fulfill(result);
}, reject);
} else {
result[i] = promise;
- --pending || fulfil(result);
+ --pending || fulfill(result);
}
};
@@ -99,13 +112,36 @@ if (typeof window !== 'undefined' && !window.Promise) {
});
};
+ Promise.race = function(promises) {
+ return new Promise((fulfill, reject) => {
+ let pending = true;
+ function ok(v) {
+ if (!pending) return;
+ pending = false;
+ fulfill(v);
+ }
+ function fail(e) {
+ if (!pending) return;
+ pending = false;
+ reject(e);
+ }
+ for (let i = 0; i < promises.length; i++) {
+ if (promises[i] && isFunction(promises[i].then)) {
+ promises[i].then(ok, fail);
+ }
+ }
+ });
+ };
+
Promise.resolve = function(value) {
+ if (value && isFunction(value.then)) return value;
return new Promise(fulfill => {
fulfill(value);
});
};
Promise.reject = function(reason) {
+ if (reason && isFunction(reason.then)) return reason;
return new Promise((fulfill, reject) => {
reject(reason);
});
|
adjust promise polyfill to be a bit more compliant and add race and finally - fixes #<I>
|
ractivejs_ractive
|
train
|
dd7f729dc38e56efdbcb96e4113187544e7b8758
|
diff --git a/app/helpers/filepicker_rails/application_helper.rb b/app/helpers/filepicker_rails/application_helper.rb
index <HASH>..<HASH> 100644
--- a/app/helpers/filepicker_rails/application_helper.rb
+++ b/app/helpers/filepicker_rails/application_helper.rb
@@ -78,62 +78,55 @@ module FilepickerRails
class FilepickerImageUrl
- VALID_OPTIONS = [:w, :h, :fit, :align, :rotate, :cache, :crop, :format,
- :quality, :watermark, :watersize, :waterposition]
+ CONVERT_OPTIONS = [:w, :h, :fit, :align, :rotate, :crop, :format,
+ :quality, :watermark, :watersize, :waterposition]
+ VALID_OPTIONS = CONVERT_OPTIONS + [:cache]
def initialize(url, options = {})
@url, @options = url, options
- remove_invalid_options
- apply_cdn_to_url
- apply_policy
end
def execute
- query_params = options.to_query
- if has_convert_options?
- [url, '/convert?', query_params]
- elsif has_policy?
- [url,'?', query_params]
+ url_with_path = if convert_options.any?
+ "#{cdn_url}/convert"
else
- [url, query_params]
- end.join
+ cdn_url
+ end
+
+ query_params = all_options.merge(policy_config).to_query
+
+ [url_with_path, query_params.presence].compact.join('?')
end
private
attr_reader :url, :options
- def remove_invalid_options
- options.delete_if{ |o| !VALID_OPTIONS.include?(o) }
+ def all_options
+ options.select { |option| VALID_OPTIONS.include?(option) }
end
- def cdn_host
- ::Rails.application.config.filepicker_rails.cdn_host
+ def convert_options
+ options.select { |option| CONVERT_OPTIONS.include?(option) }
end
- def has_policy?
- policy_config.any?
- end
-
- def has_convert_options?
- options.keys.any?{ |k| VALID_OPTIONS.include?(k) }
+ def cdn_host
+ ::Rails.application.config.filepicker_rails.cdn_host
end
- def apply_cdn_to_url
+ def cdn_url
if cdn_host
uri = URI.parse(url)
- @url = url.gsub("#{uri.scheme}://#{uri.host}", cdn_host)
+ url.gsub("#{uri.scheme}://#{uri.host}", cdn_host)
+ else
+ url
end
end
- def apply_policy
- options.merge!(policy_config)
- end
-
def policy_config
return {} unless ::Rails.application.config.filepicker_rails.secret_key.present?
grant = Policy.new
- grant.call = [:pick, :store]
+ grant.call = [:read, :convert]
{
'policy' => grant.policy,
diff --git a/spec/helpers/application_helper_spec.rb b/spec/helpers/application_helper_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/helpers/application_helper_spec.rb
+++ b/spec/helpers/application_helper_spec.rb
@@ -123,7 +123,7 @@ describe FilepickerRails::ApplicationHelper do
end
it "have correct url with 'cache'" do
- expect(filepicker_image_url("foo", cache: true)).to eq('foo/convert?cache=true')
+ expect(filepicker_image_url("foo", cache: true)).to eq('foo?cache=true')
end
it "have correct url with 'crop'" do
@@ -176,26 +176,30 @@ describe FilepickerRails::ApplicationHelper do
context 'with policy' do
before do
- Timecop.freeze(Time.zone.parse("2012-09-19 12:59:27"))
Rails.application.config.filepicker_rails.secret_key = 'filepicker123secretkey'
end
after do
Rails.application.config.filepicker_rails.secret_key = nil
- Timecop.return
end
it 'have policy and signature' do
- url = 'foo?policy=eyJleHBpcnkiOjEzNDgwNjAxNjcsImNhbGwiOlsicGljayIsInN0b3JlIl19' \
- '&signature=7bbfb03a94967056d4c98140a3ce188ec7a5b575d2cd86fe5528d7fafb3387c3'
+ expiry = Time.now.to_i
+ FilepickerRails::Policy.any_instance.stub(:expiry).and_return(expiry)
+ json_policy = {expiry: expiry, call: [:read, :convert]}.to_json
+ policy = Base64.urlsafe_encode64(json_policy)
+ signature = OpenSSL::HMAC.hexdigest('sha256', 'filepicker123secretkey', policy)
+ url = "foo?#{{policy: policy, signature: signature}.to_param}"
expect(filepicker_image_url('foo')).to eq(url)
end
it 'have policy and signature when have some convert option' do
- url = 'foo/convert' \
- '?policy=eyJleHBpcnkiOjEzNDgwNjAxNjcsImNhbGwiOlsicGljayIsInN0b3JlIl19' \
- '&quality=80' \
- '&signature=7bbfb03a94967056d4c98140a3ce188ec7a5b575d2cd86fe5528d7fafb3387c3'
+ expiry = Time.now.to_i
+ FilepickerRails::Policy.any_instance.stub(:expiry).and_return(expiry)
+ json_policy = {expiry: expiry, call: [:read, :convert]}.to_json
+ policy = Base64.urlsafe_encode64(json_policy)
+ signature = OpenSSL::HMAC.hexdigest('sha256', 'filepicker123secretkey', policy)
+ url = "foo/convert?#{{policy: policy, quality: 80, signature: signature}.to_param}"
expect(filepicker_image_url('foo', quality: 80)).to eq(url)
end
end
|
Fix the default policy for filepicker_image_url
* Need read/convert, not pick/store.
* Only call the convert end point when CONVERT_OPTIONS are present.
* Don't mutate @url, just use functions.
|
filestack_filestack-rails
|
train
|
cbe599e98e1101b47c6b17ff3cd7635dc12319ec
|
diff --git a/molgenis-data-mapper/src/main/java/org/molgenis/data/mapper/controller/MappingServiceController.java b/molgenis-data-mapper/src/main/java/org/molgenis/data/mapper/controller/MappingServiceController.java
index <HASH>..<HASH> 100644
--- a/molgenis-data-mapper/src/main/java/org/molgenis/data/mapper/controller/MappingServiceController.java
+++ b/molgenis-data-mapper/src/main/java/org/molgenis/data/mapper/controller/MappingServiceController.java
@@ -1,5 +1,6 @@
package org.molgenis.data.mapper.controller;
+import static com.google.common.collect.Iterators.size;
import static org.molgenis.data.mapper.controller.MappingServiceController.URI;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
@@ -431,6 +432,7 @@ public class MappingServiceController extends MolgenisPluginController
.getAttribute(sourceAttribute).getRefEntity().getName());
}
model.addAttribute("sourceAttributeRefEntityEntities", sourceAttributeRefEntityEntities);
+ model.addAttribute("numberOfSourceAttributes", size(sourceAttributeRefEntityEntities.iterator()));
// values for target xref / categoricals / String
Iterable<Entity> targetAttributeRefEntityEntities = dataService.findAll(dataService.getEntityMetaData(target)
@@ -476,8 +478,8 @@ public class MappingServiceController extends MolgenisPluginController
// TODO If an algorithm with the map function exists, dissect it into usable interface thing
model.addAttribute("target", target);
model.addAttribute("source", source);
- model.addAttribute("targetAttribute", targetAttribute);
- model.addAttribute("sourceAttribute", sourceAttribute);
+ model.addAttribute("targetAttribute", dataService.getEntityMetaData(target).getAttribute(targetAttribute));
+ model.addAttribute("sourceAttribute", dataService.getEntityMetaData(source).getAttribute(sourceAttribute));
model.addAttribute("hasWritePermission", hasWritePermission(project, false));
return VIEW_CATEGORY_MAPPING_EDITOR;
|
Add target and source attribute metadata to the model instead of the names. Add number of source attributes to the model
|
molgenis_molgenis
|
train
|
a3b67f2236149ab31ac5992ab51ecba8d707b0b2
|
diff --git a/chef/lib/chef/runner.rb b/chef/lib/chef/runner.rb
index <HASH>..<HASH> 100644
--- a/chef/lib/chef/runner.rb
+++ b/chef/lib/chef/runner.rb
@@ -47,9 +47,29 @@ class Chef
# Determine the appropriate provider for the given resource, then
# execute it.
def run_action(resource, action, delayed_actions)
+ # Check if this resource has an only_if block -- if it does,
+ # evaluate the only_if block and skip the resource if
+ # appropriate.
+ if resource.only_if
+ unless Chef::Mixin::Command.only_if(resource.only_if, resource.only_if_args)
+ Chef::Log.debug("Skipping #{resource} due to only_if")
+ return
+ end
+ end
+
+ # Check if this resource has a not_if block -- if it does,
+ # evaluate the not_if block and skip the resource if
+ # appropriate.
+ if resource.not_if
+ unless Chef::Mixin::Command.not_if(resource.not_if, resource.not_if_args)
+ Chef::Log.debug("Skipping #{resource} due to not_if")
+ return
+ end
+ end
+
provider = build_provider(resource)
provider.send("action_#{action}")
-
+
# Execute any immediate and queue up any delayed notifications
# associated with the resource.
if resource.updated
@@ -57,7 +77,7 @@ class Chef
Chef::Log.info("#{resource} sending #{notify.action} action to #{notify.resource} (immediate)")
run_action(notify.resource, notify.action, delayed_actions)
end
-
+
resource.notifies_delayed.each do |notify|
unless delayed_actions.include?(notify)
delayed_actions << notify
@@ -83,26 +103,6 @@ class Chef
begin
Chef::Log.debug("Processing #{resource} on #{run_context.node.name}")
- # Check if this resource has an only_if block -- if it does,
- # evaluate the only_if block and skip the resource if
- # appropriate.
- if resource.only_if
- unless Chef::Mixin::Command.only_if(resource.only_if, resource.only_if_args)
- Chef::Log.debug("Skipping #{resource} due to only_if")
- next
- end
- end
-
- # Check if this resource has a not_if block -- if it does,
- # evaluate the not_if block and skip the resource if
- # appropriate.
- if resource.not_if
- unless Chef::Mixin::Command.not_if(resource.not_if, resource.not_if_args)
- Chef::Log.debug("Skipping #{resource} due to not_if")
- next
- end
- end
-
# Execute each of this resource's actions.
action_list = resource.action.kind_of?(Array) ? resource.action : [ resource.action ]
action_list.each do |action|
diff --git a/chef/spec/unit/runner_spec.rb b/chef/spec/unit/runner_spec.rb
index <HASH>..<HASH> 100644
--- a/chef/spec/unit/runner_spec.rb
+++ b/chef/spec/unit/runner_spec.rb
@@ -179,6 +179,17 @@ describe Chef::Runner do
provider.should_receive(:action_pur).once.ordered
@runner.converge
end
-
+
+ it "should check a resource's only_if and not_if if notified by another resource" do
+ provider = Chef::Provider::SnakeOil.new(@run_context.resource_collection[0], @run_context)
+ @run_context.resource_collection[0].action = :nothing
+ @run_context.resource_collection << Chef::Resource::Cat.new("carmel", @run_context)
+ @run_context.resource_collection[1].notifies :buy, @run_context.resource_collection[0], :delayed
+ @run_context.resource_collection[1].updated = true
+ # hits only_if first time when the resource is run in order, second on notify
+ @run_context.resource_collection[0].should_receive(:only_if).exactly(2).times.and_return(nil)
+ @run_context.resource_collection[0].should_receive(:not_if).exactly(2).times.and_return(nil)
+ @runner.converge
+ end
end
|
CHEF-<I> - only_if and not_if not checked on notifies
|
chef_chef
|
train
|
1b0ce2772311dd59b9d84143ae914aef6763e368
|
diff --git a/test/get.js b/test/get.js
index <HASH>..<HASH> 100644
--- a/test/get.js
+++ b/test/get.js
@@ -1,5 +1,7 @@
'use strict';
+const tryCatch = require('try-catch');
+
const fs = require('fs');
const test = require('supertape');
const fixture = {
@@ -37,9 +39,9 @@ test('restafary: path traversal', async (t) => {
},
});
- const fn = () => JSON.parse(body);
+ const [error] = tryCatch(JSON.parse, body);
- t.doesNotThrow(fn, 'should not throw');
+ t.notOk(error, 'should not throw');
t.end();
});
@@ -49,9 +51,9 @@ test('restafary: path traversal, not default root', async (t) => {
root: '/usr',
},
});
- const fn = () => JSON.parse(body);
+ const [error] = tryCatch(JSON.parse, body);
- t.doesNotThrow(fn, 'should not throw');
+ t.notOk(error, 'should not throw');
t.end();
});
|
test(restafary) doesNotThrow -> tryCatch
|
coderaiser_node-restafary
|
train
|
4d9b46ccf15b60ad1c22784b76014a899d22f420
|
diff --git a/backend/servers/express-webrouter/app/index.js b/backend/servers/express-webrouter/app/index.js
index <HASH>..<HASH> 100644
--- a/backend/servers/express-webrouter/app/index.js
+++ b/backend/servers/express-webrouter/app/index.js
@@ -30,9 +30,7 @@ function getSetup() {
}))
// it is important to put all the apis uses before this useRender
useRender(app, {
- extraContext: {
- SITE_NAME
- }
+ getExtraConfig: req => ({ SITE_NAME })
})
const server = http.Server(app)
resolve({ app,
diff --git a/backend/servers/express-webrouter/app/src/render.js b/backend/servers/express-webrouter/app/src/render.js
index <HASH>..<HASH> 100644
--- a/backend/servers/express-webrouter/app/src/render.js
+++ b/backend/servers/express-webrouter/app/src/render.js
@@ -9,7 +9,7 @@ const packageConfig = JSON.parse(
fs.readFileSync(path.join(__dirname, '../../package.json'))
.toString('utf-8')
)
-const { TRACKING_ID, SITE_NAME } = process.env
+const { SITE_LABEL } = process.env
let TELEPORT_WELCOME = {}
const teleportDir = path.join(__dirname, '../../config/teleport_welcome.json')
if (fs.existsSync(teleportDir)) {
@@ -19,7 +19,7 @@ const TELEPORT_WELCOME_STRING = `'${JSON.stringify(TELEPORT_WELCOME)}'`
export function useRender(app, config = {}) {
// unpack
- const getExtraContext = config.getExtraContext
+ const getExtraConfig = config.getExtraConfig
// set render
app.set('view engine', 'html')
app.engine('html', ejs.renderFile)
@@ -43,15 +43,14 @@ export function useRender(app, config = {}) {
}
indexFileDir = path.join(__dirname, `../templates/${indexFileName}`)
// set the extraContext
- const extraContext = (getExtraContext && getExtraContext(req, res)) || config.extraContext || {}
+ const extraConfig = (getExtraConfig && getExtraConfig(req, res)) || config.extraContext || {}
// update the context
- app.set('context', Object.assign(app.get('context') || {}, {
- SITE_NAME,
+ app.set('config', Object.assign(app.get('config') || {}, {
+ SITE_LABEL,
TELEPORT_WELCOME,
- TELEPORT_WELCOME_STRING,
- TRACKING_ID
- }, extraContext))
+ TELEPORT_WELCOME_STRING
+ }, extraConfig))
// render
- res.render(indexFileDir, app.get('context'))
+ res.render(indexFileDir, app.get('config'))
})
}
diff --git a/backend/servers/express-webrouter/app/templates/_body.html b/backend/servers/express-webrouter/app/templates/_body.html
index <HASH>..<HASH> 100644
--- a/backend/servers/express-webrouter/app/templates/_body.html
+++ b/backend/servers/express-webrouter/app/templates/_body.html
@@ -51,9 +51,6 @@
}
.teleport__templates__img {
width: 50px;
- @media (min-width: 768px) {
- width: 50px;
- }
}
.teleport__footer {
font-size: 20px;
@@ -82,10 +79,10 @@
Teleport
</a>
</div>
- <div class="teleport__templates p2 mb3">
+ <div class="teleport__templates p1 mb3">
<div class="flex justify-center items-center">
<% for(var i=0; i<TELEPORT_WELCOME.templates.length; i++) { %>
- <div class="mr2">
+ <div class="mr1">
<a
title='<%= TELEPORT_WELCOME.templates[i].name %>'
href='<%= TELEPORT_WELCOME.templates[i].gitUrl %>'>
|
changed render getExtraConfig option
|
Ledoux_teleport-express-webrouter
|
train
|
d6d1028f7330e1141c2b3f8730a3f06357be2661
|
diff --git a/base/SearchModelTrait.php b/base/SearchModelTrait.php
index <HASH>..<HASH> 100644
--- a/base/SearchModelTrait.php
+++ b/base/SearchModelTrait.php
@@ -10,6 +10,7 @@ namespace hipanel\base;
use hiqdev\hiar\ActiveQuery;
use hiqdev\hiar\ActiveRecord;
use yii\data\ActiveDataProvider;
+use yii\helpers\ArrayHelper;
/**
* Trait SearchModelTrait
@@ -48,19 +49,20 @@ trait SearchModelTrait
/**
* Creates data provider instance with search query applied
- *
- * @param array $params
+ * @param $params
+ * @param array $dataProviderConfig
* @return ActiveDataProvider
+ * @throws \yii\base\InvalidConfigException
*/
- public function search ($params) {
+ public function search ($params, $dataProviderConfig = []) {
/**
* @var ActiveRecord $this
* @var ActiveRecord $class
* @var ActiveQuery $query
*/
$class = get_parent_class();
- $query = $class::find();
- $dataProvider = new ActiveDataProvider(compact('query'));
+ $query = $class::find(); // $class::find()->orderBy($sort->orders)->all(); if $sort is Sort obj
+ $dataProvider = new ActiveDataProvider(ArrayHelper::merge(compact('query'), $dataProviderConfig));
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
|
DataProvider config to search model
|
hiqdev_hipanel-core
|
train
|
0617190b040a904daff7668f527632a1d5b12ec7
|
diff --git a/faadata/airports/load.py b/faadata/airports/load.py
index <HASH>..<HASH> 100644
--- a/faadata/airports/load.py
+++ b/faadata/airports/load.py
@@ -136,6 +136,8 @@ def airport_import(importfile, config={'import_att': True, 'import_rmk': True, '
try:
airport.save()
except Exception, e:
+ from pprint import pprint
+ pprint(data)
print('Airport data fail for %s' % data['location_identifier'])
print e
|
In the case of a failure here it helps to see what data matches.
|
adamfast_faadata
|
train
|
cda221c15fb50f4514e8fc257dd78b081cd3c05c
|
diff --git a/dotsite/paths.py b/dotsite/paths.py
index <HASH>..<HASH> 100644
--- a/dotsite/paths.py
+++ b/dotsite/paths.py
@@ -465,7 +465,8 @@ def makepath(string, as_file=False):
result = DirectPath(string_path)
return result.expand().realpath().abspath()
-# See also http://stackoverflow.com/questions/26403972/how-do-i-get-rid-of-make-xxx-method # noqa
+# See also http://stackoverflow.com/questions/26403972
+# /how-do-i-get-rid-of-make-xxx-method
path = makepath
|
Wrap URL to keep under <I> chars
|
jalanb_pysyte
|
train
|
f15bbadd7267382da082f6e13a8ed92a17b263c0
|
diff --git a/andes/variables/dae.py b/andes/variables/dae.py
index <HASH>..<HASH> 100644
--- a/andes/variables/dae.py
+++ b/andes/variables/dae.py
@@ -1,7 +1,12 @@
import logging
+import numpy as np
+
+from typing import List, Union
from collections import OrderedDict
+
from andes.core import JacTriplet
-from andes.shared import pd, np, spmatrix, jac_names
+from andes.core.var import BaseVar
+from andes.shared import pd, spmatrix, jac_names
logger = logging.getLogger(__name__)
@@ -115,6 +120,40 @@ class DAETimeSeries:
return True
+ def get_data(self, base_vars: Union[BaseVar, List[BaseVar]], a=None):
+ """
+ Get time-series data for a variable instance.
+
+ Values for different variables will be stacked horizontally.
+
+ Parameters
+ ----------
+ base_var : BaseVar or a sequence of BaseVar(s)
+ The variable types and internal addresses
+ are used for looking up the data.
+ a : an array-like of int or None
+ Sub-indices into the address of `base_var`.
+ Applied to each variable.
+
+ """
+ out = np.zeros((len(self.t), 0))
+ if isinstance(base_vars, BaseVar):
+ base_vars = (base_vars, )
+
+ for base_var in base_vars:
+ if base_var.n == 0:
+ logger.info("Variable <%s.%s> does not contain any element.",
+ base_var.owner.class_name, base_var.name)
+ continue
+
+ indices = base_var.a
+ if a is not None:
+ indices = indices[a]
+
+ out = np.hstack((out, self.__dict__[base_var.v_code][:, indices]))
+
+ return out
+
@property
def df(self):
return self.df_xy
diff --git a/tests/test_tds_resume.py b/tests/test_tds_resume.py
index <HASH>..<HASH> 100644
--- a/tests/test_tds_resume.py
+++ b/tests/test_tds_resume.py
@@ -21,3 +21,14 @@ class TestTDSResume(unittest.TestCase):
# check if values are correctly stored
self.assertTrue(len(ss.dae.ts._ys[0.1]) > 0)
self.assertTrue(len(ss.dae.ts._ys[0.5]) > 0)
+
+ # check if `get_data` works
+ data1 = ss.dae.ts.get_data((ss.GENROU.omega, ss.GENROU.v))
+ data2 = ss.dae.ts.get_data((ss.GENROU.omega, ss.GENROU.v), a=[2])
+ nt = len(ss.dae.ts.t)
+
+ self.assertEqual(data1.shape[1], 8)
+ self.assertEqual(data1.shape[0], nt)
+
+ self.assertEqual(data2.shape[1], 2)
+ self.assertEqual(data2.shape[0], nt)
|
Implemented `get_data` for DAETimeSeries.
|
cuihantao_andes
|
train
|
bc3cad209f6f4d1f4e52759490001017f7b1c70f
|
diff --git a/src/app/controllers/graphiteTarget.js b/src/app/controllers/graphiteTarget.js
index <HASH>..<HASH> 100644
--- a/src/app/controllers/graphiteTarget.js
+++ b/src/app/controllers/graphiteTarget.js
@@ -32,7 +32,7 @@ function (angular, _, config, graphiteFunctions, Parser) {
if (astNode.type === 'function') {
var innerFunc = {};
- innerFunc.def = _.findWhere($scope.funcDefs, { name: astNode.name })
+ innerFunc.def = _.findWhere($scope.funcDefs, { name: astNode.name });
innerFunc.params = innerFunc.def.defaultParams;
_.each(astNode.params, function(param, index) {
diff --git a/src/app/services/graphite/lexer.js b/src/app/services/graphite/lexer.js
index <HASH>..<HASH> 100644
--- a/src/app/services/graphite/lexer.js
+++ b/src/app/services/graphite/lexer.js
@@ -577,7 +577,7 @@ define([
* var str = "hello\
* world";
*/
- scanStringLiteral: function (checks) {
+ scanStringLiteral: function () {
/*jshint loopfunc:true */
var quote = this.peek();
@@ -587,8 +587,6 @@ define([
}
var value = "";
- var startLine = this.line;
- var startChar = this.char;
this.skip();
diff --git a/src/app/services/graphite/parser.js b/src/app/services/graphite/parser.js
index <HASH>..<HASH> 100644
--- a/src/app/services/graphite/parser.js
+++ b/src/app/services/graphite/parser.js
@@ -11,11 +11,6 @@ define([
StringLiteral: 6
};
- function Node(type, value) {
- this.type = type;
- this.value = value;
- }
-
function Parser(expression) {
this.expression = expression;
this.lexer = new Lexer(expression);
|
integrated parser into graphite target editor
|
grafana_grafana
|
train
|
0681acbf6921e95caeec87bf518ac7bd3061ce1e
|
diff --git a/nomad/job_endpoint_test.go b/nomad/job_endpoint_test.go
index <HASH>..<HASH> 100644
--- a/nomad/job_endpoint_test.go
+++ b/nomad/job_endpoint_test.go
@@ -11,7 +11,9 @@ import (
)
func TestJobEndpoint_Register(t *testing.T) {
- s1 := testServer(t, nil)
+ s1 := testServer(t, func(c *Config) {
+ c.NumSchedulers = 0 // Prevent automatic dequeue
+ })
defer s1.Shutdown()
codec := rpcClient(t, s1)
testutil.WaitForLeader(t, s1.RPC)
@@ -78,7 +80,9 @@ func TestJobEndpoint_Register(t *testing.T) {
}
func TestJobEndpoint_Register_Existing(t *testing.T) {
- s1 := testServer(t, nil)
+ s1 := testServer(t, func(c *Config) {
+ c.NumSchedulers = 0 // Prevent automatic dequeue
+ })
defer s1.Shutdown()
codec := rpcClient(t, s1)
testutil.WaitForLeader(t, s1.RPC)
@@ -162,7 +166,9 @@ func TestJobEndpoint_Register_Existing(t *testing.T) {
}
func TestJobEndpoint_Evaluate(t *testing.T) {
- s1 := testServer(t, nil)
+ s1 := testServer(t, func(c *Config) {
+ c.NumSchedulers = 0 // Prevent automatic dequeue
+ })
defer s1.Shutdown()
codec := rpcClient(t, s1)
testutil.WaitForLeader(t, s1.RPC)
@@ -231,7 +237,9 @@ func TestJobEndpoint_Evaluate(t *testing.T) {
}
func TestJobEndpoint_Deregister(t *testing.T) {
- s1 := testServer(t, nil)
+ s1 := testServer(t, func(c *Config) {
+ c.NumSchedulers = 0 // Prevent automatic dequeue
+ })
defer s1.Shutdown()
codec := rpcClient(t, s1)
testutil.WaitForLeader(t, s1.RPC)
diff --git a/nomad/node_endpoint_test.go b/nomad/node_endpoint_test.go
index <HASH>..<HASH> 100644
--- a/nomad/node_endpoint_test.go
+++ b/nomad/node_endpoint_test.go
@@ -529,7 +529,9 @@ func TestClientEndpoint_CreateNodeEvals(t *testing.T) {
}
func TestClientEndpoint_Evaluate(t *testing.T) {
- s1 := testServer(t, nil)
+ s1 := testServer(t, func(c *Config) {
+ c.NumSchedulers = 0 // Prevent automatic dequeue
+ })
defer s1.Shutdown()
codec := rpcClient(t, s1)
testutil.WaitForLeader(t, s1.RPC)
|
Fix race condition in server endpoint tests in which workers would process evals before there status could be asserted
|
hashicorp_nomad
|
train
|
a9e1b8fb84a8a4062225f0d05e2aaf4bd5b4fa2d
|
diff --git a/infrastructure.go b/infrastructure.go
index <HASH>..<HASH> 100644
--- a/infrastructure.go
+++ b/infrastructure.go
@@ -966,10 +966,12 @@ func newHTTPClient(config *ConnConfig) (*http.Client, error) {
// Configure TLS if needed.
var tlsConfig *tls.Config
if !config.DisableTLS {
- pool := x509.NewCertPool()
- pool.AppendCertsFromPEM(config.Certificates)
- tlsConfig = &tls.Config{
- RootCAs: pool,
+ if len(config.Certificates) > 0 {
+ pool := x509.NewCertPool()
+ pool.AppendCertsFromPEM(config.Certificates)
+ tlsConfig = &tls.Config{
+ RootCAs: pool,
+ }
}
}
@@ -990,12 +992,14 @@ func dial(config *ConnConfig) (*websocket.Conn, error) {
var tlsConfig *tls.Config
var scheme = "ws"
if !config.DisableTLS {
- pool := x509.NewCertPool()
- pool.AppendCertsFromPEM(config.Certificates)
tlsConfig = &tls.Config{
- RootCAs: pool,
MinVersion: tls.VersionTLS12,
}
+ if len(config.Certificates) > 0 {
+ pool := x509.NewCertPool()
+ pool.AppendCertsFromPEM(config.Certificates)
+ tlsConfig.RootCAs = pool
+ }
scheme = "wss"
}
|
Use system CAs when Certificates are not specified.
This commit modifies the TLS setup to only override the RootCAs for the
TLS connection if certificates are specified. This allows the
Certificates parameter to be ommitted from the connection config to use
the system CAs.
|
btcsuite_btcd
|
train
|
b0b7919bae09e91fa6d3bd0f2bdc1e2d83a35dbc
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -12,13 +12,13 @@ module.exports = function() {};
module.exports.pitch = function(request) {
var callback = this.async();
- var relativeContext = path.dirname(request);
- var extension = '.' + request.split('.').slice(-1)[0];
+ var context = this.context;
+ var extension = request.slice(request.lastIndexOf('.'));
// add context dependency so new files are picked up
- this.addContextDependency(relativeContext);
+ this.addContextDependency(context);
- this.fs.readdir(this.context, function(err, files) {
+ this.fs.readdir(context, function(err, files) {
if (err) return callback(err);
var matchingFiles = files
@@ -36,7 +36,7 @@ module.exports.pitch = function(request) {
var importStatements = matchingFiles
.map(function(info) {
- return 'import * as ' + info.id + ' from ' + JSON.stringify('.' + path.sep + path.join(relativeContext, info.name)) + ';';
+ return 'import * as ' + info.id + ' from ' + JSON.stringify(path.join(context, info.name)) + ';';
})
.join('\n');
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -26,7 +26,7 @@ test('adds a context dependency', async t => {
loader.pitch.call({
context: path.dirname(path.join(__dirname, './src/a.js')),
async: () => (err, result) => { t.truthy(result); r(); },
- addContextDependency: path => t.is(path, './src'),
+ addContextDependency: dep => t.is(dep, path.join(__dirname, 'src')),
fs,
}, './src/a.js');
});
@@ -34,14 +34,18 @@ test('adds a context dependency', async t => {
const header = '/* generated by sibling-loader */';
+function p(file) {
+ return JSON.stringify(path.join(__dirname, file));
+}
+
test('js files', async t => {
t.is(
await runLoader('./src/a.js'),
`
${header}
-import * as _0 from "./src/a.js";
-import * as _1 from "./src/b.js";
-import * as _2 from "./src/c.js";
+import * as _0 from ${p('./src/a.js')};
+import * as _1 from ${p('./src/b.js')};
+import * as _2 from ${p('./src/c.js')};
export default { "a.js": _0, "b.js": _1, "c.js": _2 };
`.trim()
);
@@ -52,7 +56,7 @@ test('txt files', async t => {
await runLoader('./src/test.txt'),
`
${header}
-import * as _0 from "./src/test.txt";
+import * as _0 from ${p('./src/test.txt')};
export default { "test.txt": _0 };
`.trim()
);
@@ -63,8 +67,8 @@ test('md files', async t => {
await runLoader('./src/foo.md'),
`
${header}
-import * as _0 from "./src/bar.md";
-import * as _1 from "./src/foo.md";
+import * as _0 from ${p('./src/bar.md')};
+import * as _1 from ${p('./src/foo.md')};
export default { "bar.md": _0, "foo.md": _1 };
`.trim()
);
|
correct handling of webpack's path expansion
(paths are resolved in full)
|
erikdesjardins_sibling-loader
|
train
|
6e4c77786c9717ee7e20b9397cadaa9034fe498f
|
diff --git a/bucket_crud.go b/bucket_crud.go
index <HASH>..<HASH> 100644
--- a/bucket_crud.go
+++ b/bucket_crud.go
@@ -74,7 +74,9 @@ func (b *Bucket) Prepend(key, value string) (Cas, error) {
return cas, err
}
-// Performs an atomic addition or subtraction for an integer document.
+// Performs an atomic addition or subtraction for an integer document. Passing a
+// non-negative `initial` value will cause the document to be created if it did
+// not already exist.
func (b *Bucket) Counter(key string, delta, initial int64, expiry uint32) (uint64, Cas, error) {
val, cas, _, err := b.counter(key, delta, initial, expiry)
return val, cas, err
@@ -312,7 +314,7 @@ func (b *Bucket) prepend(key, value string) (Cas, MutationToken, error) {
func (b *Bucket) counter(key string, delta, initial int64, expiry uint32) (uint64, Cas, MutationToken, error) {
realInitial := uint64(0xFFFFFFFFFFFFFFFF)
- if initial > 0 {
+ if initial >= 0 {
realInitial = uint64(initial)
}
diff --git a/gocbcore/agentops_crud.go b/gocbcore/agentops_crud.go
index <HASH>..<HASH> 100644
--- a/gocbcore/agentops_crud.go
+++ b/gocbcore/agentops_crud.go
@@ -372,10 +372,20 @@ func (c *Agent) counter(opcode CommandCode, key []byte, delta, initial uint64, e
cb(intVal, Cas(resp.Cas), mutToken, nil)
}
+ // You cannot have an expiry when you do not want to create the document.
+ if initial == uint64(0xFFFFFFFFFFFFFFFF) && expiry != 0 {
+ return nil, ErrInvalidArgs
+ }
+
extraBuf := make([]byte, 20)
binary.BigEndian.PutUint64(extraBuf[0:], delta)
- binary.BigEndian.PutUint64(extraBuf[8:], initial)
- binary.BigEndian.PutUint32(extraBuf[16:], expiry)
+ if initial != uint64(0xFFFFFFFFFFFFFFFF) {
+ binary.BigEndian.PutUint64(extraBuf[8:], initial)
+ binary.BigEndian.PutUint32(extraBuf[16:], expiry)
+ } else {
+ binary.BigEndian.PutUint64(extraBuf[8:], 0x0000000000000000)
+ binary.BigEndian.PutUint32(extraBuf[16:], 0xFFFFFFFF)
+ }
req := &memdQRequest{
memdRequest: memdRequest{
|
GOCBC-<I>: Correctly handle document creation for Counter operations.
This also changes the semantics of the Bucket.Counter operation, in the past
to avoid creating a document if it was missing you would pass an initial of
0, this has been changed to being less than 0 instead. This is a breaking
change for previous versions, but represents an API bug.
Change-Id: Ie0a9a<I>eb6addece6fe6b0f<I>f<I>f3b
Reviewed-on: <URL>
|
couchbase_gocb
|
train
|
1d94134c33f4c9157577174c4a6c0b6250d2e86d
|
diff --git a/glue/ligolw/utils/__init__.py b/glue/ligolw/utils/__init__.py
index <HASH>..<HASH> 100644
--- a/glue/ligolw/utils/__init__.py
+++ b/glue/ligolw/utils/__init__.py
@@ -331,11 +331,11 @@ def load_fileobj(fileobj, gz = None, xmldoc = None, contenthandler = None):
"""
fileobj = MD5File(fileobj)
md5obj = fileobj.md5obj
- if gz != False:
+ if gz or gz is None:
fileobj = RewindableInputFile(fileobj)
magic = fileobj.read(2)
fileobj.seek(0, os.SEEK_SET)
- if gz == True or magic == '\037\213':
+ if gz or magic == '\037\213':
fileobj = gzip.GzipFile(mode = "rb", fileobj = fileobj)
if xmldoc is None:
xmldoc = ligolw.Document()
|
glue.ligolw.utils.load_fileobj(): generalize gz param
- don't require it to be literally one of True or False if not None, but
anything that is logically True or False.
|
gwastro_pycbc-glue
|
train
|
dfc3a535043cc5df989abdb7f35d5d599541bdcc
|
diff --git a/helpers/ContextFormat.php b/helpers/ContextFormat.php
index <HASH>..<HASH> 100644
--- a/helpers/ContextFormat.php
+++ b/helpers/ContextFormat.php
@@ -30,7 +30,7 @@ class ContextFormat
}
if (!empty($context['namespace'])) {
if (\preg_match('/^\\\\?(.*?)\\\\?$/s', $context['namespace'], $ns)) {
- $context['namespace'] = $ns[1].'\\';
+ $context['namespace'] = $ns[1] ? '\\'.$ns[1].'\\' : '\\';
}
} else {
$context['namespace'] = '\\';
diff --git a/tests/CreatorTest.php b/tests/CreatorTest.php
index <HASH>..<HASH> 100644
--- a/tests/CreatorTest.php
+++ b/tests/CreatorTest.php
@@ -24,7 +24,7 @@ class CreatorTest extends \PHPUnit_Framework_TestCase
];
$creator = new Creator($context);
$expected = [
- 'namespace' => 'basens\\',
+ 'namespace' => '\basens\\',
'parent' => null,
'validator' => null,
'classname' => null,
diff --git a/tests/helpers/ContextFormatTest.php b/tests/helpers/ContextFormatTest.php
index <HASH>..<HASH> 100644
--- a/tests/helpers/ContextFormatTest.php
+++ b/tests/helpers/ContextFormatTest.php
@@ -54,7 +54,7 @@ class ContextFormatTest extends \PHPUnit_Framework_TestCase
'classname' => null,
],
[
- 'namespace' => 'my\ns\\',
+ 'namespace' => '\my\ns\\',
'args' => [1, 2],
'append_args' => [],
'use_options' => true,
@@ -72,7 +72,7 @@ class ContextFormatTest extends \PHPUnit_Framework_TestCase
'classname' => null,
],
[
- 'namespace' => 'my\ns\\',
+ 'namespace' => '\my\ns\\',
'args' => [1, 2],
'append_args' => [],
'use_options' => true,
|
Empty namespace represents as '\'
|
axypro_creator
|
train
|
b956ecf5a9c62053a60f210b3ef0ba4b9ff0a8eb
|
diff --git a/addon/helpers/page-title.js b/addon/helpers/page-title.js
index <HASH>..<HASH> 100644
--- a/addon/helpers/page-title.js
+++ b/addon/helpers/page-title.js
@@ -1,7 +1,7 @@
import Ember from 'ember';
const get = Ember.get;
-const { guidFor } = Ember;
+const { guidFor } = Ember
function updateTitle(tokens) {
document.title = tokens.toString();
|
force a build failure through jshint
|
adopted-ember-addons_ember-page-title
|
train
|
a790c1583d1488dd4c16abf4f7a016d579df398e
|
diff --git a/store/mockstore/mocktikv/mock.go b/store/mockstore/mocktikv/mock.go
index <HASH>..<HASH> 100644
--- a/store/mockstore/mocktikv/mock.go
+++ b/store/mockstore/mocktikv/mock.go
@@ -18,8 +18,8 @@ import (
"github.com/pingcap/pd/pd-client"
)
-// NewTestClient creates a TiKV client and PD client from options.
-func NewTestClient(cluster *Cluster, mvccStore MVCCStore, path string) (*RPCClient, pd.Client, error) {
+// NewTiKVAndPDClient creates a TiKV client and PD client from options.
+func NewTiKVAndPDClient(cluster *Cluster, mvccStore MVCCStore, path string) (*RPCClient, pd.Client, error) {
if cluster == nil {
cluster = NewCluster()
BootstrapWithSingleStore(cluster)
diff --git a/store/mockstore/mocktikv/rpc.go b/store/mockstore/mocktikv/rpc.go
index <HASH>..<HASH> 100644
--- a/store/mockstore/mocktikv/rpc.go
+++ b/store/mockstore/mocktikv/rpc.go
@@ -95,6 +95,8 @@ func convertToPbPairs(pairs []Pair) []*kvrpcpb.KvPair {
return kvPairs
}
+// rpcHandler mocks tikv's side handler behavior. In general, you may assume
+// TiKV just translate the logic from Go to Rust.
type rpcHandler struct {
cluster *Cluster
mvccStore MVCCStore
@@ -435,7 +437,8 @@ func (h *rpcHandler) handleSplitRegion(req *kvrpcpb.SplitRegionRequest) *kvrpcpb
return &kvrpcpb.SplitRegionResponse{}
}
-// RPCClient sends kv RPC calls to mock cluster.
+// RPCClient sends kv RPC calls to mock cluster. RPCClient mocks the behavior of
+// a rpc client at tikv's side.
type RPCClient struct {
Cluster *Cluster
MvccStore MVCCStore
diff --git a/store/mockstore/tikv.go b/store/mockstore/tikv.go
index <HASH>..<HASH> 100644
--- a/store/mockstore/tikv.go
+++ b/store/mockstore/tikv.go
@@ -103,7 +103,7 @@ func NewMockTikvStore(options ...MockTiKVStoreOption) (kv.Storage, error) {
f(&opt)
}
- client, pdClient, err := mocktikv.NewTestClient(opt.cluster, opt.mvccStore, opt.path)
+ client, pdClient, err := mocktikv.NewTiKVAndPDClient(opt.cluster, opt.mvccStore, opt.path)
if err != nil {
return nil, errors.Trace(err)
}
diff --git a/store/tikv/delete_range_test.go b/store/tikv/delete_range_test.go
index <HASH>..<HASH> 100644
--- a/store/tikv/delete_range_test.go
+++ b/store/tikv/delete_range_test.go
@@ -34,7 +34,7 @@ var _ = Suite(&testDeleteRangeSuite{})
func (s *testDeleteRangeSuite) SetUpTest(c *C) {
s.cluster = mocktikv.NewCluster()
mocktikv.BootstrapWithMultiRegions(s.cluster, []byte("a"), []byte("b"), []byte("c"))
- client, pdClient, err := mocktikv.NewTestClient(s.cluster, nil, "")
+ client, pdClient, err := mocktikv.NewTiKVAndPDClient(s.cluster, nil, "")
c.Assert(err, IsNil)
store, err := NewTestTiKVStore(client, pdClient, nil, nil, 0)
diff --git a/store/tikv/split_test.go b/store/tikv/split_test.go
index <HASH>..<HASH> 100644
--- a/store/tikv/split_test.go
+++ b/store/tikv/split_test.go
@@ -32,7 +32,7 @@ var _ = Suite(&testSplitSuite{})
func (s *testSplitSuite) SetUpTest(c *C) {
s.cluster = mocktikv.NewCluster()
mocktikv.BootstrapWithSingleStore(s.cluster)
- client, pdClient, err := mocktikv.NewTestClient(s.cluster, nil, "")
+ client, pdClient, err := mocktikv.NewTiKVAndPDClient(s.cluster, nil, "")
c.Assert(err, IsNil)
store, err := NewTestTiKVStore(client, pdClient, nil, nil, 0)
diff --git a/store/tikv/ticlient_test.go b/store/tikv/ticlient_test.go
index <HASH>..<HASH> 100644
--- a/store/tikv/ticlient_test.go
+++ b/store/tikv/ticlient_test.go
@@ -48,7 +48,7 @@ func NewTestStore(c *C) kv.Storage {
return store
}
- client, pdClient, err := mocktikv.NewTestClient(nil, nil, "")
+ client, pdClient, err := mocktikv.NewTiKVAndPDClient(nil, nil, "")
c.Assert(err, IsNil)
store, err := NewTestTiKVStore(client, pdClient, nil, nil, 0)
|
mocktikv: rename NewTestClient to NewTiKVAndPDClient (#<I>)
|
pingcap_tidb
|
train
|
ee6d316fe649d53f92b8a385aa44357b59e903dd
|
diff --git a/src/Patterns.php b/src/Patterns.php
index <HASH>..<HASH> 100644
--- a/src/Patterns.php
+++ b/src/Patterns.php
@@ -23,7 +23,7 @@ class Patterns
const MATCH_STYLE_INLINE = '!(<[^>]* style=")(.*?)(")!is';
// @codingStandardsIgnoreStart
const MATCH_JSCRIPT = '!(<script>|<script[^>]*type="text/javascript"[^>]*>|<script[^>]*type=\'text/javascript\'[^>]*>)(.*?)(</script>)!is';
- const MATCH_LD_JSON = '!(<script[^>]*type="application/ld+json"[^>]*>|<script[^>]*type=\'application/ld+json\'[^>]*>)(.*?)(</script>)!is';
+ const MATCH_LD_JSON = '!(<script[^>]*type="application/ld\+json"[^>]*>|<script[^>]*type=\'application/ld\+json\'[^>]*>)(.*?)(</script>)!is';
// @codingStandardsIgnoreEnd
const MATCH_SCRIPT = '!(<script[^>]*>?)(.*?)(</script>)!is';
const MATCH_NOCOMPRESS = '!(<nocompress>)(.*?)(</nocompress>)!is';
|
Fixed ld+json matching missing an escape for +
|
WyriHaximus_HtmlCompress
|
train
|
ebbc9d5f6771e9b1392dfad6b387432f643e75de
|
diff --git a/lib/datasource/npm.js b/lib/datasource/npm.js
index <HASH>..<HASH> 100644
--- a/lib/datasource/npm.js
+++ b/lib/datasource/npm.js
@@ -109,7 +109,9 @@ async function getPkgReleases(input, config) {
}
const purl = input;
const res = await getDependency(purl.fullname, retries);
- delete res['renovate-config'];
+ if (res) {
+ delete res['renovate-config'];
+ }
return res;
}
|
fix(npm): add check before massaging response
|
renovatebot_renovate
|
train
|
c63737ec2ed54c438dfc0280d9ba59830127e2b6
|
diff --git a/graphenebase/account.py b/graphenebase/account.py
index <HASH>..<HASH> 100644
--- a/graphenebase/account.py
+++ b/graphenebase/account.py
@@ -99,6 +99,12 @@ class BrainKey(object):
s = hashlib.sha256(hashlib.sha512(a).digest()).digest()
return PrivateKey(hexlify(s).decode('ascii'))
+ def get_blind_private(self):
+ """ Derive private key from the brain key (and no sequence number)
+ """
+ a = _bytes(self.brainkey)
+ return PrivateKey(hashlib.sha256(a).hexdigest())
+
def get_public(self):
return self.get_private().pubkey
diff --git a/tests/test_account.py b/tests/test_account.py
index <HASH>..<HASH> 100644
--- a/tests/test_account.py
+++ b/tests/test_account.py
@@ -218,6 +218,12 @@ class Testcases(unittest.TestCase):
p = b.next_sequence().get_private()
self.assertEqual(str(p), i)
+ def test_BrainKey_blind(self):
+ b = BrainKey("MATZO COLORER BICORN KASBEKE FAERIE LOCHIA GOMUTI SOVKHOZ Y GERMAL AUNTIE PERFUMY TIME FEATURE GANGAN CELEMIN")
+ key = "5JmdAQbRpV94LDVb2igq6YR5MVj1NVaJxBWpHP9Y6LspmMobbv5"
+ p = b.get_blind_private()
+ self.assertEqual(str(p), key)
+
def test_PasswordKey(self):
a = ["Aang7foN3oz1Ungai2qua5toh3map8ladei1eem2ohsh2shuo8aeji9Thoseo7ah",
"iep1Mees9eghiifahwei5iidi0Sazae9aigaeT7itho3quoo2dah5zuvobaelau5",
|
Add get_blind_private method to BrainKey.
This is the same as `get_private` method, but without any
sequence number. It's used for generating private keys for
Blind accounts.
|
xeroc_python-graphenelib
|
train
|
e576844f0f0c797c5e962e7d4a54395eed72abbe
|
diff --git a/cmd/admin-speedtest.go b/cmd/admin-speedtest.go
index <HASH>..<HASH> 100644
--- a/cmd/admin-speedtest.go
+++ b/cmd/admin-speedtest.go
@@ -28,6 +28,7 @@ import (
json "github.com/minio/colorjson"
"github.com/minio/madmin-go"
"github.com/minio/mc/pkg/probe"
+ "github.com/minio/pkg/console"
)
var adminSpeedtestFlags = []cli.Flag{
@@ -193,7 +194,8 @@ func mainAdminSpeedtest(ctx *cli.Context) error {
}
if !globalJSON {
s.Stop()
- fmt.Printf("\n\n")
+ console.RewindLines(1)
+ console.Println()
}
printMsg(speedTestResult(result))
}
|
Erase the spinner on speedtest completion (#<I>)
|
minio_mc
|
train
|
0d8c652ab2575e0698603662779129ab97201119
|
diff --git a/test/test_helper.rb b/test/test_helper.rb
index <HASH>..<HASH> 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -1,5 +1,2 @@
require "minitest/autorun"
require "eefgilm"
-require "pry"
-require "pry-nav"
-
|
Remove Pry and Pry-Nav from Test Helper
|
enilsen16_Eefgilm
|
train
|
53b9e72838b352f2290b51f354e7f1532b98b17b
|
diff --git a/test/test_LensModel/test_Profiles/test_gauss_decomposition.py b/test/test_LensModel/test_Profiles/test_gauss_decomposition.py
index <HASH>..<HASH> 100644
--- a/test/test_LensModel/test_Profiles/test_gauss_decomposition.py
+++ b/test/test_LensModel/test_Profiles/test_gauss_decomposition.py
@@ -251,7 +251,7 @@ class TestCTNFWGaussDec(object):
r_trunc = 10.
a = 2
- r = np.linspace(1, 2, 100)
+ r = np.logspace(-1, 1, 1000) * r_s
beta = r_core / r_s
tau = r_trunc / r_s
|
Fix competing postprocessing for dyPolychord MPI run
|
sibirrer_lenstronomy
|
train
|
7d0733ad1026e8d251e90d82aa4a3afdafbd51b5
|
diff --git a/tests/test_cloudformation/test_cloudformation_stack_crud_boto3.py b/tests/test_cloudformation/test_cloudformation_stack_crud_boto3.py
index <HASH>..<HASH> 100644
--- a/tests/test_cloudformation/test_cloudformation_stack_crud_boto3.py
+++ b/tests/test_cloudformation/test_cloudformation_stack_crud_boto3.py
@@ -160,7 +160,7 @@ def test_boto3_create_stack():
TemplateBody=dummy_template_json,
)
- cf_conn.get_template(StackName="test_stack")['TemplateBody'].should.equal(
+ json.loads(json.dumps(cf_conn.get_template(StackName="test_stack")['TemplateBody'])).should.equal(
dummy_template)
@@ -270,9 +270,10 @@ def test_create_stack_from_s3_url():
StackName='stack_from_url',
TemplateURL=key_url,
)
-
- cf_conn.get_template(StackName="stack_from_url")[
- 'TemplateBody'].should.equal(dummy_template)
+ # from IPython import embed
+ # embed()
+ json.loads(json.dumps(cf_conn.get_template(StackName="stack_from_url")[
+ 'TemplateBody'])).should.equal(dummy_template)
@mock_cloudformation
@@ -306,8 +307,8 @@ def test_update_stack_from_s3_url():
TemplateURL=key_url,
)
- cf_conn.get_template(StackName="update_stack_from_url")[
- 'TemplateBody'].should.equal(dummy_update_template)
+ json.loads(json.dumps(cf_conn.get_template(StackName="update_stack_from_url")[
+ 'TemplateBody'])).should.equal(dummy_update_template)
@mock_cloudformation
|
hack tests now that boto get_templates returns ordered dicts
|
spulec_moto
|
train
|
bd5f1bfdfc4bcf1097b5a9be7635e85d66f4ea4d
|
diff --git a/create-ava-rule.js b/create-ava-rule.js
index <HASH>..<HASH> 100644
--- a/create-ava-rule.js
+++ b/create-ava-rule.js
@@ -102,6 +102,12 @@ module.exports = function createAvaRule() {
hasTestModifier: function (mod) {
return hasTestModifier(currentTestNode, mod);
},
+ hasHookModifier: function () {
+ return hasTestModifier(currentTestNode, 'before') ||
+ hasTestModifier(currentTestNode, 'beforeEach') ||
+ hasTestModifier(currentTestNode, 'after') ||
+ hasTestModifier(currentTestNode, 'afterEach');
+ },
merge: function (customHandlers) {
Object.keys(predefinedRules).forEach(function (key) {
var predef = predefinedRules[key];
diff --git a/rules/no-identical-title.js b/rules/no-identical-title.js
index <HASH>..<HASH> 100644
--- a/rules/no-identical-title.js
+++ b/rules/no-identical-title.js
@@ -33,7 +33,7 @@ module.exports = function (context) {
return ava.merge({
CallExpression: function (node) {
- if (!ava.isTestFile || ava.currentTestNode !== node) {
+ if (!ava.isTestFile || ava.currentTestNode !== node || ava.hasHookModifier()) {
return;
}
diff --git a/rules/test-title.js b/rules/test-title.js
index <HASH>..<HASH> 100644
--- a/rules/test-title.js
+++ b/rules/test-title.js
@@ -9,7 +9,7 @@ module.exports = function (context) {
return ava.merge({
CallExpression: function (node) {
- if (!ava.isTestFile || ava.currentTestNode !== node) {
+ if (!ava.isTestFile || ava.currentTestNode !== node || ava.hasHookModifier()) {
return;
}
diff --git a/test/no-identical-title.js b/test/no-identical-title.js
index <HASH>..<HASH> 100644
--- a/test/no-identical-title.js
+++ b/test/no-identical-title.js
@@ -24,6 +24,11 @@ test(() => {
header + 'const name = "foo"; test(name + " 1", t => {}); test(name + " 1", t => {});',
header + 'test("a", t => {}); notTest("a", t => {});',
header + 'notTest("a", t => {}); notTest("a", t => {});',
+ header + 'test.before(t => {}); test.before(t => {});',
+ header + 'test.after(t => {}); test.after(t => {});',
+ header + 'test.beforeEach(t => {}); test.beforeEach(t => {});',
+ header + 'test.afterEach(t => {}); test.afterEach(t => {});',
+ header + 'test.cb.before(t => {}); test.before.cb(t => {});',
// shouldn't be triggered since it's not a test file
'test(t => {}); test(t => {});',
'test("a", t => {}); test("a", t => {});'
diff --git a/test/test-title.js b/test/test-title.js
index <HASH>..<HASH> 100644
--- a/test/test-title.js
+++ b/test/test-title.js
@@ -19,6 +19,11 @@ test(() => {
header + 'test(\'my test name\', t => { t.pass(); t.end(); });',
header + 'test.cb("my test name", t => { t.pass(); t.end(); });',
header + 'test.todo("my test name");',
+ header + 'test.before(t => {});',
+ header + 'test.after(t => {});',
+ header + 'test.beforeEach(t => {});',
+ header + 'test.afterEach(t => {});',
+ header + 'test.cb.before(t => {}); test.before.cb(t => {});',
{
code: header + 'test(t => { t.pass(); t.end(); });',
options: ['if-multiple']
|
Do not enforce a title on hooks (fixes #<I>)
|
avajs_eslint-plugin-ava
|
train
|
e062ce6ccb6a726ff1b3dd52211c32ebdd57e99b
|
diff --git a/tests/test_bugs.py b/tests/test_bugs.py
index <HASH>..<HASH> 100644
--- a/tests/test_bugs.py
+++ b/tests/test_bugs.py
@@ -24,7 +24,7 @@ class Test_VariantMapper(unittest.TestCase):
self.hm = hgvs.variantmapper.VariantMapper(self.hdp)
self.hp = hgvs.parser.Parser()
self.evm = hgvs.variantmapper.EasyVariantMapper(self.hdp,
- replace_reference=True, primary_assembly='GRCh37',
+ replace_reference=True, assembly_name='GRCh37',
alt_aln_method='splign')
self.vn = hgvs.normalizer.Normalizer(self.hdp, shuffle_direction=3, cross_boundaries=True)
|
adapted test_bugs to new assembly_name argument
|
biocommons_hgvs
|
train
|
9d3022946aacea7cabca4d093046b289b1b70f5d
|
diff --git a/src/java/azkaban/webapp/servlet/ProjectManagerServlet.java b/src/java/azkaban/webapp/servlet/ProjectManagerServlet.java
index <HASH>..<HASH> 100644
--- a/src/java/azkaban/webapp/servlet/ProjectManagerServlet.java
+++ b/src/java/azkaban/webapp/servlet/ProjectManagerServlet.java
@@ -1068,12 +1068,14 @@ public class ProjectManagerServlet extends LoginAbstractAzkabanServlet {
String type = null;
final String contentType = item.getContentType();
- if(contentType.startsWith("application/zip")) {
+ if(contentType != null && (contentType.startsWith("application/zip") || contentType.startsWith("application/x-zip-compressed"))) {
type = "zip";
}
else {
item.delete();
setErrorMessageInCookie(resp, "File type " + contentType + " unrecognized.");
+
+ return;
}
File tempDir = Utils.createTempDir();
|
Adding x-zip-compressed as mime type on upload, and return on error.
|
azkaban_azkaban
|
train
|
95166d44eac63a8d1b2a24c3daa491ff20af04b0
|
diff --git a/tests/unit_tests/crud/test_crud_actions.py b/tests/unit_tests/crud/test_crud_actions.py
index <HASH>..<HASH> 100644
--- a/tests/unit_tests/crud/test_crud_actions.py
+++ b/tests/unit_tests/crud/test_crud_actions.py
@@ -3,7 +3,7 @@ import unittest
from rip.crud.crud_actions import CrudActions
-class TestSomething(unittest.TestCase):
+class TestResolveAction(unittest.TestCase):
def test_should_resolve_read_detail(self):
assert CrudActions.resolve_action(
'read_detail') == CrudActions.READ_DETAIL
@@ -26,4 +26,17 @@ class TestSomething(unittest.TestCase):
def test_should_get_aggregates(self):
assert CrudActions.resolve_action(
- 'get_aggregates') == CrudActions.GET_AGGREGATES
\ No newline at end of file
+ 'get_aggregates') == CrudActions.GET_AGGREGATES
+
+
+class TestAllActions(unittest.TestCase):
+ def test_should_get_all_actions(self):
+ all_actions = CrudActions.get_all_actions()
+
+ assert len(all_actions) == 6
+ assert CrudActions.READ_DETAIL in all_actions
+ assert CrudActions.READ_LIST in all_actions
+ assert CrudActions.CREATE_DETAIL in all_actions
+ assert CrudActions.UPDATE_DETAIL in all_actions
+ assert CrudActions.DELETE_DETAIL in all_actions
+ assert CrudActions.GET_AGGREGATES in all_actions
\ No newline at end of file
|
Add Tests for CrudActions.get_all_actions
|
Aplopio_django_rip
|
train
|
f98ab911eeaeb5dcdcf96527c534e49a4970c3d5
|
diff --git a/sass_processor/processor.py b/sass_processor/processor.py
index <HASH>..<HASH> 100644
--- a/sass_processor/processor.py
+++ b/sass_processor/processor.py
@@ -65,7 +65,8 @@ class SassProcessor(object):
if not self.processor_enabled:
return css_filename
sourcemap_filename = css_filename + '.map'
- if find_file(css_filename) and self.is_latest(sourcemap_filename, filename):
+ base = os.path.dirname(filename)
+ if find_file(css_filename) and self.is_latest(sourcemap_filename, base):
return css_filename
# with offline compilation, raise an error, if css file could not be found.
@@ -120,7 +121,7 @@ class SassProcessor(object):
_, ext = os.path.splitext(self.resolve_path())
return ext in self.sass_extensions
- def is_latest(self, sourcemap_filename, filename):
+ def is_latest(self, sourcemap_filename, base):
sourcemap_file = find_file(sourcemap_filename)
if not sourcemap_file or not os.path.isfile(sourcemap_file):
return False
@@ -128,7 +129,7 @@ class SassProcessor(object):
with open(sourcemap_file, 'r') as fp:
sourcemap = json.load(fp)
for srcfilename in sourcemap.get('sources'):
- srcfilename = os.path.join(os.path.dirname(filename), srcfilename)
+ srcfilename = os.path.join(base, srcfilename)
if not os.path.isfile(srcfilename) or os.stat(srcfilename).st_mtime > sourcemap_mtime:
# at least one of the source is younger that the sourcemap referring it
return False
|
pass base folder to is_latest
|
jrief_django-sass-processor
|
train
|
2c289559a5533ac567fd95a655e56d1c4d787fd2
|
diff --git a/lib/ronin/ui/cli/command.rb b/lib/ronin/ui/cli/command.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/ui/cli/command.rb
+++ b/lib/ronin/ui/cli/command.rb
@@ -263,7 +263,10 @@ module Ronin
setup
execute
+
return true
+ ensure
+ cleanup
end
#
@@ -293,6 +296,16 @@ module Ronin
def execute
end
+ #
+ # Default method to call after the command has finished.
+ #
+ # @since 1.5.0
+ #
+ # @api semipublic
+ #
+ def cleanup
+ end
+
protected
#
|
Added UI::CLI::Command#cleanup.
|
ronin-ruby_ronin
|
train
|
e6242af0587955ca94be36f5374bc2595b9deaff
|
diff --git a/closure/goog/iter/iter.js b/closure/goog/iter/iter.js
index <HASH>..<HASH> 100644
--- a/closure/goog/iter/iter.js
+++ b/closure/goog/iter/iter.js
@@ -189,12 +189,12 @@ goog.iter.forEach = function(iterable, f, opt_obj) {
* passed the test are present.
*/
goog.iter.filter = function(iterable, f, opt_obj) {
- iterable = goog.iter.toIterator(iterable);
+ var iterator = goog.iter.toIterator(iterable);
var newIter = new goog.iter.Iterator;
newIter.next = function() {
while (true) {
- var val = iterable.next();
- if (f.call(opt_obj, val, undefined, iterable)) {
+ var val = iterator.next();
+ if (f.call(opt_obj, val, undefined, iterator)) {
return val;
}
}
@@ -271,12 +271,12 @@ goog.iter.join = function(iterable, deliminator) {
* applying the function to each element in the original iterator.
*/
goog.iter.map = function(iterable, f, opt_obj) {
- iterable = goog.iter.toIterator(iterable);
+ var iterator = goog.iter.toIterator(iterable);
var newIter = new goog.iter.Iterator;
newIter.next = function() {
while (true) {
- var val = iterable.next();
- return f.call(opt_obj, val, undefined, iterable);
+ var val = iterator.next();
+ return f.call(opt_obj, val, undefined, iterator);
}
};
return newIter;
@@ -422,13 +422,13 @@ goog.iter.chain = function(var_args) {
* original iterator as long as {@code f} is true.
*/
goog.iter.dropWhile = function(iterable, f, opt_obj) {
- iterable = goog.iter.toIterator(iterable);
+ var iterator = goog.iter.toIterator(iterable);
var newIter = new goog.iter.Iterator;
var dropping = true;
newIter.next = function() {
while (true) {
- var val = iterable.next();
- if (dropping && f.call(opt_obj, val, undefined, iterable)) {
+ var val = iterator.next();
+ if (dropping && f.call(opt_obj, val, undefined, iterator)) {
continue;
} else {
dropping = false;
@@ -452,14 +452,14 @@ goog.iter.dropWhile = function(iterable, f, opt_obj) {
* original iterator as long as the function is true.
*/
goog.iter.takeWhile = function(iterable, f, opt_obj) {
- iterable = goog.iter.toIterator(iterable);
+ var iterator = goog.iter.toIterator(iterable);
var newIter = new goog.iter.Iterator;
var taking = true;
newIter.next = function() {
while (true) {
if (taking) {
- var val = iterable.next();
- if (f.call(opt_obj, val, undefined, iterable)) {
+ var val = iterator.next();
+ if (f.call(opt_obj, val, undefined, iterator)) {
return val;
} else {
taking = false;
|
When 'iterable' variable has its type re-defined, JsCompiler
doesn't seem to catch the type redefinition when the variable
is used from within a closure.
R=johnlenz
DELTA=<I> (0 added, 0 deleted, <I> changed)
Revision created by MOE tool push_codebase.
MOE_MIGRATION=<I>
git-svn-id: <URL>
|
google_closure-library
|
train
|
a27ce4d56a51b6570bd2447c59fa802bfddd2d37
|
diff --git a/tests/test_sklearn.py b/tests/test_sklearn.py
index <HASH>..<HASH> 100644
--- a/tests/test_sklearn.py
+++ b/tests/test_sklearn.py
@@ -3,7 +3,7 @@ from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import ElasticNet
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import make_regression, make_hastie_10_2
-from keras.layers import Dense, Flatten
+from keras.layers import Dense, Flatten, Reshape
from keras.models import Sequential
from keras import backend as K
from wandb.keras import WandbCallback
diff --git a/wandb/meta.py b/wandb/meta.py
index <HASH>..<HASH> 100644
--- a/wandb/meta.py
+++ b/wandb/meta.py
@@ -60,6 +60,9 @@ class Meta(object):
logger.debug("save program starting: {}".format(program))
if os.path.exists(program):
relative_path = os.path.relpath(program, start=self.data["root"])
+ # Ignore paths outside of out_dir when using custom dir
+ if "../" in relative_path:
+ relative_path = os.path.basename(relative_path)
util.mkdir_exists_ok(os.path.join(self.out_dir, "code", os.path.dirname(relative_path)))
saved_program = os.path.join(self.out_dir, "code", relative_path)
logger.debug("save program saved: {}".format(saved_program))
diff --git a/wandb/sklearn/__init__.py b/wandb/sklearn/__init__.py
index <HASH>..<HASH> 100644
--- a/wandb/sklearn/__init__.py
+++ b/wandb/sklearn/__init__.py
@@ -489,9 +489,9 @@ def plot_feature_importances(model=None, feature_names=None,
if result == '':
result = attributes_to_check[index]
else:
- result = f'{result}, {attributes_to_check[index]}'
+ result = ", ".join([result, attributes_to_check[index]])
- return f'{result} or {attributes_to_check[-1]}'
+ return " or ".join([result, attributes_to_check[-1]])
def check_for_attribute_on(model):
for each in attributes_to_check:
@@ -501,7 +501,7 @@ def plot_feature_importances(model=None, feature_names=None,
found_attribute = check_for_attribute_on(model)
if found_attribute is None:
- wandb.termwarn(f"{get_attributes_as_formatted_string()} attribute not in classifier. Cannot plot feature importances.")
+ wandb.termwarn("%s attribute not in classifier. Cannot plot feature importances." % get_attributes_as_formatted_string())
return
if (test_missing(model=model) and test_types(model=model) and
|
Better code saving logic (#<I>)
* Better code saving logic
* Remove f strings
* Fix tests for good
|
wandb_client
|
train
|
2d2524546f4c4d8a28e30c373dc36fe6b9e9c5e1
|
diff --git a/core/bases.py b/core/bases.py
index <HASH>..<HASH> 100644
--- a/core/bases.py
+++ b/core/bases.py
@@ -55,6 +55,16 @@ class BaseSample(BaseObject):
else:
self.meta = None
+ # ----------------------
+ # Methods of exposing underlying data
+ # ----------------------
+ def __contains__(self, key):
+ return self.data.__contains__(key)
+
+ def __getitem__(self, key):
+ return self.data.__getitem__(key)
+
+ # ----------------------
def read_data(self, **kwargs):
'''
This function should be overwritten for each
|
exposed a bit of underlying data
|
eyurtsev_FlowCytometryTools
|
train
|
86d7a21823732edc50e69f3e64fdae29f4bfb61d
|
diff --git a/spyder/utils/encoding.py b/spyder/utils/encoding.py
index <HASH>..<HASH> 100644
--- a/spyder/utils/encoding.py
+++ b/spyder/utils/encoding.py
@@ -107,12 +107,18 @@ def get_coding(text):
@return coding string
"""
for line in text.splitlines()[:2]:
- result = CODING_RE.search(to_text_string(line))
- if result:
- codec = result.group(1)
- # sometimes we find a false encoding that can result in errors
- if codec in CODECS:
- return codec
+ try:
+ result = CODING_RE.search(to_text_string(line))
+ except UnicodeDecodeError:
+ # This could fail because to_text_string assume the text is utf8-like
+ # and we don't know the encoding to give it to to_text_string
+ pass
+ else:
+ if result:
+ codec = result.group(1)
+ # sometimes we find a false encoding that can result in errors
+ if codec in CODECS:
+ return codec
# Fallback using chardet
if is_binary_string(text):
|
Fix errors with get_coding and no-uft-8 files
|
spyder-ide_spyder
|
train
|
cf46c58546c722bcaa9a17b8e06d7a580510609a
|
diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/deserialization/gson/CalendarDeserializer.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/deserialization/gson/CalendarDeserializer.java
index <HASH>..<HASH> 100644
--- a/vraptor-core/src/main/java/br/com/caelum/vraptor/deserialization/gson/CalendarDeserializer.java
+++ b/vraptor-core/src/main/java/br/com/caelum/vraptor/deserialization/gson/CalendarDeserializer.java
@@ -6,9 +6,6 @@ import java.util.Calendar;
import javax.enterprise.context.Dependent;
import javax.xml.bind.DatatypeConverter;
-import br.com.caelum.vraptor.serialization.gson.RegisterStrategy;
-import br.com.caelum.vraptor.serialization.gson.RegisterType;
-
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
@@ -22,7 +19,6 @@ import com.google.gson.JsonParseException;
* @since 4.0.0
*/
@Dependent
-@RegisterStrategy(RegisterType.SINGLE)
public class CalendarDeserializer implements JsonDeserializer<Calendar> {
@Override
diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/serialization/gson/CalendarSerializer.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/serialization/gson/CalendarSerializer.java
index <HASH>..<HASH> 100644
--- a/vraptor-core/src/main/java/br/com/caelum/vraptor/serialization/gson/CalendarSerializer.java
+++ b/vraptor-core/src/main/java/br/com/caelum/vraptor/serialization/gson/CalendarSerializer.java
@@ -35,7 +35,6 @@ import com.google.gson.JsonSerializer;
* @since 4.0.0
*/
@Dependent
-@RegisterStrategy(RegisterType.SINGLE)
public class CalendarSerializer implements JsonSerializer<Calendar> {
@Override
|
Oops! Reverting register strategy for Calendar to Inheritance because
GregorianCalendar extends Calendar
|
caelum_vraptor4
|
train
|
79de0aae708409af15c338507c6008812ad4180e
|
diff --git a/src/test/java/org/jenetics/Integer64GeneTest.java b/src/test/java/org/jenetics/Integer64GeneTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/jenetics/Integer64GeneTest.java
+++ b/src/test/java/org/jenetics/Integer64GeneTest.java
@@ -23,9 +23,14 @@
package org.jenetics;
import java.io.IOException;
+import java.util.Random;
+import javolution.context.LocalContext;
import javolution.xml.stream.XMLStreamException;
+import org.jenetics.util.Accumulators;
+import org.jenetics.util.Factory;
+import org.jenetics.util.RandomRegistry;
import org.jscience.mathematics.number.Integer64;
import org.testng.Assert;
import org.testng.annotations.Test;
@@ -37,6 +42,43 @@ import org.testng.annotations.Test;
public class Integer64GeneTest {
@Test
+ public void newInstance() {
+ LocalContext.enter();
+ try {
+ RandomRegistry.setRandom(new Random());
+
+ final Integer64 min = Integer64.ZERO;
+ final Integer64 max = Integer64.valueOf(Integer.MAX_VALUE - 1);
+ final Factory<Integer64Gene> factory = Integer64Gene.valueOf(min, max);
+
+ final Accumulators.Variance<Integer64> variance = new Accumulators.Variance<Integer64>();
+
+ final int samples = 50000;
+ for (int i = 0; i < samples; ++i) {
+ final Integer64Gene g1 = factory.newInstance();
+ final Integer64Gene g2 = factory.newInstance();
+
+ Assert.assertTrue(g1.getAllele().compareTo(min) >= 0);
+ Assert.assertTrue(g1.getAllele().compareTo(max) <= 0);
+ Assert.assertTrue(g2.getAllele().compareTo(min) >= 0);
+ Assert.assertTrue(g2.getAllele().compareTo(max) <= 0);
+ Assert.assertFalse(g1.equals(g2));
+ Assert.assertNotSame(g1, g2);
+
+ variance.accumulate(g1.getAllele());
+ variance.accumulate(g2.getAllele());
+ }
+
+ System.out.println(variance);
+ Assert.assertEquals(2*samples, variance.getSamples());
+ Assert.assertEquals(variance.getMean(), Integer.MAX_VALUE/2, 100000000);
+ Assert.assertEquals(variance.getVariance(), 3.88E17, 1.0E16);
+ } finally {
+ LocalContext.exit();
+ }
+ }
+
+ @Test
public void xmlSerialize() throws XMLStreamException {
SerializeUtils.testXMLSerialization(Integer64Gene.valueOf(5, 0, 10));
SerializeUtils.testXMLSerialization(Integer64Gene.valueOf(5, Integer.MIN_VALUE, Integer.MAX_VALUE));
|
Add test for Integer<I>Gene factory method 'newInstance'.
|
jenetics_jenetics
|
train
|
53a25d5428fc75b09c36372330c01b0332fd94b1
|
diff --git a/tests/FpdfTest.php b/tests/FpdfTest.php
index <HASH>..<HASH> 100644
--- a/tests/FpdfTest.php
+++ b/tests/FpdfTest.php
@@ -1,4 +1,6 @@
-<?php declare(strict_types=1);
+<?php
+
+declare(strict_types=1);
namespace Codedge\Fpdf\Test;
diff --git a/tests/TestCase.php b/tests/TestCase.php
index <HASH>..<HASH> 100644
--- a/tests/TestCase.php
+++ b/tests/TestCase.php
@@ -1,4 +1,6 @@
-<?php declare(strict_types=1);
+<?php
+
+declare(strict_types=1);
namespace Codedge\Fpdf\Test;
|
Apply fixes from StyleCI (#<I>)
|
codedge_laravel-fpdf
|
train
|
08b66a13a1db65097c36cee73efc339a30ee20c1
|
diff --git a/lib/libPDF.php b/lib/libPDF.php
index <HASH>..<HASH> 100644
--- a/lib/libPDF.php
+++ b/lib/libPDF.php
@@ -222,7 +222,7 @@ class libPDF extends FPDF implements libPDFInterface {
$doc->loadXML("<root/>");
- $html = preg_replace("/&(?![a-z\d]+|#\d+|#x[a-f\d]+);/i", "&", $html);
+ $html = preg_replace("/&(?!([a-z\d]+|#\d+|#x[a-f\d]+);)/i", "&", $html);
$f = $doc->createDocumentFragment();
if( !$f->appendXML($html) )
|
Fix HTMLText()'s entity detection not working all the time
|
SkUrRiEr_pdflib
|
train
|
74ebad40118826c7d8964c03b7c59a6861552acb
|
diff --git a/lib/active_scaffold/helpers/human_condition_helpers.rb b/lib/active_scaffold/helpers/human_condition_helpers.rb
index <HASH>..<HASH> 100644
--- a/lib/active_scaffold/helpers/human_condition_helpers.rb
+++ b/lib/active_scaffold/helpers/human_condition_helpers.rb
@@ -26,7 +26,7 @@ module ActiveScaffold
when :select, :multi_select, :record_select
associated = value
associated = [associated].compact unless associated.is_a? Array
- associated = column.association.klass.find(associated.map(&:to_i)).collect(&:to_label) if column.association
+ associated = column.association.klass.where(["id in (?)", associated.map(&:to_i)]).collect(&:to_label) if column.association
"#{column.active_record_class.human_attribute_name(column.name)} = #{associated.join(', ')}"
when :boolean, :checkbox
label = column.column.type_cast(value) ? as_(:true) : as_(:false)
|
avoid record not found exception for human conditions
|
activescaffold_active_scaffold
|
train
|
e57068451db525de56c75c1825e8d622f5a87fa7
|
diff --git a/core/src/main/java/com/google/bitcoin/core/Wallet.java b/core/src/main/java/com/google/bitcoin/core/Wallet.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/google/bitcoin/core/Wallet.java
+++ b/core/src/main/java/com/google/bitcoin/core/Wallet.java
@@ -245,20 +245,7 @@ public class Wallet implements Serializable, BlockChainListener {
for (TransactionOutput output : sortedOutputs) {
if (total >= target) break;
// Only pick chain-included transactions, or transactions that are ours and pending.
- TransactionConfidence confidence = output.parentTransaction.getConfidence();
- ConfidenceType type = confidence.getConfidenceType();
- boolean pending = type.equals(ConfidenceType.NOT_SEEN_IN_CHAIN) ||
- type.equals(ConfidenceType.NOT_IN_BEST_CHAIN);
- boolean confirmed = type.equals(ConfidenceType.BUILDING);
- if (!confirmed) {
- // If the transaction is still pending ...
- if (!pending) continue;
- // And it was created by us ...
- if (!confidence.getSource().equals(TransactionConfidence.Source.SELF)) continue;
- // And it's been seen by the network and propagated ...
- if (confidence.numBroadcastPeers() <= 1) continue;
- // Then it's OK to select.
- }
+ if (!isSelectable(output)) continue;
selected.add(output);
total += output.getValue().longValue();
}
@@ -266,6 +253,25 @@ public class Wallet implements Serializable, BlockChainListener {
// transaction.
return new CoinSelection(BigInteger.valueOf(total), selected);
}
+
+ public static boolean isSelectable(TransactionOutput output) {
+ // Only pick chain-included transactions, or transactions that are ours and pending.
+ TransactionConfidence confidence = output.parentTransaction.getConfidence();
+ ConfidenceType type = confidence.getConfidenceType();
+ boolean pending = type.equals(ConfidenceType.NOT_SEEN_IN_CHAIN) ||
+ type.equals(ConfidenceType.NOT_IN_BEST_CHAIN);
+ boolean confirmed = type.equals(ConfidenceType.BUILDING);
+ if (!confirmed) {
+ // If the transaction is still pending ...
+ if (!pending) return false;
+ // And it was created by us ...
+ if (!confidence.getSource().equals(TransactionConfidence.Source.SELF)) return false;
+ // And it's been seen by the network and propagated ...
+ if (confidence.numBroadcastPeers() <= 1) return false;
+ // Then it's OK to select.
+ }
+ return true;
+ }
}
private transient CoinSelector coinSelector = new DefaultCoinSelector();
@@ -570,7 +576,6 @@ public class Wallet implements Serializable, BlockChainListener {
* @param delayTime How many time units to wait until saving the wallet on a background thread.
* @param timeUnit the unit of measurement for delayTime.
* @param eventListener callback to be informed when the auto-save thread does things, or null
- * @throws IOException
*/
public synchronized void autosaveToFile(File f, long delayTime, TimeUnit timeUnit,
AutosaveEventListener eventListener) {
|
Split some selection logic into a static method of DefaultCoinSelector. Resolves issue <I>.
|
bitcoinj_bitcoinj
|
train
|
54809a701b9cc0306f7277efd3767b02e71be2e5
|
diff --git a/py/BUILD.bazel b/py/BUILD.bazel
index <HASH>..<HASH> 100644
--- a/py/BUILD.bazel
+++ b/py/BUILD.bazel
@@ -15,7 +15,7 @@ compile_pip_requirements(
requirements_txt = ":requirements_lock.txt",
)
-SE_VERSION = "4.4.1"
+SE_VERSION = "4.4.2"
BROWSER_VERSIONS = [
"v85",
@@ -170,6 +170,7 @@ py_wheel(
"urllib3[socks]~=1.26",
"trio~=0.17",
"trio-websocket~=0.9",
+ "certifi~=2021.10.8",
],
strip_path_prefixes = [
"py/",
diff --git a/py/selenium/__init__.py b/py/selenium/__init__.py
index <HASH>..<HASH> 100644
--- a/py/selenium/__init__.py
+++ b/py/selenium/__init__.py
@@ -16,4 +16,4 @@
# under the License.
-__version__ = "4.4.1"
+__version__ = "4.4.2"
diff --git a/py/selenium/webdriver/__init__.py b/py/selenium/webdriver/__init__.py
index <HASH>..<HASH> 100644
--- a/py/selenium/webdriver/__init__.py
+++ b/py/selenium/webdriver/__init__.py
@@ -36,7 +36,7 @@ from .common.action_chains import ActionChains # noqa
from .common.proxy import Proxy # noqa
from .common.keys import Keys # noqa
-__version__ = '4.4.1'
+__version__ = '4.4.2'
# We need an explicit __all__ because the above won't otherwise be exported.
__all__ = [
diff --git a/py/setup.py b/py/setup.py
index <HASH>..<HASH> 100755
--- a/py/setup.py
+++ b/py/setup.py
@@ -27,7 +27,7 @@ for scheme in INSTALL_SCHEMES.values():
setup_args = {
'cmdclass': {'install': install},
'name': 'selenium',
- 'version': "4.4.1",
+ 'version': "4.4.2",
'license': 'Apache 2.0',
'description': 'Python bindings for Selenium',
'long_description': open(join(abspath(dirname(__file__)), "README.rst")).read(),
|
[py] Bump Python Bindings to <I>
|
SeleniumHQ_selenium
|
train
|
c18b393ce9def3d6125e5cccba774da14f37f2d0
|
diff --git a/cmd/juju/status/output_tabular.go b/cmd/juju/status/output_tabular.go
index <HASH>..<HASH> 100644
--- a/cmd/juju/status/output_tabular.go
+++ b/cmd/juju/status/output_tabular.go
@@ -16,6 +16,7 @@ import (
"github.com/juju/charm/v9/hooks"
"github.com/juju/errors"
"github.com/juju/naturalsort"
+ "github.com/juju/version/v2"
cmdcrossmodel "github.com/juju/juju/cmd/juju/crossmodel"
"github.com/juju/juju/cmd/juju/storage"
@@ -24,6 +25,7 @@ import (
"github.com/juju/juju/core/instance"
"github.com/juju/juju/core/relation"
"github.com/juju/juju/core/status"
+ jujuversion "github.com/juju/juju/version"
)
const (
@@ -55,13 +57,13 @@ func FormatTabular(writer io.Writer, forceColor bool, value interface{}) error {
// Default table output
header := []interface{}{"Model", "Controller", "Cloud/Region", "Version"}
- values := []interface{}{fs.Model.Name, fs.Model.Controller, cloudRegion, fs.Model.Version}
-
+ values := []interface{}{fs.Model.Name, fs.Model.Controller, cloudRegion}
// Optional table output if values exist
message := getModelMessage(fs.Model)
if fs.Model.SLA != "" {
header = append(header, "SLA")
values = append(values, fs.Model.SLA)
+
}
if cs := fs.Controller; cs != nil && cs.Timestamp != "" {
header = append(header, "Timestamp")
@@ -71,11 +73,19 @@ func FormatTabular(writer io.Writer, forceColor bool, value interface{}) error {
header = append(header, "Notes")
values = append(values, message)
}
-
// The first set of headers don't use outputHeaders because it adds the blank line.
w := startSection(tw, true, header...)
- w.Println(values...)
-
+ versionPos := indexOf("Version", header)
+ w.Print(values[:versionPos]...)
+ staleVersion := false
+ modelVersionNum, err := version.Parse(fs.Model.Version)
+ staleVersion = err == nil && jujuversion.Current.Compare(modelVersionNum) > 0
+ if staleVersion {
+ w.PrintColor(output.WarningHighlight, fs.Model.Version)
+ } else {
+ w.Print(fs.Model.Version)
+ }
+ w.Println(values[versionPos:]...)
if len(fs.Branches) > 0 {
printBranches(tw, fs.Branches)
}
|
highlight version number if stale
a stale version number is that which does not match the current juju agent version number
|
juju_juju
|
train
|
5d7083b6ca12f1abbfea4f9c32babc36de7a1265
|
diff --git a/lib/views/json.js b/lib/views/json.js
index <HASH>..<HASH> 100644
--- a/lib/views/json.js
+++ b/lib/views/json.js
@@ -1,20 +1,16 @@
'use strict';
-const _ = require('underscore');
-
-exports.execute = function (error, data, response, statusCode) {
- let status = error ? (error.status || 500) : (statusCode || 200);
-
- let object = { success: !error };
-
- if (error !== undefined && error !== null) {
- object.error = _.omit(error, 'status');
- object.error.message = error.message || 'internal_server_error';
- } else if (data !== undefined && data !== null) {
- object.data = data;
+exports.execute = function (error, data, response, status = 200) {
+ if (error !== undefined && error !== null && error.status !== null) {
+ status = error.status;
+ delete error.status;
}
- response.status(status).json(object);
+ response.status(status).json({
+ success: error === undefined && error === null && !error,
+ data,
+ error
+ });
};
module.exports = class JsonView {
|
[Views:Json] Reduce code complexity
|
BoolJS_booljs-express
|
train
|
097760e578940bf09317c6607e2e4001557c3572
|
diff --git a/src/Columns/Element.php b/src/Columns/Element.php
index <HASH>..<HASH> 100755
--- a/src/Columns/Element.php
+++ b/src/Columns/Element.php
@@ -4,6 +4,9 @@ namespace Terranet\Administrator\Columns;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Database\Eloquent\Model as Eloquent;
+use Illuminate\Database\Eloquent\Relations\BelongsToMany;
+use Illuminate\Database\Eloquent\Relations\HasMany;
+use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Terranet\Administrator\Columns\Decorators\CellDecorator;
use Terranet\Administrator\Traits\Collection\ElementContainer;
use Terranet\Administrator\Traits\LoopsOverRelations;
@@ -110,6 +113,11 @@ class Element extends ElementContainer
{
$id = $this->id();
+ # Treat (Has)Many(ToMany|Through) relations as "count()" subQuery.
+ if (($relation = $this->hasRelation($eloquent, $id)) && $this->isCountableRelation($relation)) {
+ return $this->fetchRelationValue($eloquent, $id, [$id => $relation], true);
+ }
+
if ($this->relations) {
return $this->fetchRelationValue($eloquent, $id, $this->relations, true);
}
@@ -135,7 +143,7 @@ class Element extends ElementContainer
*/
public function setStandalone($flag = true)
{
- $this->standalone = (bool) $flag;
+ $this->standalone = (bool)$flag;
return $this;
}
diff --git a/src/Traits/LoopsOverRelations.php b/src/Traits/LoopsOverRelations.php
index <HASH>..<HASH> 100755
--- a/src/Traits/LoopsOverRelations.php
+++ b/src/Traits/LoopsOverRelations.php
@@ -4,6 +4,8 @@ namespace Terranet\Administrator\Traits;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
+use Illuminate\Database\Eloquent\Relations\HasMany;
+use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Terranet\Administrator\Exception;
@@ -23,20 +25,15 @@ trait LoopsOverRelations
protected function fetchRelationValue($eloquent, $name, array $relations = [], $format = false)
{
$object = clone $eloquent;
-
while ($relation = array_shift($relations)) {
- $object = call_user_func([$orig = $object, $relation]);
+ # Treat (Has)Many(ToMany|Through) relations as "count()" subQuery.
+ if ($this->isCountableRelation($relation)) {
+ $relationObject = $object->$name();
- if ($object instanceof BelongsToMany) {
- return \DB::table($object->getTable())
- ->where($this->getQualifiedForeignKeyName($object), $orig->getKey())
- ->pluck($this->getQualifiedRelatedKeyName($object))
- ->toArray();
+ return $relationObject->count();
}
- if (!($object instanceof HasOne || $object instanceof BelongsTo || $object instanceof MorphOne)) {
- throw new Exception('Only HasOne and BelongsTo relations supported');
- }
+ $object = call_user_func([$orig = $object, $relation]);
$object = $object->getResults();
}
@@ -52,11 +49,15 @@ trait LoopsOverRelations
*/
protected function getQualifiedForeignKeyName($object)
{
- $foreignKey = method_exists($object, 'getQualifiedForeignKeyName')
- ? $object->getQualifiedForeignKeyName()
- : $object->getForeignKey();
+ if (method_exists($object, 'getQualifiedForeignKeyName')) {
+ return $object->getQualifiedForeignKeyName();
+ }
- return $foreignKey;
+ if (method_exists($object, 'getQualifiedForeignPivotKeyName')) {
+ return $object->getQualifiedForeignPivotKeyName();
+ }
+
+ return $object->getForeignKey();
}
/**
@@ -65,8 +66,35 @@ trait LoopsOverRelations
*/
protected function getQualifiedRelatedKeyName($object)
{
- return method_exists($object, 'getQualifiedRelatedKeyName')
- ? $object->getQualifiedRelatedKeyName()
- : $object->getOtherKey();
+ if (method_exists($object, 'getQualifiedRelatedKeyName')) {
+ return $object->getQualifiedRelatedKeyName();
+ }
+
+ if (method_exists($object, 'getQualifiedRelatedPivotKeyName')) {
+ return $object->getQualifiedRelatedPivotKeyName();
+ }
+
+ return $object->getOtherKey();
+ }
+
+ /**
+ * @param $eloquent
+ * @param $id
+ * @return bool
+ */
+ protected function hasRelation($eloquent, $id)
+ {
+ return (method_exists($eloquent, $id) && ($relation = $eloquent->$id())) ? $relation : null;
+ }
+
+ /**
+ * @param $relation
+ * @return bool
+ */
+ protected function isCountableRelation($relation)
+ {
+ return (is_a($relation, BelongsToMany::class)
+ || is_a($relation, HasMany::class)
+ || is_a($relation, HasManyThrough::class));
}
}
|
Treat (Has)Many(ToMany|Through) relations as Countable
|
adminarchitect_core
|
train
|
489378db5852d5e26a98295ab5fb8abe9653d710
|
diff --git a/lib/google/apis/core/base_service.rb b/lib/google/apis/core/base_service.rb
index <HASH>..<HASH> 100644
--- a/lib/google/apis/core/base_service.rb
+++ b/lib/google/apis/core/base_service.rb
@@ -84,6 +84,8 @@ module Google
# Base service for all APIs. Not to be used directly.
#
class BaseService
+ include Logging
+
# Root URL (host/port) for the API
# @return [Addressable::URI]
attr_accessor :root_url
@@ -393,6 +395,8 @@ module Google
end
client.follow_redirect_count = 5
client.default_header = { 'User-Agent' => user_agent }
+
+ client.debug_dev = logger if logger.level == Logger::DEBUG
client
end
diff --git a/lib/google/apis/core/http_command.rb b/lib/google/apis/core/http_command.rb
index <HASH>..<HASH> 100644
--- a/lib/google/apis/core/http_command.rb
+++ b/lib/google/apis/core/http_command.rb
@@ -155,6 +155,12 @@ module Google
else
@form_encoded = false
end
+
+ unless body
+ self.header['Content-Type'] = 'application/json'
+ self.header['Content-Length'] = 0
+ end
+
end
# Release any resources used by this command
|
Ensure content length when empty body, hook up httpclient to logger when debugging
|
googleapis_google-api-ruby-client
|
train
|
8ff7d9b6f69247169ca7302af3763b9f19edb2a5
|
diff --git a/azurerm/helpers/azure/resource_group.go b/azurerm/helpers/azure/resource_group.go
index <HASH>..<HASH> 100644
--- a/azurerm/helpers/azure/resource_group.go
+++ b/azurerm/helpers/azure/resource_group.go
@@ -47,8 +47,8 @@ func SchemaResourceGroupNameForDataSource() *schema.Schema {
func validateResourceGroupName(v interface{}, k string) (warnings []string, errors []error) {
value := v.(string)
- if len(value) > 80 {
- errors = append(errors, fmt.Errorf("%q may not exceed 80 characters in length", k))
+ if len(value) > 90 {
+ errors = append(errors, fmt.Errorf("%q may not exceed 90 characters in length", k))
}
if strings.HasSuffix(value, ".") {
diff --git a/azurerm/helpers/azure/resource_group_test.go b/azurerm/helpers/azure/resource_group_test.go
index <HASH>..<HASH> 100644
--- a/azurerm/helpers/azure/resource_group_test.go
+++ b/azurerm/helpers/azure/resource_group_test.go
@@ -48,11 +48,11 @@ func TestValidateResourceGroupName(t *testing.T) {
ErrCount: 1,
},
{
- Value: acctest.RandString(80),
+ Value: acctest.RandString(90),
ErrCount: 0,
},
{
- Value: acctest.RandString(81),
+ Value: acctest.RandString(91),
ErrCount: 1,
},
}
|
correct resource group character limit for name
* correct length: `1-<I>`
* <URL>
|
terraform-providers_terraform-provider-azurerm
|
train
|
fb043bba15fd59c7c6e947cfd870b12960b438dc
|
diff --git a/pkg/adaptor/transformer.go b/pkg/adaptor/transformer.go
index <HASH>..<HASH> 100644
--- a/pkg/adaptor/transformer.go
+++ b/pkg/adaptor/transformer.go
@@ -49,6 +49,10 @@ func NewTransformer(pipe *pipe.Pipe, path string, extra Config) (StopStartListen
t.fn = string(ba)
+ if err = t.initEnvironment(); err != nil {
+ return t, err
+ }
+
return t, nil
}
@@ -56,10 +60,6 @@ func NewTransformer(pipe *pipe.Pipe, path string, extra Config) (StopStartListen
// transformers it into mejson, and then uses the supplied javascript module.exports function
// to transform the document. The document is then emited to this adaptor's children
func (t *Transformer) Listen() (err error) {
- if err = t.initEnvironment(); err != nil {
- return err
- }
-
return t.pipe.Listen(t.transformOne)
}
|
init the transformer environment in the transformer c'tor, rather then in the listen method
|
compose_transporter
|
train
|
c527c237a208487787c930be21ce22c459fb7b9d
|
diff --git a/tests/cases/creator/count_distinct.php b/tests/cases/creator/count_distinct.php
index <HASH>..<HASH> 100644
--- a/tests/cases/creator/count_distinct.php
+++ b/tests/cases/creator/count_distinct.php
@@ -52,4 +52,4 @@ $created = $creator->created;
$expected = getExpectedValue(dirname(__FILE__), 'distinct.sql', false);
ok($created === $expected, 'count(distinct x)');
-?>
\ No newline at end of file
+?>
diff --git a/tests/cases/creator/delete.php b/tests/cases/creator/delete.php
index <HASH>..<HASH> 100644
--- a/tests/cases/creator/delete.php
+++ b/tests/cases/creator/delete.php
@@ -51,4 +51,4 @@ $created = $creator->created;
$expected = getExpectedValue(dirname(__FILE__), 'delete.sql', false);
ok($created === $expected, 'a multi-table delete statement');
-?>
\ No newline at end of file
+?>
diff --git a/tests/cases/creator/insert.php b/tests/cases/creator/insert.php
index <HASH>..<HASH> 100644
--- a/tests/cases/creator/insert.php
+++ b/tests/cases/creator/insert.php
@@ -68,4 +68,4 @@ $created = $creator->created;
$expected = getExpectedValue(dirname(__FILE__), 'insert3.sql', false);
ok($created === $expected, 'multiple records within INSERT (2)');
-?>
\ No newline at end of file
+?>
|
CHG: code formatting according to the guidelines, folder creator is now clean.
git-svn-id: <URL>
|
greenlion_PHP-SQL-Parser
|
train
|
035849d4058ae070bc552f5ad98001d145753652
|
diff --git a/openpnm/algorithms/MixedInvasionPercolation.py b/openpnm/algorithms/MixedInvasionPercolation.py
index <HASH>..<HASH> 100644
--- a/openpnm/algorithms/MixedInvasionPercolation.py
+++ b/openpnm/algorithms/MixedInvasionPercolation.py
@@ -196,6 +196,11 @@ class MixedInvasionPercolation(GenericAlgorithm):
logger.error("Either 'inlets' or 'clusters' must be passed to" +
" setup method")
self.queue = []
+ if (self.settings['cooperative_pore_filling'] and
+ hasattr(self, 'tt_Pc')):
+ check_coop = True
+ else:
+ check_coop = False
for i, cluster in enumerate(clusters):
self.queue.append([])
# Perform initial analysis on input pores
@@ -205,8 +210,12 @@ class MixedInvasionPercolation(GenericAlgorithm):
if np.size(cluster) > 1:
for elem_id in cluster:
self._add_ts2q(elem_id, self.queue[i])
+ if check_coop:
+ self._check_coop(elem_id, self.queue[i])
elif np.size(cluster) == 1:
self._add_ts2q(cluster, self.queue[i])
+ if check_coop:
+ self._check_coop(elem_id, self.queue[i])
else:
logger.warning("Some inlet clusters have no pores")
if self.settings['snap_off']:
@@ -988,7 +997,7 @@ class MixedInvasionPercolation(GenericAlgorithm):
for key in self.tt_Pc.keys():
self.tt_Pc[key] = np.nan
pairs = np.asarray([list(key) for key in adj_mat.keys()])
- pores = np.asarray([adj_mat[key] for key in adj_mat.keys()])
+ pores = np.asarray([adj_mat[key] for key in adj_mat.keys()]) - 1
angles = _throat_pair_angle(pairs[:, 0], pairs[:, 1], pores, net)
for Pc in inv_points:
if Pc == 0.0:
@@ -1010,7 +1019,10 @@ class MixedInvasionPercolation(GenericAlgorithm):
if np.any(mask):
for [i] in np.argwhere(mask):
self.tt_Pc[tuple(pairs[i])] = Pc
- print('Coop filling setup complete in', time.time()-start, 'seconds')
+ # Change to lil for single throat lookups
+ self.tt_Pc = self.tt_Pc.tolil()
+ logger.info("Coop filling finished in " +
+ str(np.around(time.time()-start, 2)) + " s")
def setup_coop_filling(self, inv_points=None):
r"""
|
update coop_filling to handle the problem with assigning pore index zero to a dok_matrix
|
PMEAL_OpenPNM
|
train
|
89d955f2b398ee519364b5c05fcee1aea786ee28
|
diff --git a/pandas/tests/tseries/frequencies/test_freq_code.py b/pandas/tests/tseries/frequencies/test_freq_code.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/tseries/frequencies/test_freq_code.py
+++ b/pandas/tests/tseries/frequencies/test_freq_code.py
@@ -1,3 +1,4 @@
+import numpy as np
import pytest
from pandas._libs.tslibs import (
@@ -78,3 +79,19 @@ def test_cat(args):
with pytest.raises(ValueError, match=msg):
to_offset(str(args[0]) + args[1])
+
+
+@pytest.mark.parametrize(
+ "freqstr,expected",
+ [
+ ("1H", "2021-01-01T09:00:00"),
+ ("1D", "2021-01-02T08:00:00"),
+ ("1W", "2021-01-03T08:00:00"),
+ ("1M", "2021-01-31T08:00:00"),
+ ("1Y", "2021-12-31T08:00:00"),
+ ],
+)
+def test_compatibility(freqstr, expected):
+ ts_np = np.datetime64("2021-01-01T08:00:00.00")
+ do = to_offset(freqstr)
+ assert ts_np + do == np.datetime64(expected)
|
TST: add test for compatibility with numpy datetime<I> (#<I>)
* TST: add test for compatibility with numpy datetime<I> #<I>
* TST; add test for compatibility with numpy datetime<I> (#<I>)
* Fixed a fat finger error in one of the expected values
* Fixes from pre-commit [automated commit]
* changed numpy import
|
pandas-dev_pandas
|
train
|
422dc84f346e2e33c4b594044da7e78c18aaefeb
|
diff --git a/library/Imbo/Image/ImagePreparation.php b/library/Imbo/Image/ImagePreparation.php
index <HASH>..<HASH> 100644
--- a/library/Imbo/Image/ImagePreparation.php
+++ b/library/Imbo/Image/ImagePreparation.php
@@ -12,6 +12,7 @@ namespace Imbo\Image;
use Imbo\EventManager\EventInterface,
Imbo\EventListener\ListenerInterface,
+ Imbo\Image\Identifier\Generator\GeneratorInterface,
Imbo\Exception\ImageException,
Imbo\Exception,
Imbo\Model\Image,
@@ -109,7 +110,7 @@ class ImagePreparation implements ListenerInterface {
$imageIdentifierGenerator = $config['imageIdentifierGenerator'];
if (is_callable($imageIdentifierGenerator) &&
- !($imageIdentifierGenerator instanceof ImageIdentifierGeneratorInterface)) {
+ !($imageIdentifierGenerator instanceof GeneratorInterface)) {
$imageIdentifierGenerator = $imageIdentifierGenerator();
}
diff --git a/tests/phpunit/ImboUnitTest/Image/ImagePreparationTest.php b/tests/phpunit/ImboUnitTest/Image/ImagePreparationTest.php
index <HASH>..<HASH> 100644
--- a/tests/phpunit/ImboUnitTest/Image/ImagePreparationTest.php
+++ b/tests/phpunit/ImboUnitTest/Image/ImagePreparationTest.php
@@ -10,7 +10,9 @@
namespace ImboUnitTest\Image;
-use Imbo\Image\ImagePreparation;
+use Imbo\Image\ImagePreparation,
+ Imbo\Model\Image,
+ Imbo\Image\Identifier\Generator\GeneratorInterface;
/**
* @covers Imbo\Image\ImagePreparation
@@ -173,4 +175,31 @@ class ImagePreparationTest extends \PHPUnit_Framework_TestCase {
$this->request->expects($this->once())->method('setImage')->with($this->isInstanceOf('Imbo\Model\Image'));
$this->prepare->prepareImage($event);
}
+
+ /**
+ * @covers Imbo\Image\ImagePreparation::prepareImage
+ * @covers Imbo\Image\ImagePreparation::generateImageIdentifier
+ */
+ public function testDoesNotInstantiateCallableGenerator() {
+ $imagePath = FIXTURES_DIR . '/image.png';
+ $imageData = file_get_contents($imagePath);
+
+ $config['imageIdentifierGenerator'] = new CallableImageIdentifierGenerator();
+
+ $event = $this->getMock('Imbo\EventManager\Event');
+ $event->expects($this->any())->method('getRequest')->will($this->returnValue($this->request));
+ $event->expects($this->any())->method('getResponse')->will($this->returnValue($this->response));
+ $event->expects($this->any())->method('getConfig')->will($this->returnValue($config));
+ $event->expects($this->any())->method('getDatabase')->will($this->returnValue($this->database));
+
+ $this->request->expects($this->once())->method('getContent')->will($this->returnValue($imageData));
+ $this->request->expects($this->once())->method('setImage')->with($this->isInstanceOf('Imbo\Model\Image'));
+ $this->prepare->prepareImage($event);
+ }
+}
+
+class CallableImageIdentifierGenerator implements GeneratorInterface {
+ public function generate(Image $image) {}
+ public function isDeterministic() {}
+ public function __invoke() {}
}
|
Fix potential bug caused by missing use statement in image preparation
|
imbo_imbo
|
train
|
1c1458a9c80b5739e3dedd09536b4e25701f7ce2
|
diff --git a/mbuild/compound.py b/mbuild/compound.py
index <HASH>..<HASH> 100755
--- a/mbuild/compound.py
+++ b/mbuild/compound.py
@@ -16,6 +16,7 @@ import numpy as np
from oset import oset as OrderedSet
import parmed as pmd
from parmed.periodic_table import AtomicNum, element_by_name, Mass
+import simtk.openmm.app.element as elem
from six import integer_types, string_types
from mbuild.bond_graph import BondGraph
@@ -1182,6 +1183,14 @@ class Compound(object):
"""
openbabel = import_('openbabel')
+ for particle in self.particles():
+ try:
+ elem.get_by_symbol(particle.name)
+ except KeyError:
+ raise MBuildError("Element name {} not recognized. Cannot "
+ "perform minimization."
+ "".format(particle.name)) from None
+
tmp_dir = tempfile.mkdtemp()
original = clone(self)
self._kick()
@@ -1214,13 +1223,7 @@ class Compound(object):
ff.UpdateCoordinates(mol)
obConversion.WriteFile(mol, os.path.join(tmp_dir, 'minimized.mol2'))
- try:
- self.update_coordinates(os.path.join(tmp_dir, 'minimized.mol2'))
- except ValueError:
- for i, particle in enumerate(self.particles()):
- particle.pos = original.xyz[i]
- warn("Minimization failed (perhaps your Compound contains non-"
- "element types). Coordinates not updated.", RuntimeWarning)
+ self.update_coordinates(os.path.join(tmp_dir, 'minimized.mol2'))
def save(self, filename, show_ports=False, forcefield_name=None,
forcefield_files=None, box=None, overwrite=False, residues=None,
diff --git a/mbuild/tests/test_compound.py b/mbuild/tests/test_compound.py
index <HASH>..<HASH> 100755
--- a/mbuild/tests/test_compound.py
+++ b/mbuild/tests/test_compound.py
@@ -535,7 +535,7 @@ class TestCompound(BaseTest):
def test_energy_minimization_non_element(self, octane):
for particle in octane.particles():
particle.name = 'Q'
- with pytest.warns(RuntimeWarning):
+ with pytest.raises(MBuildError):
octane.energy_minimization()
@pytest.mark.skipif(not has_openbabel, reason="Open Babel package not installed")
|
More descriptive error when non-elements detected
Previously a catch-all warning was to be raised if the minimization failed,
however, this only occurred when non-elements were detected and was not
always reliable. Now a periodic table lookup is performed prior to attempting
minimization and an error is raised if non-elements are detected.
|
mosdef-hub_mbuild
|
train
|
b6af597f2cd785593ebb36b8b8f0e90d2bcc32ab
|
diff --git a/scapy.py b/scapy.py
index <HASH>..<HASH> 100755
--- a/scapy.py
+++ b/scapy.py
@@ -22,6 +22,9 @@
#
# $Log: scapy.py,v $
+# Revision 0.9.14.6 2003/09/12 14:45:35 pbi
+# - had Dot11 working
+#
# Revision 0.9.14.5 2003/09/12 10:04:05 pbi
# - added summary() method to Packet objects
#
@@ -273,7 +276,7 @@
from __future__ import generators
-RCSID="$Id: scapy.py,v 0.9.14.5 2003/09/12 10:04:05 pbi Exp $"
+RCSID="$Id: scapy.py,v 0.9.14.6 2003/09/12 14:45:35 pbi Exp $"
VERSION = RCSID.split()[2]+"beta"
@@ -1015,7 +1018,49 @@ class ARPSourceMACField(MACField):
return MACField.i2h(self, pkt, x)
def i2m(self, pkt, x):
return MACField.i2m(self, pkt, self.i2h(pkt, x))
-
+
+class Dot11AddrMACField(MACField):
+ def is_applicable(self, pkt):
+ return 1
+ def addfield(self, pkt, s, val):
+ if self.is_applicable(pkt):
+ return MACField.addfield(self, pkt, s, val)
+ else:
+ return s
+ def getfield(self, pkt, s):
+ if self.is_applicable(pkt):
+ return MACField.getfield(self, pkt, s)
+ else:
+ return s,None
+
+class Dot11Addr2MACField(MACField):
+ def is_applicable(self, pkt):
+ if pkt.type == 1:
+ return pkt.subtype in [ 0xb, 0xa, 0xe, 0xf] # RTS, PS-Poll, CF-End, CF-End+CF-Ack
+ return 0
+
+class Dot11Addr3MACField(MACField):
+ def is_applicable(self, pkt):
+ if pkt.type in [0,2]:
+ return 1
+ return 0
+
+class Dot11Addr4MACField(MACField):
+ def is_applicable(self, pkt):
+ if pkt.type == 2:
+ if pkt.FCfield & 0x3 == 0x3: # To-DS and From-DS are set
+ return 1
+ return 0
+ def addfield(self, pkt, s, val):
+ if self.is_applicable(pkt):
+ return MACField.addfield(self, pkt, s, val)
+ else:
+ return s
+ def getfield(self, pkt, s):
+ if self.is_applicable(pkt):
+ return MACField.getfield(self, pkt, s)
+ else:
+ return s,None
class IPField(Field):
@@ -1213,10 +1258,17 @@ class EnumField(Field):
x = self.s2i[x]
return x
def i2repr(self, pkt, x):
- y = self.i2s.get(x)
- if y is None:
- y = x
- return y
+ return self.i2s.get(x, x)
+
+
+class BitEnumField(BitField,EnumField):
+ def __init__(self, name, default, size, enum):
+ EnumField.__init__(self, name, default, enum)
+ self.size = size
+ def any2i(self, pkt, x):
+ return EnumField.any2i(self, pkt, x)
+ def i2repr(self, pkt, x):
+ return EnumField.i2repr(self, pkt, x)
class ShortEnumField(EnumField):
def __init__(self, name, default, enum):
@@ -2465,16 +2517,19 @@ dhcpmagic="".join(map(chr,[99,130,83,99]))
class Dot11(Packet):
name = "802.11"
fields_desc = [
- BitField("proto", 0, 2),
- BitField("type", 0, 2),
BitField("subtype", 0, 4),
- FlagsField("fc", 0, 8, ["to-DS", "from-DS", "MF", "retry", "pw-mgt", "MD", "wep", "order"]),
+ BitEnumField("type", 0, 2, ["Management", "Control", "Data", "Reserved"]),
+ BitField("proto", 0, 2),
+ FlagsField("FCfield", 0, 8, ["to-DS", "from-DS", "MF", "retry", "pw-mgt", "MD", "wep", "order"]),
ShortField("ID",0),
MACField("addr1", ETHER_ANY),
- MACField("addr2", ETHER_ANY),
- MACField("addr3", ETHER_ANY),
+ Dot11Addr2MACField("addr2", ETHER_ANY),
+ Dot11Addr3MACField("addr3", ETHER_ANY),
ShortField("SC", 0),
- MACField("addr4", ETHER_ANY) ]
+ Dot11Addr4MACField("addr4", ETHER_ANY)
+ ]
+ def mysummary(self):
+ return self.sprintf("802.11 %Dot11.type% %Dot11.subtype% %Dot11.addr1%")
#########
##
@@ -2522,6 +2577,7 @@ def bind_layers(lower, upper, fval):
layer_bonds = [ ( Dot3, LLC, { } ),
+ ( Dot11, LLC, { "type" : 2 } ),
( LLPPP, IP, { } ),
( Ether, Dot1Q, { "type" : 0x8100 } ),
( Ether, Ether, { "type" : 0x0001 } ),
|
- had Dot<I> working
|
secdev_scapy
|
train
|
f4672c174f0646a5abb0a13d905efe9c94332e40
|
diff --git a/firefed/feature/feature.py b/firefed/feature/feature.py
index <HASH>..<HASH> 100644
--- a/firefed/feature/feature.py
+++ b/firefed/feature/feature.py
@@ -27,6 +27,7 @@ def output_formats(choices, default):
class Feature(ABC):
description = '(no description)'
+ has_summary = False
def __init__(self, firefed):
self.ff = firefed
diff --git a/firefed/feature/summary.py b/firefed/feature/summary.py
index <HASH>..<HASH> 100644
--- a/firefed/feature/summary.py
+++ b/firefed/feature/summary.py
@@ -9,4 +9,6 @@ class Summary(Feature):
features.remove(Summary)
for Feature_ in features:
args.summarize = True
+ if not Feature.has_summary:
+ continue
Feature_(self.ff)(args)
diff --git a/firefed/firefed.py b/firefed/firefed.py
index <HASH>..<HASH> 100644
--- a/firefed/firefed.py
+++ b/firefed/firefed.py
@@ -7,7 +7,7 @@ class Firefed:
def __init__(self, args):
self.profile_dir = args.profile
ChosenFeature = feature_map()[args.feature]
- if args.format != 'csv': # TODO Refactor as verbosity flag
+ if 'format' not in args or args.format != 'csv': # TODO Refactor as verbosity flag
info('Profile:', self.profile_dir)
info('Feature: %s\n' % ChosenFeature.__name__)
ChosenFeature(self)(args)
diff --git a/tests/test_firefed.py b/tests/test_firefed.py
index <HASH>..<HASH> 100644
--- a/tests/test_firefed.py
+++ b/tests/test_firefed.py
@@ -1,3 +1,4 @@
+import argparse
from datetime import datetime
import os
from pathlib import Path
@@ -6,10 +7,13 @@ import shutil
import sqlite3
import csv
from io import StringIO
+from unittest import mock
+import sys
+import firefed.__main__
from firefed import Firefed
from firefed.feature import Feature, Summary, Logins
-from firefed.util import profile_dir, ProfileNotFoundError, feature_map, moz_datetime, moz_timestamp, make_parser
+from firefed.util import profile_dir, profile_dir_type, ProfileNotFoundError, feature_map, moz_datetime, moz_timestamp, make_parser
@pytest.fixture
@@ -28,13 +32,13 @@ def mock_home(tmpdir_factory):
f.write(data)
return home_path
-@pytest.fixture
+@pytest.fixture(scope='module')
def mock_profile(mock_home):
profile_path = mock_home / '.mozilla/firefox/random.default'
make_permissions_sqlite(profile_path)
return profile_path
-@pytest.fixture
+@pytest.fixture(scope='function')
def feature(mock_profile, parser):
def func(*more_args):
args = parser.parse_args(['--profile', str(mock_profile), *more_args])
@@ -57,6 +61,27 @@ def parse_csv(str_):
return list(csv.reader(StringIO(str_)))
+class TestMain:
+
+ def test_main(self):
+ with pytest.raises(SystemExit) as e:
+ firefed.__main__.main()
+ assert e.value.code == 2
+
+ def test_main_help(self, capsys):
+ with mock.patch.object(sys, 'argv', ['firefed', '-h']):
+ with pytest.raises(SystemExit) as e:
+ firefed.__main__.main()
+ assert e.value.code == 0
+ out, _ = capsys.readouterr()
+ assert out.startswith('usage:')
+
+ def test_main_with_feature(self, mock_profile):
+ argv = ['firefed', '--profile', str(mock_profile), 'summary']
+ with mock.patch.object(sys, 'argv', argv):
+ firefed.__main__.main()
+
+
class TestUtils:
def test_profile_dir(self, monkeypatch, mock_home):
@@ -71,6 +96,21 @@ class TestUtils:
with pytest.raises(ProfileNotFoundError):
profile_dir('nonexistent')
+ def test_profile_dir_type(self, mock_home):
+ assert profile_dir('default') == profile_dir_type('default')
+ with pytest.raises(argparse.ArgumentTypeError):
+ profile_dir_type('nonexistent')
+
+ def test_argparse(self, capsys, mock_profile):
+ parser = make_parser()
+ with pytest.raises(SystemExit) as e:
+ args = parser.parse_args(['-h'])
+ assert e.value.code == 0
+ out, _ = capsys.readouterr()
+ assert out.startswith('usage:')
+ args = parser.parse_args(['--profile', str(mock_profile), 'summary'])
+ assert args.summarize is False
+
def test_feature_map(self):
fmap = feature_map()
assert len(fmap) > 1
|
Add more tests + refactorings
|
numirias_firefed
|
train
|
b8e7585d28ebaae50749b508e177b095cbcef4d0
|
diff --git a/src/system/modules/metamodelsattribute_rating/config/config.php b/src/system/modules/metamodelsattribute_rating/config/config.php
index <HASH>..<HASH> 100644
--- a/src/system/modules/metamodelsattribute_rating/config/config.php
+++ b/src/system/modules/metamodelsattribute_rating/config/config.php
@@ -15,10 +15,6 @@
* @filesource
*/
-$GLOBALS['METAMODELS']['attributes']['rating'] = array
-(
- 'class' => 'MetaModelAttributeRating',
- 'image' => 'system/modules/metamodelsattribute_rating/html/star-full.png'
-);
-
+$GLOBALS['METAMODELS']['attributes']['rating']['class'] = 'MetaModelAttributeRating';
+$GLOBALS['METAMODELS']['attributes']['rating']['image'] = 'system/modules/metamodelsattribute_rating/html/star-full.png';
$GLOBALS['TL_HOOKS']['simpleAjax'][] = array('MetaModelAttributeRatingAjax', 'handle');
\ No newline at end of file
|
The config now does "deep assignments"
See <URL>
|
MetaModels_attribute_rating
|
train
|
9b46836afb401a15c28052359b921f5d04b6a5dc
|
diff --git a/libs/holograph.js b/libs/holograph.js
index <HASH>..<HASH> 100644
--- a/libs/holograph.js
+++ b/libs/holograph.js
@@ -96,7 +96,7 @@ function preparePageLinks(current, pages, index_title) {
for (category in pages) {
if (pages.hasOwnProperty(category)) {
links.push({
- link: category + '.html',
+ link: category.replace(/\s+/g, '').toLowerCase() + '.html',
title: category,
selected: category === current ? 'selected' : ''
});
|
Improve URLs
Resolves issue #<I>.
|
holography_holograph
|
train
|
1fa098b6ba38e26ebd92a15b7a35936a9ad48a07
|
diff --git a/domain-management/src/main/java/org/jboss/as/domain/management/security/adduser/AddUser.java b/domain-management/src/main/java/org/jboss/as/domain/management/security/adduser/AddUser.java
index <HASH>..<HASH> 100644
--- a/domain-management/src/main/java/org/jboss/as/domain/management/security/adduser/AddUser.java
+++ b/domain-management/src/main/java/org/jboss/as/domain/management/security/adduser/AddUser.java
@@ -361,7 +361,7 @@ public class AddUser {
return MESSAGES.argRealm();
}
},
- SILENT("-s", "--silent") {
+ SILENT("-s", "--silent", "--silent=true") {
@Override
public String instructions() {
return MESSAGES.argSilent();
@@ -407,8 +407,10 @@ public class AddUser {
};
private static String USAGE;
+
private String shortArg;
private String longArg;
+ private String additionalArg;
private CommandLineArgument(String option) {
this.shortArg = option;
@@ -419,12 +421,18 @@ public class AddUser {
this.longArg = longArg;
}
+ private CommandLineArgument(String shortArg, String longArg, String additionalArg) {
+ this.shortArg = shortArg;
+ this.longArg = longArg;
+ this.additionalArg = additionalArg;
+ }
+
public String key() {
return longArg != null ? longArg.substring(2) : shortArg.substring(1);
}
public boolean match(String option) {
- return option.equals(shortArg) || option.equals(longArg);
+ return option.equals(shortArg) || option.equals(longArg) || option.equals(additionalArg);
}
public String getShortArg() {
|
[WFLY-<I>] Add support for a --silent=true option to add-user.
The real option should be --silent but this is causing some confusion for end users.
|
wildfly_wildfly
|
train
|
3d67f687fe591bb9af11dc38656c5e69ba605aa1
|
diff --git a/src/com/opencms/defaults/A_CmsContentDefinition.java b/src/com/opencms/defaults/A_CmsContentDefinition.java
index <HASH>..<HASH> 100644
--- a/src/com/opencms/defaults/A_CmsContentDefinition.java
+++ b/src/com/opencms/defaults/A_CmsContentDefinition.java
@@ -1,7 +1,7 @@
/*
* File : $Source: /alkacon/cvs/opencms/src/com/opencms/defaults/Attic/A_CmsContentDefinition.java,v $
-* Date : $Date: 2001/07/31 15:50:13 $
-* Version: $Revision: 1.6 $
+* Date : $Date: 2001/10/19 15:02:17 $
+* Version: $Revision: 1.7 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
@@ -19,7 +19,7 @@
* Lesser General Public License for more details.
*
* For further information about OpenCms, please see the
-* OpenCms Website: http://www.opencms.org
+* OpenCms Website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
@@ -93,7 +93,6 @@ public static Vector applyFilter(CmsObject cms, CmsFilterMethod filterMethod, St
allParametersArray = new Object[allParameters.size()];
allParameters.copyInto(allParametersArray);
-
return (Vector) method.invoke(null, allParametersArray);
}
@@ -345,4 +344,14 @@ private boolean accessOther( int flags ) throws CmsException {
return false;
}
}
+
+/**
+ * if the content definition objects should be displayed
+ * in an extended list with projectflags and state
+ * this method must be overwritten with value true
+ * @returns a boolean
+ */
+public static boolean isExtendedList() {
+ return false;
+}
}
|
New method isExtendedList returns true if the content definition
should use the new list with projectflag and state.
|
alkacon_opencms-core
|
train
|
0c83eae6fbc9c8504d66c2b7aa31f06d7361cf08
|
diff --git a/builtin/credential/approle/path_login.go b/builtin/credential/approle/path_login.go
index <HASH>..<HASH> 100644
--- a/builtin/credential/approle/path_login.go
+++ b/builtin/credential/approle/path_login.go
@@ -83,7 +83,7 @@ func (b *backend) pathLoginUpdate(ctx context.Context, req *logical.Request, dat
return logical.ErrorResponse("invalid role ID"), nil
}
- var metadata map[string]string
+ metadata := make(map[string]string)
if role.BindSecretID {
secretID := strings.TrimSpace(data.Get("secret_id").(string))
if secretID == "" {
@@ -261,6 +261,12 @@ func (b *backend) pathLoginUpdate(ctx context.Context, req *logical.Request, dat
}
}
+ // For some reason, if metadata was set to nil while processing secret ID
+ // binding, ensure that it is initialized again to avoid a panic.
+ if metadata == nil {
+ metadata = make(map[string]string)
+ }
+
// Always include the role name, for later filtering
metadata["role_name"] = role.name
diff --git a/builtin/credential/approle/path_login_test.go b/builtin/credential/approle/path_login_test.go
index <HASH>..<HASH> 100644
--- a/builtin/credential/approle/path_login_test.go
+++ b/builtin/credential/approle/path_login_test.go
@@ -8,6 +8,58 @@ import (
"github.com/hashicorp/vault/logical"
)
+func TestAppRole_BoundCIDRLogin(t *testing.T) {
+ var resp *logical.Response
+ var err error
+ b, s := createBackendWithStorage(t)
+
+ // Create a role with secret ID binding disabled and only bound cidr list
+ // enabled
+ resp, err = b.HandleRequest(context.Background(), &logical.Request{
+ Path: "role/testrole",
+ Operation: logical.CreateOperation,
+ Data: map[string]interface{}{
+ "bind_secret_id": false,
+ "bound_cidr_list": []string{"127.0.0.1/8"},
+ },
+ Storage: s,
+ })
+ if err != nil || (resp != nil && resp.IsError()) {
+ t.Fatalf("err:%v resp:%#v", err, resp)
+ }
+
+ // Read the role ID
+ resp, err = b.HandleRequest(context.Background(), &logical.Request{
+ Path: "role/testrole/role-id",
+ Operation: logical.ReadOperation,
+ Storage: s,
+ })
+ if err != nil || (resp != nil && resp.IsError()) {
+ t.Fatalf("err:%v resp:%#v", err, resp)
+ }
+
+ roleID := resp.Data["role_id"]
+
+ // Fill in the connection information and login with just the role ID
+ resp, err = b.HandleRequest(context.Background(), &logical.Request{
+ Path: "login",
+ Operation: logical.UpdateOperation,
+ Data: map[string]interface{}{
+ "role_id": roleID,
+ },
+ Storage: s,
+ Connection: &logical.Connection{RemoteAddr: "127.0.0.1"},
+ })
+ if err != nil || (resp != nil && resp.IsError()) {
+ t.Fatalf("err:%v resp:%#v", err, resp)
+ }
+
+ // Login should pass
+ if resp.Auth == nil {
+ t.Fatalf("expected login to succeed")
+ }
+}
+
func TestAppRole_RoleLogin(t *testing.T) {
var resp *logical.Response
var err error
|
Fix panic due to metadata being nil (#<I>)
* Fix panic due to metadata being nil
* added a nil check
* Added a test
* ensure metadata is never nil
* Remove unnecessary allocation
* revert back to early initialization
|
hashicorp_vault
|
train
|
60b8d6a5c6a7aaf3f2f07114e04ea97b3857411f
|
diff --git a/go/teams/create.go b/go/teams/create.go
index <HASH>..<HASH> 100644
--- a/go/teams/create.go
+++ b/go/teams/create.go
@@ -141,8 +141,8 @@ func CreateImplicitTeam(ctx context.Context, g *libkb.GlobalContext, impTeam key
func makeSigAndPostRootTeam(ctx context.Context, g *libkb.GlobalContext, me *libkb.User, members SCTeamMembers,
invites *SCTeamInvites, secretboxRecipients map[keybase1.UserVersion]keybase1.PerUserKey, name string,
- teamID keybase1.TeamID, public, implicit bool, settings *SCTeamSettings) error {
-
+ teamID keybase1.TeamID, public, implicit bool, settings *SCTeamSettings) (err error) {
+ defer g.Trace("makeSigAndPostRootTeam", func() error { return err })()
g.Log.CDebugf(ctx, "makeSigAndPostRootTeam get device keys")
deviceSigningKey, err := g.ActiveDevice.SigningKey()
if err != nil {
@@ -247,6 +247,7 @@ func makeSigAndPostRootTeam(ctx context.Context, g *libkb.GlobalContext, me *lib
payload["per_team_key"] = secretboxes
_, err = g.API.PostJSON(libkb.APIArg{
+ NetContext: ctx,
Endpoint: "sig/multi",
SessionType: libkb.APISessionTypeREQUIRED,
JSONPayload: payload,
|
use context when posting team sigs (#<I>)
|
keybase_client
|
train
|
5f6ba048e635e6fe0953d8bbbeafbd86a31f50ad
|
diff --git a/front/src/js/controllers/dashboardCtrl.js b/front/src/js/controllers/dashboardCtrl.js
index <HASH>..<HASH> 100644
--- a/front/src/js/controllers/dashboardCtrl.js
+++ b/front/src/js/controllers/dashboardCtrl.js
@@ -8,7 +8,7 @@ dashboardCtrl.controller('DashboardCtrl', ['$scope', '$rootScope', '$routeParams
function loadResults() {
// Load result if needed
if (!$rootScope.loadedResult || $rootScope.loadedResult.runId !== $routeParams.runId) {
- Results.get({runId: $routeParams.runId}, function(result) {
+ Results.get({runId: $routeParams.runId, exclude: 'toolsResults'}, function(result) {
$rootScope.loadedResult = result;
$scope.result = result;
init();
diff --git a/front/src/js/controllers/ruleCtrl.js b/front/src/js/controllers/ruleCtrl.js
index <HASH>..<HASH> 100644
--- a/front/src/js/controllers/ruleCtrl.js
+++ b/front/src/js/controllers/ruleCtrl.js
@@ -9,7 +9,7 @@ ruleCtrl.controller('RuleCtrl', ['$scope', '$rootScope', '$routeParams', '$locat
function loadResults() {
// Load result if needed
if (!$rootScope.loadedResult || $rootScope.loadedResult.runId !== $routeParams.runId) {
- Results.get({runId: $routeParams.runId}, function(result) {
+ Results.get({runId: $routeParams.runId, exclude: 'toolsResults'}, function(result) {
$rootScope.loadedResult = result;
$scope.result = result;
init();
diff --git a/front/src/js/controllers/screenshotCtrl.js b/front/src/js/controllers/screenshotCtrl.js
index <HASH>..<HASH> 100644
--- a/front/src/js/controllers/screenshotCtrl.js
+++ b/front/src/js/controllers/screenshotCtrl.js
@@ -7,7 +7,7 @@ screenshotCtrl.controller('ScreenshotCtrl', ['$scope', '$rootScope', '$routePara
function loadResults() {
// Load result if needed
if (!$rootScope.loadedResult || $rootScope.loadedResult.runId !== $routeParams.runId) {
- Results.get({runId: $routeParams.runId}, function(result) {
+ Results.get({runId: $routeParams.runId, exclude: 'toolsResults'}, function(result) {
$rootScope.loadedResult = result;
$scope.result = result;
}, function(err) {
diff --git a/front/src/js/controllers/timelineCtrl.js b/front/src/js/controllers/timelineCtrl.js
index <HASH>..<HASH> 100644
--- a/front/src/js/controllers/timelineCtrl.js
+++ b/front/src/js/controllers/timelineCtrl.js
@@ -7,7 +7,7 @@ timelineCtrl.controller('TimelineCtrl', ['$scope', '$rootScope', '$routeParams',
function loadResults() {
// Load result if needed
if (!$rootScope.loadedResult || $rootScope.loadedResult.runId !== $routeParams.runId) {
- Results.get({runId: $routeParams.runId}, function(result) {
+ Results.get({runId: $routeParams.runId, exclude: 'toolsResults'}, function(result) {
$rootScope.loadedResult = result;
$scope.result = result;
render();
|
Make the results API call smaller by removing toolsResults
|
gmetais_YellowLabTools
|
train
|
55d77a73f95cfb92e1c00ed35a38eb1197d542ac
|
diff --git a/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/AbstractForager.java b/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/AbstractForager.java
index <HASH>..<HASH> 100644
--- a/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/AbstractForager.java
+++ b/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/AbstractForager.java
@@ -6,6 +6,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
+ * Abstract superclass for {@link Forager}.
+ * @see Forager
* @author Geoffrey De Smet
*/
public abstract class AbstractForager implements Forager {
diff --git a/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/Forager.java b/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/Forager.java
index <HASH>..<HASH> 100644
--- a/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/Forager.java
+++ b/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/Forager.java
@@ -8,7 +8,8 @@ import org.drools.solver.core.localsearch.decider.MoveScope;
import org.drools.solver.core.move.Move;
/**
- * Do not implement directly, but instead extend {@link AbstractForager}.
+ * A Forager collects the accepted moves and picks the next step from those for the Decider.
+ * @see AbstractForager
* @author Geoffrey De Smet
*/
public interface Forager extends LocalSearchSolverLifecycleListener {
diff --git a/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/PickEarlyByScore.java b/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/PickEarlyByScore.java
index <HASH>..<HASH> 100644
--- a/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/PickEarlyByScore.java
+++ b/drools-solver/drools-solver-core/src/main/java/org/drools/solver/core/localsearch/decider/forager/PickEarlyByScore.java
@@ -7,5 +7,4 @@ public enum PickEarlyByScore {
NONE,
FIRST_BEST_SCORE_IMPROVING,
FIRST_LAST_STEP_SCORE_IMPROVING;
-
}
|
javadocs (extraction from score_refactor attempt 1 that cannot be committed because its a lot slower)
git-svn-id: <URL>
|
kiegroup_optaplanner
|
train
|
e49bc9dacf3425cf98dfeceb0048afc4c50d4278
|
diff --git a/src/views/account/_form.php b/src/views/account/_form.php
index <HASH>..<HASH> 100644
--- a/src/views/account/_form.php
+++ b/src/views/account/_form.php
@@ -72,15 +72,20 @@ use yii\web\View;
?>
</div>
</div>
- <div class="box-footer">
- <?= Html::submitButton(Yii::t('hipanel', 'Save'), ['class' => 'btn btn-success']) ?>
- <?= Html::button(Yii::t('hipanel', 'Cancel'), ['class' => 'btn btn-default', 'onclick' => 'history.go(-1)']) ?>
- </div>
</div>
</div>
</div>
<?php } ?>
+ <div class="row">
+ <div class="col-md-4">
+ <div class="box box-widget">
+ <div class="box-body">
+ <?= Html::submitButton(Yii::t('hipanel', 'Save'), ['class' => 'btn btn-success']) ?>
+ <?= Html::button(Yii::t('hipanel', 'Cancel'), ['class' => 'btn btn-default', 'onclick' => 'history.go(-1)']) ?>
+ </div>
+ </div>
+ </div>
+ </div>
</div>
-
<?php ActiveForm::end(); ?>
<?php $this->registerJs("$('#account-sshftp_ips').popover({placement: 'top', trigger: 'focus'});"); ?>
diff --git a/src/views/db/_form.php b/src/views/db/_form.php
index <HASH>..<HASH> 100644
--- a/src/views/db/_form.php
+++ b/src/views/db/_form.php
@@ -55,8 +55,15 @@ $form = ActiveForm::begin([
</div>
</div>
<?php } ?>
+ <div class="row">
+ <div class="col-md-4">
+ <div class="box box-widget">
+ <div class="box-body">
+ <?= Html::submitButton(Yii::t('hipanel', 'Save'), ['class' => 'btn btn-success']) ?>
+ <?= Html::button(Yii::t('hipanel', 'Cancel'), ['class' => 'btn btn-default', 'onclick' => 'history.go(-1)']) ?>
+ </div>
+ </div>
+ </div>
+ </div>
</div>
-<?= Html::submitButton(Yii::t('hipanel', 'Save'), ['class' => 'btn btn-default']) ?>
-
-<?= Html::button(Yii::t('hipanel', 'Cancel'), ['class' => 'btn btn-default', 'onclick' => 'history.go(-1)']) ?>
<?php ActiveForm::end(); ?>
|
Fixed account form button and bd form button
|
hiqdev_hipanel-module-hosting
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.