hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
f43ede5cdda183ba04ab59ffa2ca7ff59916e40e
|
diff --git a/raiden/api/v1/encoding.py b/raiden/api/v1/encoding.py
index <HASH>..<HASH> 100644
--- a/raiden/api/v1/encoding.py
+++ b/raiden/api/v1/encoding.py
@@ -16,7 +16,7 @@ from werkzeug.exceptions import NotFound
from werkzeug.routing import BaseConverter
from raiden.api.objects import Address, AddressList, PartnersPerToken, PartnersPerTokenList
-from raiden.constants import SECRET_LENGTH, SECRETHASH_LENGTH, UINT256_MAX
+from raiden.constants import SECRET_LENGTH, SECRETHASH_LENGTH, UINT256_MAX, NULL_ADDRESS_BYTES
from raiden.settings import DEFAULT_INITIAL_CHANNEL_TARGET, DEFAULT_JOINABLE_FUNDS_TARGET
from raiden.transfer import channel
from raiden.transfer.state import ChannelState, NettingChannelState
@@ -56,6 +56,7 @@ class AddressField(fields.Field):
"invalid_checksum": "Not a valid EIP55 encoded address",
"invalid_data": "Not a valid hex encoded address, contains invalid characters.",
"invalid_size": "Not a valid hex encoded address, decoded address is not 20 bytes long.",
+ "null_address": "The 0x0000000000000000000000000000000000000000 address is not accepted",
}
@staticmethod
@@ -77,6 +78,9 @@ class AddressField(fields.Field):
if len(value) != 20:
self.fail("invalid_size")
+ if value == NULL_ADDRESS_BYTES:
+ self.fail("null_address")
+
return value
|
Do not accept null address input for the AddressField
Fix #<I>
|
raiden-network_raiden
|
train
|
6cb82a52ee6751f36ef1c2759ca083161ad3f2ff
|
diff --git a/src/components/connectAdvanced.js b/src/components/connectAdvanced.js
index <HASH>..<HASH> 100644
--- a/src/components/connectAdvanced.js
+++ b/src/components/connectAdvanced.js
@@ -106,6 +106,10 @@ export default function connectAdvanced(
`or explicitly pass "${storeKey}" as a prop to "${displayName}".`
)
+ // make sure `getState` is properly bound in order to avoid breaking
+ // custom store implementations that rely on the store's context
+ this.getState = this.store.getState.bind(this.store);
+
this.initSelector()
this.initSubscription()
}
@@ -160,7 +164,7 @@ export default function connectAdvanced(
initSelector() {
const { dispatch } = this.store
- let getState = this.store.getState.bind(this.store)
+ const { getState } = this;
const sourceSelector = selectorFactory(dispatch, selectorFactoryOptions)
// wrap the selector in an object that tracks its results between runs
diff --git a/test/components/connect.spec.js b/test/components/connect.spec.js
index <HASH>..<HASH> 100644
--- a/test/components/connect.spec.js
+++ b/test/components/connect.spec.js
@@ -25,6 +25,30 @@ describe('React', () => {
}
}
+ class ContextBoundStore {
+ constructor(reducer) {
+ this.reducer = reducer
+ this.listeners = []
+ this.state = undefined
+ this.dispatch({})
+ }
+
+ getState() {
+ return this.state
+ }
+
+ subscribe(listener) {
+ this.listeners.push(listener)
+ return (() => this.listeners.filter(l => l !== listener))
+ }
+
+ dispatch(action) {
+ this.state = this.reducer(this.getState(), action)
+ this.listeners.forEach(l => l())
+ return action
+ }
+ }
+
ProviderMock.childContextTypes = {
store: PropTypes.object.isRequired
}
@@ -134,6 +158,30 @@ describe('React', () => {
expect(stub.props.string).toBe('ab')
})
+ it('should retain the store\'s context', () => {
+ const store = new ContextBoundStore(stringBuilder)
+
+ let Container = connect(
+ state => ({ string: state })
+ )(function Container(props) {
+ return <Passthrough {...props}/>
+ })
+
+ const spy = expect.spyOn(console, 'error')
+ const tree = TestUtils.renderIntoDocument(
+ <ProviderMock store={store}>
+ <Container />
+ </ProviderMock>
+ )
+ spy.destroy()
+ expect(spy.calls.length).toBe(0)
+
+ const stub = TestUtils.findRenderedComponentWithType(tree, Passthrough)
+ expect(stub.props.string).toBe('')
+ store.dispatch({ type: 'APPEND', body: 'a' })
+ expect(stub.props.string).toBe('a')
+ })
+
it('should handle dispatches before componentDidMount', () => {
const store = createStore(stringBuilder)
|
add store context-preservation tests
|
reduxjs_react-redux
|
train
|
a54efd95c9ac0b87ad24d6d191c467bfddc690a9
|
diff --git a/presto-orc/src/test/java/com/facebook/presto/orc/TestDecryption.java b/presto-orc/src/test/java/com/facebook/presto/orc/TestDecryption.java
index <HASH>..<HASH> 100644
--- a/presto-orc/src/test/java/com/facebook/presto/orc/TestDecryption.java
+++ b/presto-orc/src/test/java/com/facebook/presto/orc/TestDecryption.java
@@ -238,7 +238,6 @@ public class TestDecryption
{
Type rowType = rowType(BIGINT, BIGINT, BIGINT);
Slice iek1 = Slices.utf8Slice("iek1");
- Slice dek = Slices.utf8Slice("dek");
DwrfWriterEncryption dwrfWriterEncryption = new DwrfWriterEncryption(
UNKNOWN,
ImmutableList.of(
@@ -277,7 +276,6 @@ public class TestDecryption
List<List<?>> values = ImmutableList.of(columnValues, columnValues);
Slice iek1 = Slices.utf8Slice("iek1");
Slice iek2 = Slices.utf8Slice("iek2");
- Slice dek = Slices.utf8Slice("dek");
DwrfWriterEncryption dwrfWriterEncryption = new DwrfWriterEncryption(
UNKNOWN,
ImmutableList.of(
@@ -312,7 +310,6 @@ public class TestDecryption
.collect(toList()));
Slice iek = Slices.utf8Slice("iek");
- Slice dek = Slices.utf8Slice("dek");
DwrfWriterEncryption dwrfWriterEncryption = new DwrfWriterEncryption(
UNKNOWN,
ImmutableList.of(
@@ -341,7 +338,6 @@ public class TestDecryption
Type rowType = rowType(BIGINT, BIGINT, BIGINT);
Slice iek1 = Slices.utf8Slice("iek1");
Slice iek2 = Slices.utf8Slice("iek2");
- Slice dek = Slices.utf8Slice("dek");
DwrfWriterEncryption dwrfWriterEncryption = new DwrfWriterEncryption(
UNKNOWN,
ImmutableList.of(
@@ -374,7 +370,7 @@ public class TestDecryption
ImmutableList.of(0, 1, 3));
}
- private void testDecryptionRoundTrip(
+ private static void testDecryptionRoundTrip(
List<Type> types,
List<List<?>> writtenalues,
List<List<?>> readValues,
@@ -406,7 +402,7 @@ public class TestDecryption
}
}
- private void validateFileStatistics(File file, Optional<DwrfWriterEncryption> dwrfWriterEncryption)
+ private static void validateFileStatistics(File file, Optional<DwrfWriterEncryption> dwrfWriterEncryption)
throws IOException
{
OrcDataSource orcDataSource = new FileOrcDataSource(file, new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), new DataSize(1, MEGABYTE), true);
@@ -436,7 +432,7 @@ public class TestDecryption
}
}
- private boolean hasNoTypeStats(DwrfProto.ColumnStatistics columnStatistics)
+ private static boolean hasNoTypeStats(DwrfProto.ColumnStatistics columnStatistics)
{
return !columnStatistics.hasBinaryStatistics()
&& !columnStatistics.hasBucketStatistics()
|
Minor cleanup in TestDecryption
|
prestodb_presto
|
train
|
ac7bf449143915b86cd8cfa67e531bd3a8ba6ee4
|
diff --git a/core-bundle/src/Resources/contao/library/Contao/Automator.php b/core-bundle/src/Resources/contao/library/Contao/Automator.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/library/Contao/Automator.php
+++ b/core-bundle/src/Resources/contao/library/Contao/Automator.php
@@ -98,7 +98,7 @@ class Automator extends \System
$objDatabase->execute("TRUNCATE TABLE tl_version");
// Add a log entry
- $this->log('Purged the undo table', __METHOD__, TL_CRON);
+ $this->log('Purged the version table', __METHOD__, TL_CRON);
}
|
[Core] Add a correct log entry when purging the version table
|
contao_contao
|
train
|
453071ce348d93a6643900dd5175ec3ba1c5c918
|
diff --git a/src/cartesian/XAxis.js b/src/cartesian/XAxis.js
index <HASH>..<HASH> 100644
--- a/src/cartesian/XAxis.js
+++ b/src/cartesian/XAxis.js
@@ -50,6 +50,19 @@ class XAxis extends Component {
'threshold']),
PropTypes.func,
]),
+ label: PropTypes.oneOfType([
+ PropTypes.number, PropTypes.string, PropTypes.func, PropTypes.element,
+ ]),
+ tick: PropTypes.oneOfType([
+ PropTypes.bool, PropTypes.func, PropTypes.object, PropTypes.element,
+ ]),
+ axisLine: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
+ tickLine: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
+ minTickGap: PropTypes.number,
+ tickSize: PropTypes.number,
+ interval: PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf([
+ 'preserveStart', 'preserveEnd', 'preserveStartEnd',
+ ])]),
};
static defaultProps = {
diff --git a/src/cartesian/YAxis.js b/src/cartesian/YAxis.js
index <HASH>..<HASH> 100644
--- a/src/cartesian/YAxis.js
+++ b/src/cartesian/YAxis.js
@@ -50,6 +50,19 @@ class YAxis extends Component {
'threshold']),
PropTypes.func,
]),
+ label: PropTypes.oneOfType([
+ PropTypes.number, PropTypes.string, PropTypes.func, PropTypes.element,
+ ]),
+ tick: PropTypes.oneOfType([
+ PropTypes.bool, PropTypes.func, PropTypes.object, PropTypes.element,
+ ]),
+ axisLine: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
+ tickLine: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]),
+ minTickGap: PropTypes.number,
+ tickSize: PropTypes.number,
+ interval: PropTypes.oneOfType([PropTypes.number, PropTypes.oneOf([
+ 'preserveStart', 'preserveEnd', 'preserveStartEnd',
+ ])]),
};
static defaultProps = {
|
Adding missing propTypes to XAxis+YAxis
label, tick, axisLine, tickLine, minTickGap, tickSize, interval - these
are in the online docs but were missing. Copied from their definitions
in CartesianAxis.
|
recharts_recharts
|
train
|
9eb574b6c431ad251ba2a8f6582a60219ce9f47a
|
diff --git a/src/packet/public_key.js b/src/packet/public_key.js
index <HASH>..<HASH> 100644
--- a/src/packet/public_key.js
+++ b/src/packet/public_key.js
@@ -195,7 +195,7 @@ PublicKey.prototype.getFingerprint = function () {
* @return {Promise<Object} An object of the form {algorithm: String, bits:int, curve:String}
*/
PublicKey.prototype.getAlgorithmInfo = function () {
- var result = {};
+ const result = {};
result.algorithm = this.algorithm;
if (this.params[0] instanceof type_mpi) {
result.bits = this.params[0].byteLength() * 8;
|
Hotfix - change var for const
|
openpgpjs_openpgpjs
|
train
|
3555fa99d1ae2981573c7f178bc5571556e89171
|
diff --git a/client/actions/show-heartbeat/index.js b/client/actions/show-heartbeat/index.js
index <HASH>..<HASH> 100644
--- a/client/actions/show-heartbeat/index.js
+++ b/client/actions/show-heartbeat/index.js
@@ -1,6 +1,6 @@
import { Action, registerAction } from '../utils';
-const VERSION = 54; // Increase when changed.
+const VERSION = 55; // Increase when changed.
const LAST_SHOWN_DELAY = 1000 * 60 * 60 * 24 * 7; // 7 days
@@ -149,7 +149,10 @@ export default class ShowHeartbeatAction extends Action {
message,
engagementButtonLabel,
thanksMessage,
- postAnswerUrl: this.annotatePostAnswerUrl({ url: postAnswerUrl, userId }),
+ postAnswerUrl: this.annotatePostAnswerUrl({
+ url: postAnswerUrl,
+ userId,
+ }),
learnMoreMessage,
learnMoreUrl,
flowId: flow.id,
@@ -196,6 +199,20 @@ export default class ShowHeartbeatAction extends Action {
return Number.isNaN(lastShown) ? null : lastShown;
}
+ getGAParams() {
+ let message = this.recipe.arguments.message || '';
+ // remove spaces
+ message = message.replace(/\s+/g, '');
+ // url-ify
+ message = encodeURIComponent(message);
+
+ return {
+ utm_source: 'firefox',
+ utm_medium: this.recipe.action, // action name
+ utm_campaign: message, // 'shortenedmesssagetext'
+ };
+ }
+
annotatePostAnswerUrl({ url, userId }) {
// Don't bother with empty URLs.
if (!url) {
@@ -210,6 +227,8 @@ export default class ShowHeartbeatAction extends Action {
isDefaultBrowser: this.client.isDefaultBrowser ? 1 : 0,
searchEngine: this.client.searchEngine,
syncSetup: this.client.syncSetup ? 1 : 0,
+ // Google Analytics parameters
+ ...this.getGAParams(),
};
// if a userId is given,
|
Update show-heartbeat to include GA vars in post URL
|
mozilla_normandy
|
train
|
61af97c0784c1bb3c417895bf09d7a34ac599e1c
|
diff --git a/skl_groups/features.py b/skl_groups/features.py
index <HASH>..<HASH> 100644
--- a/skl_groups/features.py
+++ b/skl_groups/features.py
@@ -139,8 +139,10 @@ class Features(object):
self.n_pts = n_pts
self.stacked_features = bags
self._boundaries = bounds = np.r_[0, np.cumsum(n_pts)]
- self.features = [bags[bounds[i-1]:bounds[i]]
- for i in xrange(1, len(bounds))]
+
+ self.features = np.empty(len(n_pts), object)
+ self.features[:] = [bags[bounds[i-1]:bounds[i]]
+ for i in xrange(1, len(bounds))]
else:
if n_pts is not None:
@@ -343,10 +345,10 @@ class Features(object):
meta = {k: np.r_[self.meta[k], oth.meta[k]]
for k in self.meta if k in oth.meta}
oth_features = oth.features
- elif isinstance(oth, list) or \
- (isinstance(oth, np.ndarray) and oth.dtype.kind == 'o'):
+ elif isinstance(oth, list):
meta = {}
- oth_features = oth
+ oth_features = np.empty(len(oth), object)
+ oth_features[:] = oth
else:
return NotImplemented
@@ -354,10 +356,13 @@ class Features(object):
stack=False, copy=True, **meta)
def __radd__(self, oth):
- if isinstance(oth, list) or \
- (isinstance(oth, np.ndarray) and oth.dtype.kind == 'o'):
- return Features(np.r_[oth, self.features], stack=False, copy=True)
- return NotImplemented
+ if isinstance(oth, list):
+ oth_features = np.empty(len(oth), object)
+ oth_features[:] = oth
+ else:
+ return NotImplemented
+ return Features(np.r_[oth_features, self.features],
+ stack=False, copy=True)
############################################################################
## Others
diff --git a/skl_groups/tests/test_features.py b/skl_groups/tests/test_features.py
index <HASH>..<HASH> 100644
--- a/skl_groups/tests/test_features.py
+++ b/skl_groups/tests/test_features.py
@@ -198,12 +198,21 @@ def test_feats_add():
assert not plus_list.meta
assert np.all(plus_list[16] == bags[16])
+ plus_singlelist = first_15 + [bags[18]]
+ assert np.all(plus_singlelist[15] == bags[18])
+
rplus_list = bags[15:] + first_15
assert np.all(rplus_list[0] == bags[15])
+ rplus_singlelist = [bags[15]] + first_15
+ assert np.all(rplus_singlelist[0] == bags[15])
+ assert rplus_singlelist[1:] == first_15.bare()
+
wrong_type(lambda: first_15 + 12)
wrong_type(lambda: 12 + first_15)
+ assert_raises(ValueError, lambda: first_15 + np.asarray(bags))
+
################################################################################
if __name__ == '__main__':
|
Features: make .features an object array, fix __add__
Took away code for adding to an object array, because numpy tries to do
it and then complains that it can't broadcast.
|
dougalsutherland_skl-groups
|
train
|
a91ecec8db8b0c0846cd5f5c0e2058b594ffcc1f
|
diff --git a/lib/bolt/cli.rb b/lib/bolt/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/bolt/cli.rb
+++ b/lib/bolt/cli.rb
@@ -62,7 +62,7 @@ END
Usage: bolt file <action> [options]
Available actions are:
- upload Upload a local file
+ upload <src> <dest> Upload local file <src> to <dest> on each node
Available options are:
END
@@ -195,7 +195,9 @@ END
src = options[:object]
dest = options[:leftovers].first
- unless file_exist?(src)
+ if dest.nil?
+ raise Bolt::CLIError, "A destination path must be specified"
+ elsif !file_exist?(src)
raise Bolt::CLIError, "The source file '#{src}' does not exist"
end
|
(TASKS-<I>) Validate upload destination
Validate upload destination is not nil and update usage for file upload to make
it clear that the syntax is different than scp.
|
puppetlabs_bolt
|
train
|
79e61ea8b8b80b641c9d51054b8f14ae8f8859ef
|
diff --git a/matrix_client/client.py b/matrix_client/client.py
index <HASH>..<HASH> 100644
--- a/matrix_client/client.py
+++ b/matrix_client/client.py
@@ -26,22 +26,13 @@ logger = logging.getLogger(__name__)
# Cache constants used when instantiating Matrix Client to specify level of caching
-class Enum(object):
- def __init__(self, **kwargs):
- self._values = kwargs.values()
- for k, v in kwargs.items():
- setattr(self, k, v)
+class CACHE(int):
+ pass
- def __contains__(self, item):
- return item in self._values
-
-class Cache(Enum):
- def __init__(self):
- Enum.__init__(self, NONE=-1, SOME=0, ALL=1)
-
-
-CACHE = Cache()
+CACHE.NONE = CACHE(-1)
+CACHE.SOME = CACHE(0)
+CACHE.ALL = CACHE(1)
class MatrixClient(object):
@@ -132,7 +123,7 @@ class MatrixClient(object):
self.invite_listeners = []
self.left_listeners = []
self.ephemeral_listeners = []
- if cache_level in CACHE:
+ if isinstance(cache_level, CACHE):
self._cache_level = cache_level
else:
self._cache_level = CACHE.ALL
|
Simplify yet enhance the Enum replacement
So we can have full instances of our enum class instead of bare ints.
|
matrix-org_matrix-python-sdk
|
train
|
6f43d0223fec0b6b7673dd57ac8de095dc8151aa
|
diff --git a/src/CoandaCMS/Coanda/Urls/Repositories/Eloquent/EloquentUrlRepository.php b/src/CoandaCMS/Coanda/Urls/Repositories/Eloquent/EloquentUrlRepository.php
index <HASH>..<HASH> 100644
--- a/src/CoandaCMS/Coanda/Urls/Repositories/Eloquent/EloquentUrlRepository.php
+++ b/src/CoandaCMS/Coanda/Urls/Repositories/Eloquent/EloquentUrlRepository.php
@@ -140,7 +140,7 @@ class EloquentUrlRepository implements \CoandaCMS\Coanda\Urls\Repositories\UrlRe
private function updateSubTree($slug, $new_slug)
{
- $this->model->where('slug', 'like', $slug . '/%')->update(['slug' => \DB::raw("REPLACE(slug, '" . $slug . "', '" . $new_slug . "')")]);
+ $this->model->where('slug', 'like', $slug . '/%')->update(['slug' => \DB::raw("REPLACE(slug, '" . $slug . "/', '" . $new_slug . "/')")]);
}
public function delete($for, $for_id)
|
Bugfix - include the / as part of the replace statment.
|
CoandaCMS_coanda-core
|
train
|
e815e8f55cf9a82447c70d0b536042e6de095f77
|
diff --git a/lib/decode.js b/lib/decode.js
index <HASH>..<HASH> 100644
--- a/lib/decode.js
+++ b/lib/decode.js
@@ -88,26 +88,27 @@ decode.list = function() {
decode.integer = function() {
var end = decode.find( 0x65 )
- var number = decode.data.toString('ascii', decode.position+1, end )
+ var number = decode.data.toString( 'ascii', decode.position + 1, end )
decode.position += end + 1 - decode.position
- return parseInt( number )
+ return parseInt( number, 10 )
+
}
decode.bytes = function() {
var sep = decode.find( 0x3A )
- var length = parseInt(decode.data.toString('ascii', decode.position, sep ), 10)
+ var length = parseInt( decode.data.toString( 'ascii', decode.position, sep ), 10 )
var end = ++sep + length
decode.position += end - decode.position
return decode.encoding
- ? decode.data.toString(decode.encoding, sep, end )
- : decode.data.slice( sep, end )
+ ? decode.data.toString( decode.encoding, sep, end )
+ : decode.data.slice( sep, end )
}
-// Expose
+// Exports
module.exports = decode
|
Updated lib/decode: Cosmetics
|
themasch_node-bencode
|
train
|
de407a62f9e7ba71fa8353f2479fe48d65dde7d3
|
diff --git a/WordPress/Sniffs/Arrays/ArrayDeclarationSpacingSniff.php b/WordPress/Sniffs/Arrays/ArrayDeclarationSpacingSniff.php
index <HASH>..<HASH> 100644
--- a/WordPress/Sniffs/Arrays/ArrayDeclarationSpacingSniff.php
+++ b/WordPress/Sniffs/Arrays/ArrayDeclarationSpacingSniff.php
@@ -11,6 +11,7 @@ namespace WordPressCS\WordPress\Sniffs\Arrays;
use WordPressCS\WordPress\Sniff;
use PHP_CodeSniffer\Util\Tokens;
+use PHPCSUtils\Utils\Arrays;
use PHPCSUtils\Utils\PassedParameters;
/**
@@ -99,7 +100,7 @@ class ArrayDeclarationSpacingSniff extends Sniff {
/*
* Determine the array opener & closer.
*/
- $array_open_close = $this->find_array_open_close( $stackPtr );
+ $array_open_close = Arrays::getOpenClose( $this->phpcsFile, $stackPtr );
if ( false === $array_open_close ) {
// Array open/close could not be determined.
return;
@@ -214,7 +215,7 @@ class ArrayDeclarationSpacingSniff extends Sniff {
// Skip passed any nested arrays.
if ( isset( $this->targets[ $this->tokens[ $ptr ]['code'] ] ) ) {
- $nested_array_open_close = $this->find_array_open_close( $ptr );
+ $nested_array_open_close = Arrays::getOpenClose( $this->phpcsFile, $ptr );
if ( false === $nested_array_open_close ) {
// Nested array open/close could not be determined.
continue;
diff --git a/WordPress/Sniffs/Arrays/ArrayIndentationSniff.php b/WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
index <HASH>..<HASH> 100644
--- a/WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
+++ b/WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
@@ -12,6 +12,7 @@ namespace WordPressCS\WordPress\Sniffs\Arrays;
use WordPressCS\WordPress\Sniff;
use PHP_CodeSniffer\Util\Tokens;
use PHPCSUtils\BackCompat\Helper;
+use PHPCSUtils\Utils\Arrays;
use PHPCSUtils\Utils\PassedParameters;
/**
@@ -104,7 +105,7 @@ class ArrayIndentationSniff extends Sniff {
/*
* Determine the array opener & closer.
*/
- $array_open_close = $this->find_array_open_close( $stackPtr );
+ $array_open_close = Arrays::getOpenClose( $this->phpcsFile, $stackPtr );
if ( false === $array_open_close ) {
// Array open/close could not be determined.
return;
diff --git a/WordPress/Sniffs/Arrays/CommaAfterArrayItemSniff.php b/WordPress/Sniffs/Arrays/CommaAfterArrayItemSniff.php
index <HASH>..<HASH> 100644
--- a/WordPress/Sniffs/Arrays/CommaAfterArrayItemSniff.php
+++ b/WordPress/Sniffs/Arrays/CommaAfterArrayItemSniff.php
@@ -11,6 +11,7 @@ namespace WordPressCS\WordPress\Sniffs\Arrays;
use WordPressCS\WordPress\Sniff;
use PHP_CodeSniffer\Util\Tokens;
+use PHPCSUtils\Utils\Arrays;
use PHPCSUtils\Utils\PassedParameters;
/**
@@ -63,7 +64,7 @@ class CommaAfterArrayItemSniff extends Sniff {
/*
* Determine the array opener & closer.
*/
- $array_open_close = $this->find_array_open_close( $stackPtr );
+ $array_open_close = Arrays::getOpenClose( $this->phpcsFile, $stackPtr );
if ( false === $array_open_close ) {
// Array open/close could not be determined.
return;
diff --git a/WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php b/WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php
index <HASH>..<HASH> 100644
--- a/WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php
+++ b/WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php
@@ -9,6 +9,7 @@
namespace WordPressCS\WordPress\Sniffs\Arrays;
+use PHPCSUtils\Utils\Arrays;
use PHPCSUtils\Utils\PassedParameters;
use WordPressCS\WordPress\Sniff;
@@ -176,7 +177,7 @@ class MultipleStatementAlignmentSniff extends Sniff {
/*
* Determine the array opener & closer.
*/
- $array_open_close = $this->find_array_open_close( $stackPtr );
+ $array_open_close = Arrays::getOpenClose( $this->phpcsFile, $stackPtr );
if ( false === $array_open_close ) {
// Array open/close could not be determined.
return;
|
Sniff::find_array_open_close(): switch over to the PHPCSUtils version
|
WordPress-Coding-Standards_WordPress-Coding-Standards
|
train
|
f0aaadfd48576c7bcf5cb0e90c45629cedb948a0
|
diff --git a/nicta-ner/src/main/java/nicta/ner/util/Dictionary.java b/nicta-ner/src/main/java/nicta/ner/util/Dictionary.java
index <HASH>..<HASH> 100644
--- a/nicta-ner/src/main/java/nicta/ner/util/Dictionary.java
+++ b/nicta-ner/src/main/java/nicta/ner/util/Dictionary.java
@@ -39,60 +39,56 @@ public final class Dictionary {
*/
private Dictionary() {}
- public static String checkup(String word) {
+ public static String checkup(final String word) {
return dict.get(word);
}
/** This method checks if the word is a plural form. */
- public static boolean isPlural(String _word) {
- String word = _word.toLowerCase();
- String wordStub = null;
+ public static boolean isPlural(final String _word) {
+ final String word = _word.toLowerCase();
// word + s
if (word.endsWith("s")) {
- wordStub = word.substring(0, word.length() - 1);
+ final String wordStub = word.substring(0, word.length() - 1);
if (checkup(wordStub) != null) return true;
}
// word + ed
if (word.endsWith("ed")) {
- wordStub = word.substring(0, word.length() - 2);
+ final String wordStub = word.substring(0, word.length() - 2);
if (checkup(wordStub) != null) return true;
}
// word(-y) + ied
if (word.endsWith("ied")) {
- wordStub = word.substring(0, word.length() - 3) + "y";
+ //noinspection StringConcatenationMissingWhitespace
+ final String wordStub = word.substring(0, word.length() - 3) + "y";
if (checkup(wordStub) != null) return true;
}
return false;
}
- /**
- * This method checks if the word is a past tense word.
- * @param _word
- * @return
- */
- public static boolean isPastTense(String _word) {
- String word = _word.toLowerCase();
- String wordStub = null;
+ /** This method checks if the word is a past tense word. */
+ public static boolean isPastTense(final String _word) {
+ final String word = _word.toLowerCase();
// word(e) + d
if (word.endsWith("d")) {
- wordStub = word.substring(0, word.length() - 1);
+ final String wordStub = word.substring(0, word.length() - 1);
if (checkup(wordStub) != null) return true;
}
// word + ed
if (word.endsWith("ces") || word.endsWith("ses")) {
- wordStub = word.substring(0, word.length() - 2);
+ final String wordStub = word.substring(0, word.length() - 2);
if (checkup(wordStub) != null) return true;
}
// word(-y) + ies
if (word.endsWith("ies")) {
- wordStub = word.substring(0, word.length() - 3) + "y";
+ //noinspection StringConcatenationMissingWhitespace
+ final String wordStub = word.substring(0, word.length() - 3) + "y";
if (checkup(wordStub) != null) return true;
}
|
Final small refactorings of Dictionary.
|
NICTA_nicta-ner
|
train
|
89ac6d3e7759486caeb653a690a9d4e38439290a
|
diff --git a/lib/request.js b/lib/request.js
index <HASH>..<HASH> 100644
--- a/lib/request.js
+++ b/lib/request.js
@@ -6,7 +6,16 @@ const http = require('http')
const https = require('https')
const httpAgent = new http.Agent({ keepAlive: true })
const httpsAgent = new https.Agent({ keepAlive: true })
-const agent = ({ protocol }) => protocol === 'http:' ? httpAgent : httpsAgent
+// Useful to:
+// - accept self-signed certificates
+// - accept certificates that would otherwise generate a UNABLE_TO_VERIFY_LEAF_SIGNATURE error
+const insecureHttpsAgent = new https.Agent({ keepAlive: true, rejectUnauthorized: false })
+const tlsErrorsHosts = new Set([ 'datos.bne.es' ])
+
+const agent = ({ host, protocol }) => {
+ if (tlsErrorsHosts.has(host)) return protocol === 'http:' ? httpAgent : insecureHttpsAgent
+ else return protocol === 'http:' ? httpAgent : httpsAgent
+}
const globalHeaders = require('./request_headers')
const buildHeaders = customHeaders => {
|
request: ignore tls errors for hosts known to produce them
|
maxlath_wikidata-cli
|
train
|
ca98f240402b29486d471ddc8cd9c611baa07d74
|
diff --git a/app/controllers/capcoauth/logout_controller.rb b/app/controllers/capcoauth/logout_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/capcoauth/logout_controller.rb
+++ b/app/controllers/capcoauth/logout_controller.rb
@@ -13,7 +13,7 @@ module Capcoauth
# If request JSON, just return the url in a JSON hash
logout_url = "#{Capcoauth.configuration.capcoauth_url}/users/sign_out"
- if request.format.json?
+ if request.format.json? || request.format.api_json?
render json: { logout_url: logout_url }
else
redirect_to logout_url, notice: 'You have been logged out'
|
JSON check should include api_json? method as well for JSONAPI-vendored content types
|
arcreative_capcoauth-gem
|
train
|
78133b6b938804e122f80765c4d80eb705c22fc6
|
diff --git a/lib/resource.js b/lib/resource.js
index <HASH>..<HASH> 100644
--- a/lib/resource.js
+++ b/lib/resource.js
@@ -61,9 +61,10 @@ function to_json(){
* @example var x = new NAME.Thing({});
*/
Resource = Class(/** @lends module:tastypie.resource.Resource.prototype */{
- mixin:[ Meta, events.EventEmitter, Parentize ]
+ inherits: events.EventEmitter
+ ,mixin:[ Meta, Parentize ]
,meta: {
- name:null
+ resourceName:null
,defaultFormat:'application/json'
,serializer: new serializer()
,collection:'data'
@@ -168,14 +169,13 @@ Resource = Class(/** @lends module:tastypie.resource.Resource.prototype */{
}
debug('dispatching %s %s', httpmethod, action );
//this.is_authenticated( bundle )
- this.emit('before:dispatch', action, method, bundle )
method.call( this, bundle, function(err, data ){
if( err ){
// return this.emit('error', err )
}
// this.respond( null, data, req, res )
- this.emit('dispatch', action, method, data, bundle )
+
})
}
@@ -195,52 +195,21 @@ Resource = Class(/** @lends module:tastypie.resource.Resource.prototype */{
,get_list: function get_list( bundle ){
this._get_list( bundle,function( e, objects ){
- var that = this
- , paginator
- , resource_name
- , collection_name
- , to_be_serialize;
-
- collection_name = this.meta.collection;
- resource_name = this.meta.name
-
- objects = objects || [];
- objects = this.sort( JSON.parse(objects) );
-
- paginator = new this.meta.paginator({
- limit : 25
- , req : bundle.req
- , res : bundle.res
- , collectionName: name
- , objects : objects
+ var that = this;
+ objects = objects || [];
+ objects = this.sort( JSON.parse(objects) );
+ var paginator = new this.meta.paginator({
+ limit:25
+ ,req:bundle.req
+ ,res:bundle.res
+ ,collectionName:this.meta.collection
+ ,objects:objects
});
-
- to_be_serialize = paginator.page();
-
- /**
- * DESCRIPTION
- * @method NAME
- * @param {TYPE} NAME ...
- * @param {TYPE} NAME ...
- * @return
- **/
- this.emit('before:deydration', resource_name, bundle )
-
- to_be_serialize[ collection_name ] = to_be_serialize[ collection_name ].map( function( item ){
- return that.full_dehydrate( item, bundle )
+ var to_be_serialize = paginator.page();
+ to_be_serialize[ this.meta.collection ] = to_be_serialize[ this.meta.collection ].map( function( item ){
+ return that.full_dehydrate( item )
});
-
bundle.data = to_be_serialize
-
- /**
- * DESCRIPTION
- * @method NAME
- * @param {TYPE} NAME ...
- * @param {TYPE} NAME ...
- * @return
- **/
- this.emit('dehydration', resource_name, bundle )
-
return this.respond( bundle )
}.bind( this ));
}
@@ -296,33 +265,22 @@ Resource = Class(/** @lends module:tastypie.resource.Resource.prototype */{
* @param {Object} obj an object to dehydrate object
* @return Object An object containing only serializable data
**/
- ,full_dehydrate: function( obj, bundle ){
- if( typeof obj.toJSON == 'function' ){
- return object.toJSON();
- }
-
- var key, fn, tpl;
- tpl ='dehydrate_';
- for(key in obj){
- fn = this[tpl+key];
- if( fn ){
- obj[key] = fn( bundle )
- }
- }
+ ,full_dehydrate: function( obj ){
+ return obj.toJSON ? obj.toJSON() : obj
}
/**
* Method to generate a response for a bundled request. Will set contnent-type and length headers
* @chainable
* @method module:tastypie.resources.Resource#respond
* @param {Bundle|Object} bundle A bundle or similar object
- * @param {ok|Function} cls An ok function to call to finish the request. Function should accept a response object, and data to send
+ * @param {HttpResponse|Function} cls An HttpResponse function to call to finish the request. Function should accept a response object, and data to send
* @return Resource
**/
,respond: function respond( bundle, cls ){
- cls = cls || http.ok;
+ cls = cls || http.HttpResponse;
var format = this.format( bundle, this.meta.serializer.types );
- this.emit('before:serialization', this.meta.name, bundle )
+
this.serialize( bundle.data, format, function(err, data ){
bundle.res.set('Content-Type', format);
bundle.res.set('Content-Length', data.length);
@@ -330,7 +288,6 @@ Resource = Class(/** @lends module:tastypie.resource.Resource.prototype */{
bundle.data = err.message;
return this.error( bundle, err );
}
- this.emit('serialization', this.meta.name, data, bundle )
cls( bundle.res, data );
}.bind(this));
@@ -345,7 +302,7 @@ Resource = Class(/** @lends module:tastypie.resource.Resource.prototype */{
* @return
**/
,error: function error( bundle, err, cls ){
- cls = cls || http.badRequest;
+ cls = cls || http.BadRequest;
var format = this.format( bundle.req, bundle.res, this.meta.serializer.types );
this.serialize({
|
make the resource an old style class / factory thing
|
node-tastypie_tastypie
|
train
|
0ca31bb5d75359fe798b5ead9bbc3fd88cf05616
|
diff --git a/bundles/org.eclipse.orion.client.editor/web/orion/editor/edit.js b/bundles/org.eclipse.orion.client.editor/web/orion/editor/edit.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.editor/web/orion/editor/edit.js
+++ b/bundles/org.eclipse.orion.client.editor/web/orion/editor/edit.js
@@ -10,7 +10,7 @@
* IBM Corporation - initial API and implementation
*******************************************************************************/
-/*globals define window document */
+/*globals define */
define('orion/editor/edit', [
@@ -42,6 +42,8 @@ define('orion/editor/edit', [
/** @private */
function getTextFromElement(element) {
+ var document = element.ownerDocument;
+ var window = document.defaultView || document.parentWindow;
if (!window.getSelection) {
return element.innerText || element.textContent;
}
@@ -76,13 +78,18 @@ define('orion/editor/edit', [
}
/** @private */
- function mergeOptions(parent, defaultOptions) {
- var options = {};
- for (var p in defaultOptions) {
- if (defaultOptions.hasOwnProperty(p)) {
- options[p] = defaultOptions[p];
+ function merge(obj1, obj2) {
+ for (var p in obj2) {
+ if (obj2.hasOwnProperty(p)) {
+ obj1[p] = obj2[p];
}
}
+ }
+
+ /** @private */
+ function mergeOptions(parent, defaultOptions) {
+ var options = {};
+ merge(options, defaultOptions);
for (var attr, j = 0, attrs = parent.attributes, l = attrs.length; j < l; j++) {
attr = attrs.item(j);
var key = optionName(attr.nodeName);
@@ -111,7 +118,6 @@ define('orion/editor/edit', [
return parseInt(height, 10) || 0;
}
- var editAll;
/**
* @class This object describes the options for <code>edit</code>.
* @name orion.editor.EditOptions
@@ -146,7 +152,16 @@ define('orion/editor/edit', [
}
if (!parent) {
if (options.className) {
- return editAll(options);
+ var parents = (options.document || document).getElementsByClassName(options.className);
+ if (parents) {
+ options.className = undefined;
+ var editors = [];
+ for (var i = 0; i < parents.length; i++) {
+ options.parent = parents[i];
+ editors.push(edit(options));
+ }
+ return editors;
+ }
}
}
if (!parent) { throw "no parent"; } //$NON-NLS-0$
@@ -259,22 +274,14 @@ define('orion/editor/edit', [
}
return editor;
}
-
- editAll = function (defaultOptions) {
- var elements = document.getElementsByClassName(defaultOptions.className);
- var editors;
- if (elements) {
- editors = [];
- defaultOptions.className = undefined;
- for (var i = 0; i < elements.length; i++) {
- var element = elements[i];
- defaultOptions.parent = element;
- var editor = edit(defaultOptions);
- editors.push(editor);
- }
+
+ var editorNS = this.orion.editor;
+ if (editorNS) {
+ for (var i = 0; i < arguments.length; i++) {
+ merge(editorNS, arguments[i]);
}
- return editors;
- };
+ }
return edit;
-});
\ No newline at end of file
+});
+
|
do not reference window/document globals. Add the editor API to the global name space.
|
eclipse_orion.client
|
train
|
aa51cea25173b387201c833e34299803a226d3b5
|
diff --git a/generators/service/templates/model/knex-user.js b/generators/service/templates/model/knex-user.js
index <HASH>..<HASH> 100644
--- a/generators/service/templates/model/knex-user.js
+++ b/generators/service/templates/model/knex-user.js
@@ -7,18 +7,24 @@
module.exports = function (app) {
const db = app.get('knexClient');
- db.schema.createTableIfNotExists('<%= kebabName %>', table => {
- table.increments('id');
- <% if(authentication.strategies.indexOf('local') !== -1) { %>
- table.string('email').unique();
- table.string('password');
- <% } %>
- <% authentication.oauthProviders.forEach(provider => { %>
- table.string('<%= provider.name %>Id');
- <% }); %>
- })
- .then(() => console.log('Updated <%= kebabName %> table'))
- .catch(e => console.error('Error updating <%= kebabName %> table', e));
+ db.schema.hasTable('<%= kebabName %>').then(exists => {
+ if(!exists) {
+ db.schema.createTable('<%= kebabName %>', table => {
+ table.increments('id');
+ <% if(authentication.strategies.indexOf('local') !== -1) { %>
+ table.string('email').unique();
+ table.string('password');
+ <% } %>
+ <% authentication.oauthProviders.forEach(provider => { %>
+ table.string('<%= provider.name %>Id');
+ <% }); %>
+ })
+ .then(
+ () => console.log('Updated <%= kebabName %> table'),
+ e => console.error('Error updating <%= kebabName %> table', e)
+ );
+ }
+ });
return db;
};
|
Update Knex user model to create table properly (#<I>)
|
feathersjs_generator-feathers
|
train
|
a470921db90688c38ca628984be82ea6ee8259bc
|
diff --git a/src/components/DatePicker.jsx b/src/components/DatePicker.jsx
index <HASH>..<HASH> 100644
--- a/src/components/DatePicker.jsx
+++ b/src/components/DatePicker.jsx
@@ -49,7 +49,7 @@ export default class DatePicker extends Component {
month: React.PropTypes.number,
year: React.PropTypes.number,
showOtherMonthDate: React.PropTypes.bool,
- styleWeekendOn: React.PropTypes.oneOf([-1, 0, 1, 2, 3, 4, 5, 6]),
+ styleWeekend: React.PropTypes.bool,
renderDay: React.PropTypes.func,
onFocus: React.PropTypes.func,
onBlur: React.PropTypes.func,
@@ -146,7 +146,7 @@ export default class DatePicker extends Component {
readOnly: false,
locale: 'en',
showOtherMonthDate: true,
- styleWeekendOn: -1
+ styleWeekend: false
};
/**
@@ -620,11 +620,11 @@ export default class DatePicker extends Component {
<div style={ weekHeaderStyle }>
{
map(dayNames, (dayAbbr, index) => {
- let weekendIndex = ((7 - this.localeData.firstDay) % 7) + this.props.styleWeekendOn;
+ let weekendIndex = ((7 - this.localeData.firstDay) % 7) + this.localeData.weekEnd;
weekendIndex = this.localeData.isRTL ? 6 - weekendIndex : weekendIndex;
return (
<span key={ 'dayAbbr-' + index }
- style={ (index === weekendIndex && this.props.styleWeekendOn >= 0) ? weekendLblStyle : dayLblStyle }
+ style={ (this.props.styleWeekend && index === weekendIndex) ? weekendLblStyle : dayLblStyle }
className={ unionClassNames(this.props.dayLblClassName, this.pseudoStyleIds.dayLblStyleId) }>
{ dayAbbr }
</span>
@@ -673,7 +673,7 @@ export default class DatePicker extends Component {
}
}
- if (currentDate.getDay() === this.props.styleWeekendOn) {
+ if (this.props.styleWeekend && currentDate.getDay() === this.localeData.weekEnd) {
dayStyle = extend(dayStyle, style.weekendStyle, this.props.weekendStyle);
}
@@ -1073,4 +1073,5 @@ export default class DatePicker extends Component {
* 2. Docs
* 3. Date range
* 4. Date input
+ * 5. Should weekend data put in internationalization file with a sensible default ?
**/
diff --git a/src/config/datePicker.js b/src/config/datePicker.js
index <HASH>..<HASH> 100644
--- a/src/config/datePicker.js
+++ b/src/config/datePicker.js
@@ -8,6 +8,7 @@ const datePickerConfig = {
'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
dayNamesMin: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
firstDay: 1,
+ weekEnd: 0,
isRTL: false
},
'ar': {
@@ -15,6 +16,7 @@ const datePickerConfig = {
'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'],
dayNamesMin: ['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'],
firstDay: 6,
+ weekEnd: 5,
isRTL: true
},
'he': {
@@ -22,6 +24,7 @@ const datePickerConfig = {
'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'],
dayNamesMin: ['א\'', 'ב\'', 'ג\'', 'ד\'', 'ה\'', 'ו\'', 'שבת'],
firstDay: 0,
+ weekEnd: 6,
isRTL: true
},
'fr': {
@@ -29,6 +32,7 @@ const datePickerConfig = {
'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'],
dayNamesMin: ['D', 'L', 'M', 'M', 'J', 'V', 'S'],
firstDay: 1,
+ weekEnd: 0,
isRTL: false
},
'zh-CN': {
@@ -36,6 +40,7 @@ const datePickerConfig = {
'七月', '八月', '九月', '十月', '十一月', '十二月'],
dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
firstDay: 1,
+ weekEnd: 0,
isRTL: false
}
}
diff --git a/src/utils/date-helpers.js b/src/utils/date-helpers.js
index <HASH>..<HASH> 100644
--- a/src/utils/date-helpers.js
+++ b/src/utils/date-helpers.js
@@ -41,6 +41,7 @@ export function getLocaleData(locale) {
'July', 'August', 'September', 'October', 'November', 'December'];
localeResult.dayNamesMin = (lData && lData.dayNamesMin) ? lData.dayNamesMin : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
localeResult.firstDay = (lData && lData.firstDay) ? lData.firstDay : 0;
+ localeResult.weekEnd = (lData && lData.weekEnd) ? lData.weekEnd : 0;
localeResult.isRTL = (lData && lData.isRTL) ? lData.isRTL : false;
return localeResult;
}
|
feat(DatePicker): moving weekend info to locale data
|
nikgraf_belle
|
train
|
a24a1ab9f4be1820bdaa26092ef36dd258ac8b5f
|
diff --git a/grakn-engine/src/main/java/ai/grakn/engine/GraknEngineServer.java b/grakn-engine/src/main/java/ai/grakn/engine/GraknEngineServer.java
index <HASH>..<HASH> 100644
--- a/grakn-engine/src/main/java/ai/grakn/engine/GraknEngineServer.java
+++ b/grakn-engine/src/main/java/ai/grakn/engine/GraknEngineServer.java
@@ -138,6 +138,19 @@ public class GraknEngineServer {
public static void stopHTTP() {
Spark.stop();
+
+ // Block until server is truly stopped
+ // This occurs when there is no longer a port assigned to the Spark server
+ boolean running = true;
+ while (running) {
+ try {
+ Spark.port();
+ }
+ catch(IllegalStateException e){
+ LOG.debug("Spark server has been stopped");
+ running = false;
+ }
+ }
}
public static void stopCluster() {
diff --git a/grakn-test/src/test/java/ai/grakn/test/GraknTestEnv.java b/grakn-test/src/test/java/ai/grakn/test/GraknTestEnv.java
index <HASH>..<HASH> 100644
--- a/grakn-test/src/test/java/ai/grakn/test/GraknTestEnv.java
+++ b/grakn-test/src/test/java/ai/grakn/test/GraknTestEnv.java
@@ -114,10 +114,6 @@ public abstract class GraknTestEnv {
static void stopHTTP(){
if(HTTP_RUNNING.compareAndSet(true, false)) {
GraknEngineServer.stopHTTP();
- // The Spark framework we are using kicks off a shutdown process in a separate
- // thread and there is not way to detect when it is finished. The only option
- // we have is to "wait a while" (Boris).
- try {Thread.sleep(5000);} catch(InterruptedException ex) { Log.info("Thread sleep interrupted."); }
}
}
|
Wait until Spark server truly stops wehn shutting down (#<I>)
|
graknlabs_grakn
|
train
|
63f0ba770dbe79ae7838ce8491c4b639c4d8c941
|
diff --git a/remoto/connection.py b/remoto/connection.py
index <HASH>..<HASH> 100644
--- a/remoto/connection.py
+++ b/remoto/connection.py
@@ -8,14 +8,16 @@ from .lib import execnet
class Connection(object):
- def __init__(self, hostname, logger=None, sudo=False, threads=1, eager=True):
- self.hostname = hostname
+ def __init__(self, hostname, logger=None, sudo=False, threads=1, eager=True, detect_sudo=False):
self.sudo = sudo
+ self.hostname = hostname
self.logger = logger or FakeRemoteLogger()
self.remote_module = None
self.channel = None
self.global_timeout = None # wait for ever
if eager:
+ if detect_sudo:
+ self.sudo = self._detect_sudo()
self.gateway = self._make_gateway(hostname)
def _make_gateway(self, hostname):
@@ -23,9 +25,38 @@ class Connection(object):
self._make_connection_string(hostname)
)
- def _make_connection_string(self, hostname, _needs_ssh=None):
+ def _detect_sudo(self, _execnet=None):
+ """
+ ``sudo`` detection has to create a different connection to the remote
+ host so that we can reliably ensure that ``getuser()`` will return the
+ right information.
+
+ After getting the user info it closes the connection and returns
+ a boolean
+ """
+ exc = _execnet or execnet
+ gw = exc.makegateway(
+ self._make_connection_string(self.hostname, use_sudo=False)
+ )
+
+ channel = gw.remote_exec(
+ 'import getpass; channel.send(getpass.getuser())'
+ )
+
+ result = channel.receive()
+ gw.exit()
+
+ if result == 'root':
+ return False
+ self.logger.debug('connection detected need for sudo')
+ return True
+
+ def _make_connection_string(self, hostname, _needs_ssh=None, use_sudo=None):
_needs_ssh = _needs_ssh or needs_ssh
- interpreter = 'sudo python' if self.sudo else 'python'
+ if use_sudo is not None:
+ interpreter = 'sudo python' if use_sudo else 'python'
+ else:
+ interpreter = 'sudo python' if self.sudo else 'python'
if _needs_ssh(hostname):
return 'ssh=%s//python=%s' % (hostname, interpreter)
return 'popen//python=%s' % interpreter
|
create a sudo detection method to help better detect a need for sudo
Closes #7
|
alfredodeza_remoto
|
train
|
e3511a17b66fc1b1878b363e07ac449ded0290b6
|
diff --git a/java/client/test/org/openqa/selenium/WindowSwitchingTest.java b/java/client/test/org/openqa/selenium/WindowSwitchingTest.java
index <HASH>..<HASH> 100644
--- a/java/client/test/org/openqa/selenium/WindowSwitchingTest.java
+++ b/java/client/test/org/openqa/selenium/WindowSwitchingTest.java
@@ -123,10 +123,11 @@ public class WindowSwitchingTest extends AbstractDriverTestCase {
driver.findElement(By.name("windowThree")).click();
driver.switchTo().window("result");
+ int currentWindowHandles = driver.getWindowHandles().size();
try {
driver.findElement(By.id("close")).click();
- Set<String> allHandles = waitFor(windowHandleCountToBe(1));
+ Set<String> allHandles = waitFor(windowHandleCountToBe(currentWindowHandles - 1));
assertEquals(1, allHandles.size());
} finally {
|
EranMes: Making the window switching test slightly more accurate.
r<I>
|
SeleniumHQ_selenium
|
train
|
ff35cd4678ecde7c93b69c778986769ce62105e7
|
diff --git a/upload/catalog/model/catalog/product.php b/upload/catalog/model/catalog/product.php
index <HASH>..<HASH> 100644
--- a/upload/catalog/model/catalog/product.php
+++ b/upload/catalog/model/catalog/product.php
@@ -306,7 +306,7 @@ class ModelCatalogProduct extends Model {
public function getPopularProducts($limit) {
$product_data = array();
- $query = $this->db->query("SELECT p.product_id FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "' ORDER BY p.viewed, p.date_added DESC LIMIT " . (int)$limit);
+ $query = $this->db->query("SELECT p.product_id FROM " . DB_PREFIX . "product p LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) WHERE p.status = '1' AND p.date_available <= NOW() AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "' ORDER BY p.viewed DESC, p.date_added DESC LIMIT " . (int)$limit);
foreach ($query->rows as $result) {
$product_data[$result['product_id']] = $this->getProduct($result['product_id']);
|
fix for #<I>, because mysql "order by" default is ASC.
|
opencart_opencart
|
train
|
3b11d251703d355c3334f61b8af4753426d6014a
|
diff --git a/core/server/services/mega/mega.js b/core/server/services/mega/mega.js
index <HASH>..<HASH> 100644
--- a/core/server/services/mega/mega.js
+++ b/core/server/services/mega/mega.js
@@ -48,7 +48,7 @@ async function listener(model, options) {
return;
}
- if (!post.get('send_email_when_published')) {
+ if (!model.get('send_email_when_published')) {
return;
}
|
Fixed check for send_email_when_published
no-issue
|
TryGhost_Ghost
|
train
|
7a65099b18eb5f3da3d1f8949c8e35b46be83911
|
diff --git a/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Registration.java b/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Registration.java
index <HASH>..<HASH> 100644
--- a/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Registration.java
+++ b/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/Registration.java
@@ -55,7 +55,10 @@ public class Registration {
OptionBuilder<DatasetRepository> repoBuilder) {
REPO_PATTERNS.put(repoPattern, repoBuilder);
DATASET_PATTERNS.put(datasetPattern, repoBuilder);
- REPO_TO_DATASET_PATTERNS.put(repoPattern, datasetPattern);
+ // the first dataset pattern for a repository pattern is always used
+ if (!REPO_TO_DATASET_PATTERNS.containsKey(repoPattern)) {
+ REPO_TO_DATASET_PATTERNS.put(repoPattern, datasetPattern);
+ }
}
public static Pair<URIPattern, Map<String, String>> lookupPatternByRepoUri(URI uri) {
|
CDK-<I>: Use first dataset URI as canonical form.
This updates the repository pattern to dataset pattern mapping so that
new dataset URIs for a repository URI will not replace existing ones.
The result is that when a repository URI is looked up by URIBuilder to
get the corresponding dataset URI pattern, the first registered pattern
will be returned rather than the last. This makes registration produce
URIs in the form expected with existing precedence (patterns registered
first are matched first).
|
kite-sdk_kite
|
train
|
31be68c50bae1ec09e716af8be43338225e4d6f2
|
diff --git a/OAuth/ResourceOwner/FacebookResourceOwner.php b/OAuth/ResourceOwner/FacebookResourceOwner.php
index <HASH>..<HASH> 100644
--- a/OAuth/ResourceOwner/FacebookResourceOwner.php
+++ b/OAuth/ResourceOwner/FacebookResourceOwner.php
@@ -81,10 +81,10 @@ class FacebookResourceOwner extends GenericOAuth2ResourceOwner
parent::configureOptions($resolver);
$resolver->setDefaults(array(
- 'authorization_url' => 'https://www.facebook.com/dialog/oauth',
- 'access_token_url' => 'https://graph.facebook.com/oauth/access_token',
- 'revoke_token_url' => 'https://graph.facebook.com/me/permissions',
- 'infos_url' => 'https://graph.facebook.com/me',
+ 'authorization_url' => 'https://www.facebook.com/v2.0/dialog/oauth',
+ 'access_token_url' => 'https://graph.facebook.com/v2.0/oauth/access_token',
+ 'revoke_token_url' => 'https://graph.facebook.com/v2.0/me/permissions',
+ 'infos_url' => 'https://graph.facebook.com/v2.0/me',
'use_commas_in_scope' => true,
|
Use new graph address for FacebookResourceOwner
|
hwi_HWIOAuthBundle
|
train
|
0b4f6eb759fdfb6b4f2b828e7b7f6f0920663350
|
diff --git a/src/ox_modules/module-pdf.js b/src/ox_modules/module-pdf.js
index <HASH>..<HASH> 100644
--- a/src/ox_modules/module-pdf.js
+++ b/src/ox_modules/module-pdf.js
@@ -13,6 +13,7 @@
import OxError from '../errors/OxygenError';
const errHelper = require('../errors/helper');
+const path = require('path');
var pdfreader = require('pdfreader');
var deasync = require('deasync');
@@ -52,14 +53,14 @@ function checkRows(searchStr, rows) {
return result;
}
-function assertion(path, text, pageNum = 0){
+function assertion(pdfFilePath, text, pageNum = 0){
let rows = {}; // indexed by y-position
let currentPage = 1;
return new Promise(function(resolve, reject) {
const searchStr = text.replace(/\s/g, '');
- new pdfreader.PdfReader().parseFileItems(path, function(
+ new pdfreader.PdfReader().parseFileItems(pdfFilePath, function(
err,
item
) {
@@ -128,7 +129,7 @@ function assertion(path, text, pageNum = 0){
});
}
-function count(path, text, pageNum = 0){
+function count(pdfFilePath, text, pageNum = 0){
let rows = {}; // indexed by y-position
let currentPage = 1;
let totalResult = 0;
@@ -136,7 +137,7 @@ function count(path, text, pageNum = 0){
return new Promise(function(resolve, reject) {
const searchStr = text.replace(/\s/g, '');
- new pdfreader.PdfReader().parseFileItems(path, function(
+ new pdfreader.PdfReader().parseFileItems(pdfFilePath, function(
err,
item
) {
@@ -232,7 +233,9 @@ function validateMessage(arg, name) {
}
}
-module.exports = function() {
+module.exports = function(options, context, rs, logger, modules, services) {
+ this.options = options;
+
module.isInitialized = function() {
return true;
};
@@ -240,21 +243,23 @@ module.exports = function() {
/**
* @summary Asserts that text is present in a PDF file
* @function assert
- * @param {String} path - Absolute path to the PDF file.
+ * @param {String} pdfFilePath - Absolute path to the PDF file.
* @param {String} text - Text to assert.
* @param {Number=} pageNum - Page number.
* @param {String=} message - Message to throw if assertion fails.
*/
- module.assert = function(path, text, pageNum = null, message = null) {
- validateString(path, 'path');
+ module.assert = function(pdfFilePath, text, pageNum = null, message = null) {
+ validateString(pdfFilePath, 'pdfFilePath');
validateString(text, 'text');
validatePageNum(pageNum, 'pageNum');
validateMessage(message, 'message');
-
+ // resolve relative file path
+ pdfFilePath = path.resolve(this.options.cwd, pdfFilePath);
+
try {
let actual = null;
const expected = true;
- assertion(path, text, pageNum).then(
+ assertion(pdfFilePath, text, pageNum).then(
result => {
actual = result;
},
@@ -290,13 +295,13 @@ module.exports = function() {
/**
* @summary Asserts that text is not present in a PDF file
* @function assertNot
- * @param {String} path - Absolute path to the pdf file.
+ * @param {String} pdfFilePath - Absolute path to the pdf file.
* @param {String} text - Text to assert.
* @param {Number=} pageNum - Page number.
* @param {String=} message - Message to throw if assertion fails.
*/
- module.assertNot = function(path, text, pageNum = null, message = null) {
- validateString(path, 'path');
+ module.assertNot = function(pdfFilePath, text, pageNum = null, message = null) {
+ validateString(pdfFilePath, 'pdfFilePath');
validateString(text, 'text');
validatePageNum(pageNum, 'pageNum');
validateMessage(message, 'message');
@@ -304,7 +309,7 @@ module.exports = function() {
try {
let actual = null;
const expected = false;
- assertion(path, text, pageNum).then(
+ assertion(pdfFilePath, text, pageNum).then(
result => {
actual = result;
},
@@ -340,18 +345,18 @@ module.exports = function() {
/**
* @summary Count the number of times specified text is present in a PDF file.
* @function count
- * @param {String} path - Absolute path to the pdf file.
+ * @param {String} pdfFilePath - Absolute path to the pdf file.
* @param {String} text - Text to count.
* @param {Number=} pageNum - Page number.
* @return {Number} Number of times the specified text was found.
*/
- module.count = function(path, text, pageNum = null) {
- validateString(path, 'path');
+ module.count = function(pdfFilePath, text, pageNum = null) {
+ validateString(pdfFilePath, 'pdfFilePath');
validateString(text, 'text');
validatePageNum(pageNum, 'pageNum');
let actual = null;
- count(path, text, pageNum, true).then(
+ count(pdfFilePath, text, pageNum, true).then(
result => {
actual = result;
},
|
Allow to use relative path in PDF module.
|
oxygenhq_oxygen
|
train
|
080ddd1d32dc3d4cd303026044eb350ac43ae536
|
diff --git a/src/PermissionMatcher.php b/src/PermissionMatcher.php
index <HASH>..<HASH> 100644
--- a/src/PermissionMatcher.php
+++ b/src/PermissionMatcher.php
@@ -12,33 +12,42 @@ class PermissionMatcher
*
* @param array|object $permissions
* @param array $authzGroups
+ * @param boolean $reverse Returns an array where the priviliges are the keys and authzgroups the values
* @return array
*/
- public function match($permissions, array $authzGroups)
+ public function match($permissions, array $authzGroups, $reverse = false)
{
$privileges = [];
foreach ($permissions as $permissionAuthzGroup => $permissionPrivileges) {
- if ($this->hasMatchingAuthzGroup($permissionAuthzGroup, $authzGroups)) {
+ $matchingAuthzGroup = $this->hasMatchingAuthzGroup($permissionAuthzGroup, $authzGroups);
+
+ if (!$matchingAuthzGroup) {
+ continue;
+ }
+
+ if ($reverse) {
+ $privileges = $this->addAuthzGroupsToPrivileges($privileges, $permissionPrivileges, [$permissionAuthzGroup, $matchingAuthzGroup]);
+ } else {
$privileges[] = $permissionPrivileges;
}
}
- return $this->flatten($privileges);
+ return $reverse ? $privileges : $this->flatten($privileges);
}
-
/**
* Check if one of the authz groups match
*
* @param string $permissionAuthzGroup
* @param array $authzGroups
+ * @return string|boolean
*/
protected function hasMatchingAuthzGroup($permissionAuthzGroup, array $authzGroups)
{
foreach ($authzGroups as $authzGroup) {
if ($this->authzGroupsAreEqual($permissionAuthzGroup, $authzGroup)) {
- return true;
+ return $authzGroup;
}
}
@@ -147,6 +156,26 @@ class PermissionMatcher
}
/**
+ * Populate an array of privileges with their corresponding authz groups
+ *
+ * @param array $privileges The resulting array
+ * @param string|array $authzGroupsPrivileges The privileges that the authzgroup has
+ * @param array $authzGroups
+ * @return array $priviliges
+ */
+ protected function addAuthzGroupsToPrivileges(array $privileges, $authzGroupsPrivileges, array $authzGroups)
+ {
+ $authzGroupsPrivileges = !is_string($authzGroupsPrivileges) ? $authzGroupsPrivileges : [$authzGroupsPrivileges];
+
+ foreach($authzGroupsPrivileges as $privilige) {
+ $privileges[$privilige] = !empty($privileges[$privilige]) ? $privileges[$privilige] : [];
+ $privileges[$privilige] = array_unique(array_merge($privileges[$privilige], $authzGroups));
+ }
+
+ return $privileges;
+ }
+
+ /**
* Check if a string starts with given substring
*
* @param string $haystack
diff --git a/tests/unit/PermissionMatcherTest.php b/tests/unit/PermissionMatcherTest.php
index <HASH>..<HASH> 100644
--- a/tests/unit/PermissionMatcherTest.php
+++ b/tests/unit/PermissionMatcherTest.php
@@ -196,4 +196,43 @@ class PermissionMatcherTest extends \Codeception\TestCase\Test
$this->assertArrayMatches(['read'], $this->matcher->match($permissions, ['guest']));
$this->assertArrayMatches(['read'], $this->matcher->match($permissions, ['foo']));
}
+
+ public function testMatchReverse()
+ {
+ $permissions = [
+ 'admin' => 'read',
+ 'admin.support' => 'write',
+ 'admin.dev' => 'develop',
+ 'admin.dev.tester' => 'test',
+ 'guest' => 'find',
+ 'guest.support' => 'sing',
+ '*.support' => 'dance'
+ ];
+
+ $this->assertEquals([
+ 'read' => ['admin']
+ ], $this->matcher->match($permissions, ['admin'], true));
+
+ $this->assertEquals([
+ 'write' => ['admin.support', 'admin.*'],
+ 'develop' => ['admin.dev', 'admin.*'],
+ 'test' => ['admin.dev.tester', 'admin.*']
+ ], $this->matcher->match($permissions, ['admin.*'], true));
+
+ $this->assertEquals([
+ 'test' => ['admin.dev.tester', 'admin.*.*']
+ ], $this->matcher->match($permissions, ['admin.*.*'], true));
+
+ $this->assertEquals([
+ 'read' => ['admin'],
+ 'write' => ['admin.support', 'admin.*'],
+ 'develop' => ['admin.dev', 'admin.*'],
+ 'test' => ['admin.dev.tester', 'admin.*']
+ ], $this->matcher->match($permissions, ['admin', 'admin.*'], true));
+
+ $this->assertEquals([
+ 'develop' => ['admin.dev', 'admin.d*'],
+ 'test' => ['admin.dev.tester', 'admin.d*']
+ ], $this->matcher->match($permissions, ['admin.d*'], true));
+ }
}
|
Added option to output reversed priviliges
|
legalthings_permission-matcher
|
train
|
bb8cc5d2070482a4e737ffde31587865def588ab
|
diff --git a/polyfill.js b/polyfill.js
index <HASH>..<HASH> 100644
--- a/polyfill.js
+++ b/polyfill.js
@@ -3,7 +3,7 @@
var setPrototypeOf = require('es5-ext/object/set-prototype-of')
, object = require('es5-ext/object/valid-object')
, value = require('es5-ext/object/valid-value')
- , d = require('d/d')
+ , d = require('d')
, getIterator = require('es6-iterator/get')
, forOf = require('es6-iterator/for-of')
, toStringTagSymbol = require('es6-symbol').toStringTag
|
Update up to changes in d package
|
medikoo_es6-weak-map
|
train
|
41a65d8876911831fd5581cbc7d354e02f5a427c
|
diff --git a/client/server/middleware/unsupported-browser.js b/client/server/middleware/unsupported-browser.js
index <HASH>..<HASH> 100644
--- a/client/server/middleware/unsupported-browser.js
+++ b/client/server/middleware/unsupported-browser.js
@@ -18,13 +18,32 @@ function isSupportedBrowser( req ) {
} );
}
+// We don't want to redirect some of our public landing pages, so we include them
+// here.
+function allowPath( path ) {
+ // Strip leading '/'.
+ let parsedPath = path.replace( /^\//, '' );
+ const possiblePathLocales = [ 'en', ...config( 'magnificent_non_en_locales' ) ];
+ for ( const locale of possiblePathLocales ) {
+ // Strip leading locale (e.g. 'es/')
+ if ( parsedPath.startsWith( locale ) ) {
+ parsedPath = parsedPath.replace( new RegExp( `^${ locale }/?` ), '' );
+ break;
+ }
+ }
+ // At this point, '/es/themes' is just 'themes', ready to match our allowed paths.
+ const allowedPaths = [ 'browsehappy', 'log-in', 'start', 'new', 'themes', 'theme', 'domains' ];
+ return allowedPaths.some( ( p ) => parsedPath.startsWith( p ) );
+}
+
export default () => ( req, res, next ) => {
if ( ! config.isEnabled( 'redirect-fallback-browsers' ) ) {
next();
return;
}
- if ( req.path === '/browsehappy' ) {
+ // Permitted paths even if the browser is unsupported.
+ if ( allowPath( req.path ) ) {
next();
return;
}
|
Skip unsupported browser redirect if page is public (#<I>)
|
Automattic_wp-calypso
|
train
|
612c50fba596c2559968f9aedd7076a847ef922a
|
diff --git a/core/elements/ons-page.spec.js b/core/elements/ons-page.spec.js
index <HASH>..<HASH> 100644
--- a/core/elements/ons-page.spec.js
+++ b/core/elements/ons-page.spec.js
@@ -32,7 +32,7 @@ describe('ons-page', function() {
var spy = chai.spy();
document.addEventListener('hide', spy);
var element = new OnsPageElement();
- document.body.appendChild(element)
+ document.body.appendChild(element);
element._hide();
expect(element.style.display).to.equal('none');
expect(spy).to.have.been.called.once;
@@ -42,7 +42,7 @@ describe('ons-page', function() {
var spy = chai.spy();
document.addEventListener('show', spy);
var element = new OnsPageElement();
- document.body.appendChild(element)
+ document.body.appendChild(element);
element._show();
expect(element.style.display).to.equal('block');
expect(spy).to.have.been.called.once;
|
style(ons-page): added missing semi-colons in karma test
|
OnsenUI_OnsenUI
|
train
|
93522cad1f86b1dc5100a3e9d72c7139858dde2a
|
diff --git a/test/com/google/javascript/jscomp/ReplaceCssNamesTest.java b/test/com/google/javascript/jscomp/ReplaceCssNamesTest.java
index <HASH>..<HASH> 100644
--- a/test/com/google/javascript/jscomp/ReplaceCssNamesTest.java
+++ b/test/com/google/javascript/jscomp/ReplaceCssNamesTest.java
@@ -22,7 +22,6 @@ import static com.google.javascript.jscomp.ReplaceCssNames.UNKNOWN_SYMBOL_WARNIN
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.rhino.Node;
-
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@@ -31,7 +30,7 @@ import java.util.Set;
* Tests for ReplaceCssNames.java.
*
*/
-public final class ReplaceCssNamesTest extends CompilerTestCase {
+public final class ReplaceCssNamesTest extends TypeICompilerTestCase {
/** Whether to pass the map of replacements as opposed to null */
boolean useReplacementMap;
@@ -63,6 +62,10 @@ public final class ReplaceCssNamesTest extends CompilerTestCase {
Map<String, Integer> cssNames;
public ReplaceCssNamesTest() {
+ super(LINE_JOINER.join(
+ DEFAULT_EXTERNS,
+ "Object.prototype.getClass;",
+ "goog.getCssName;"));
}
@Override protected CompilerPass getProcessor(Compiler compiler) {
@@ -106,7 +109,13 @@ public final class ReplaceCssNamesTest extends CompilerTestCase {
return 1;
}
- public void testDoNotUseReplacementMap() {
+ // NOTE(aravindpg): The ccsNames field is populated by each test method, and then compared
+ // to expected. So, our usual strategy of running both NTI and OTI for each test doesn't work
+ // here. We need to run all three methods in doNotUseReplacementMap with OTI before we can
+ // run them with NTI. That's why we refactored this code to call doNotUseReplacementMap from
+ // two places.
+
+ private void doNotUseReplacementMap() {
useReplacementMap = false;
test("var x = goog.getCssName('goog-footer-active')",
"var x = 'goog-footer-active'");
@@ -126,6 +135,16 @@ public final class ReplaceCssNamesTest extends CompilerTestCase {
assertEquals(expected, cssNames);
}
+ public void testDoNotUseReplacementMapOti() {
+ this.mode = TypeInferenceMode.OTI_ONLY;
+ doNotUseReplacementMap();
+ }
+
+ public void testDoNotUseReplacementMapNti() {
+ this.mode = TypeInferenceMode.NTI_ONLY;
+ doNotUseReplacementMap();
+ }
+
public void testOneArgWithUnknownStringLiterals() {
test("var x = goog.getCssName('unknown')",
"var x = 'unknown'", null, UNKNOWN_SYMBOL_WARNING);
@@ -135,7 +154,7 @@ public final class ReplaceCssNamesTest extends CompilerTestCase {
"setClass('ab')", null, UNKNOWN_SYMBOL_WARNING);
}
- public void testOneArgWithSimpleStringLiterals() {
+ private void oneArgWithSimpleStringLiterals() {
test("var x = goog.getCssName('buttonbar')",
"var x = 'b'");
test("el.className = goog.getCssName('colorswatch')",
@@ -151,7 +170,17 @@ public final class ReplaceCssNamesTest extends CompilerTestCase {
assertEquals(expected, cssNames);
}
- public void testOneArgWithCompositeClassNames() {
+ public void testOneArgWithSimpleStringLiteralsOti() {
+ this.mode = TypeInferenceMode.OTI_ONLY;
+ oneArgWithSimpleStringLiterals();
+ }
+
+ public void testOneArgWithSimpleStringLiteralsNti() {
+ this.mode = TypeInferenceMode.NTI_ONLY;
+ oneArgWithSimpleStringLiterals();
+ }
+
+ private void oneArgWithCompositeClassNames() {
test("var x = goog.getCssName('goog-footer-active')",
"var x = 'g-f-a'");
test("el.className = goog.getCssName('goog-colorswatch-disabled')",
@@ -170,6 +199,16 @@ public final class ReplaceCssNamesTest extends CompilerTestCase {
assertEquals(expected, cssNames);
}
+ public void testOneArgWithCompositeClassNamesOti() {
+ this.mode = TypeInferenceMode.OTI_ONLY;
+ oneArgWithCompositeClassNames();
+ }
+
+ public void testoOeArgWithCompositeClassNamesNti() {
+ this.mode = TypeInferenceMode.NTI_ONLY;
+ oneArgWithCompositeClassNames();
+ }
+
public void testOneArgWithCompositeClassNamesFull() {
renamingMap = getFullMap();
@@ -206,8 +245,8 @@ public final class ReplaceCssNamesTest extends CompilerTestCase {
public void testTwoArsWithVariableFirstArg() {
test("var x = goog.getCssName(baseClass, 'active')",
"var x = baseClass + '-a'");
- test("el.className = goog.getCssName(this.getClass(), 'disabled')",
- "el.className = this.getClass() + '-d'");
+ test("el.className = goog.getCssName((new Object).getClass(), 'disabled')",
+ "el.className = (new Object).getClass() + '-d'");
test("setClass(goog.getCssName(BASE_CLASS, 'disabled'))",
"setClass(BASE_CLASS + '-d')");
}
|
[NTI] Convert ReplaceCssNames to run with NTI.
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
46d2c3b387bb3662d16929347087fafe1a76ef91
|
diff --git a/flask_injector.py b/flask_injector.py
index <HASH>..<HASH> 100644
--- a/flask_injector.py
+++ b/flask_injector.py
@@ -16,7 +16,7 @@ import flask
from injector import Injector
from flask import Config, Request
from werkzeug.local import Local, LocalManager
-from injector import Module, Scope, ScopeDecorator, singleton, InstanceProvider
+from injector import Module, Provider, Scope, ScopeDecorator, singleton, InstanceProvider
__author__ = 'Alec Thomas <alec@swapoff.org>'
@@ -37,6 +37,20 @@ def wrap_fun(fun, injector):
return wrapper
+class CachedProviderWrapper(Provider):
+ def __init__(self, old_provider):
+ self._old_provider = old_provider
+ self._cache = {}
+
+ def get(self, injector):
+ key = id(injector)
+ try:
+ return self._cache[key]
+ except KeyError:
+ instance = self._cache[key] = self._old_provider.get(injector)
+ return instance
+
+
class RequestScope(Scope):
"""A scope whose object lifetime is tied to a request.
@@ -65,21 +79,6 @@ class RequestScope(Scope):
self._locals.scope[key] = provider
return provider
else:
- from injector import Provider
-
- class CachedProviderWrapper(Provider):
- def __init__(self, old_provider):
- self._old_provider = old_provider
- self._cache = {}
-
- def get(self, injector):
- key = id(injector)
- try:
- return self._cache[key]
- except KeyError:
- instance = self._cache[key] = self._old_provider.get(injector)
- return instance
-
def get(self, key, provider):
try:
return self._locals.scope[key]
|
Refactor, flake8 didn't understand this class nesting
|
alecthomas_flask_injector
|
train
|
62045c3232de3270c8964a5871cfd79ea714882e
|
diff --git a/pandas/_libs/algos_common_helper.pxi.in b/pandas/_libs/algos_common_helper.pxi.in
index <HASH>..<HASH> 100644
--- a/pandas/_libs/algos_common_helper.pxi.in
+++ b/pandas/_libs/algos_common_helper.pxi.in
@@ -109,8 +109,6 @@ def ensure_object(object arr):
return arr
else:
return arr.astype(np.object_)
- elif hasattr(arr, '_box_values_as_index'):
- return arr._box_values_as_index()
else:
return np.array(arr, dtype=np.object_)
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py
index <HASH>..<HASH> 100644
--- a/pandas/core/arrays/datetimes.py
+++ b/pandas/core/arrays/datetimes.py
@@ -588,7 +588,7 @@ class DatetimeArray(dtl.DatetimeLikeArrayMixin,
@Appender(dtl.DatetimeLikeArrayMixin._validate_fill_value.__doc__)
def _validate_fill_value(self, fill_value):
- if isna(fill_value) or fill_value == iNaT:
+ if isna(fill_value):
fill_value = iNaT
elif isinstance(fill_value, (datetime, np.datetime64)):
self._assert_tzawareness_compat(fill_value)
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py
index <HASH>..<HASH> 100644
--- a/pandas/core/dtypes/cast.py
+++ b/pandas/core/dtypes/cast.py
@@ -5,7 +5,7 @@ from datetime import datetime, timedelta
import numpy as np
from pandas._libs import lib, tslib, tslibs
-from pandas._libs.tslibs import OutOfBoundsDatetime, Period, iNaT
+from pandas._libs.tslibs import NaT, OutOfBoundsDatetime, Period, iNaT
from pandas.compat import PY3, string_types, text_type, to_str
from .common import (
@@ -272,7 +272,7 @@ def maybe_promote(dtype, fill_value=np.nan):
fill_value = tslibs.Timedelta(fill_value).value
elif is_datetime64tz_dtype(dtype):
if isna(fill_value):
- fill_value = iNaT
+ fill_value = NaT
elif is_extension_array_dtype(dtype) and isna(fill_value):
fill_value = dtype.na_value
elif is_float(fill_value):
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py
index <HASH>..<HASH> 100644
--- a/pandas/core/indexes/datetimelike.py
+++ b/pandas/core/indexes/datetimelike.py
@@ -203,15 +203,6 @@ class DatetimeIndexOpsMixin(ExtensionOpsMixin):
return type(self)._simple_new(result, name=self.name)
return arg
- def _box_values_as_index(self):
- """
- Return object Index which contains boxed values.
- """
- # XXX: this is broken (not called) for PeriodIndex, which doesn't
- # define _box_values AFAICT
- from pandas.core.index import Index
- return Index(self._box_values(self.asi8), name=self.name, dtype=object)
-
def _box_values(self, values):
return self._data._box_values(values)
diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/arrays/test_datetimelike.py
+++ b/pandas/tests/arrays/test_datetimelike.py
@@ -388,6 +388,10 @@ class TestDatetimeArray(SharedTests):
# Timestamp with mismatched tz-awareness
arr.take([-1, 1], allow_fill=True, fill_value=now)
+ with pytest.raises(ValueError):
+ # require NaT, not iNaT, as it could be confused with an integer
+ arr.take([-1, 1], allow_fill=True, fill_value=pd.NaT.value)
+
def test_concat_same_type_invalid(self, datetime_index):
# different timezones
dti = datetime_index
|
<I> follow-up: fix incorrectly accepting iNaT in validate_fill_value (#<I>)
|
pandas-dev_pandas
|
train
|
7bedbdb6328f3bd3319cff81d983d06af23229a2
|
diff --git a/languagetool-language-modules/fr/src/main/java/org/languagetool/rules/fr/PostponedAdjectiveConcordanceFilter.java b/languagetool-language-modules/fr/src/main/java/org/languagetool/rules/fr/PostponedAdjectiveConcordanceFilter.java
index <HASH>..<HASH> 100644
--- a/languagetool-language-modules/fr/src/main/java/org/languagetool/rules/fr/PostponedAdjectiveConcordanceFilter.java
+++ b/languagetool-language-modules/fr/src/main/java/org/languagetool/rules/fr/PostponedAdjectiveConcordanceFilter.java
@@ -111,7 +111,7 @@ public class PostponedAdjectiveConcordanceFilter extends RuleFilter {
private static final Pattern COORDINACIO_IONI = Pattern.compile("et|ou|ni");
private static final Pattern KEEP_COUNT = Pattern.compile("Y|J .*|N .*|D .*|P.*|V ppa .*|M nonfin|UNKNOWN|Z.*|V.* inf|V ppr");
private static final Pattern KEEP_COUNT2 = Pattern.compile(",|et|ou|ni"); // |\\d+%?|%
- private static final Pattern STOP_COUNT = Pattern.compile("[\\-;:\\(\\)\\[\\]–—―‒]");
+ private static final Pattern STOP_COUNT = Pattern.compile("[;:\\(\\)\\[\\]–—―‒]");
private static final Pattern PREPOSICIONS = Pattern.compile("P");
private static final Pattern PREPOSICIO_CANVI_NIVELL = Pattern.compile("d'|de|des|du|à|au|aux|en|dans|sur|entre|par|pour|avec|sans|contre|comme"); //???
private static final Pattern VERB = Pattern.compile("V.* (inf|ind|sub|con|ppr|imp).*"); // Any verb that is not V ppa
|
[fr] undo change in PostponedAdjectiveConcordanceFilter
|
languagetool-org_languagetool
|
train
|
4c8c1cf93f4b9e9e9492dbd0578e66aba3d378fa
|
diff --git a/lib/reporters/base.js b/lib/reporters/base.js
index <HASH>..<HASH> 100644
--- a/lib/reporters/base.js
+++ b/lib/reporters/base.js
@@ -85,6 +85,13 @@ exports.cursor = {
};
/**
+ * A test is considered slow if it
+ * exceeds the following value in milliseconds.
+ */
+
+exports.slow = 75;
+
+/**
* Outut the given `failures` as a list.
*
* @param {Array} failures
@@ -145,12 +152,14 @@ function Base(runner) {
runner.on('pass', function(test){
stats.passes = stats.passes || 0;
- // TODO: configurable
- test.speed = test.duration < 20
- ? 'fast'
- : test.duration < 75
+
+ var medium = exports.slow / 2;
+ test.speed = test.duration > exports.slow
+ ? 'slow'
+ : test.duration > medium
? 'medium'
- : 'slow';
+ : 'fast';
+
stats.passes++;
});
|
Added exports.slow to tweak what is considered "slow"
|
mochajs_mocha
|
train
|
e20eaff867001861f35f5629861ff9e80eaeef8a
|
diff --git a/devices.js b/devices.js
index <HASH>..<HASH> 100755
--- a/devices.js
+++ b/devices.js
@@ -17299,16 +17299,46 @@ const devices = [
model: 'HLU2909K',
vendor: 'Datek',
description: 'APEX smart plug 16A',
- fromZigbee: [fz.electrical_measurement, fz.on_off, fz.metering],
+ fromZigbee: [fz.on_off, fz.electrical_measurement, fz.metering, fz.temperature],
toZigbee: [tz.on_off],
meta: {configureKey: 1},
configure: async (device, coordinatorEndpoint, logger) => {
const endpoint = device.getEndpoint(1);
- await reporting.bind(endpoint, coordinatorEndpoint, ['genOnOff', 'seMetering']);
- endpoint.saveClusterAttributeKeyValue('seMetering', {divisor: 100, multiplier: 1});
- endpoint.saveClusterAttributeKeyValue('haElectricalMeasurement', {acVoltageDivisor: 100});
+ await reporting.bind(endpoint, coordinatorEndpoint, ['genOnOff', 'haElectricalMeasurement', 'msTemperatureMeasurement']);
+ await endpoint.read('haElectricalMeasurement', ['acVoltageMultiplier', 'acVoltageDivisor']);
+ await endpoint.read('haElectricalMeasurement', ['acCurrentMultiplier', 'acCurrentDivisor']);
+ await endpoint.read('haElectricalMeasurement', ['acPowerMultiplier', 'acPowerDivisor']);
+ await reporting.onOff(endpoint);
+ await reporting.rmsVoltage(endpoint);
+ await reporting.rmsCurrent(endpoint);
+ await reporting.activePower(endpoint);
+ await reporting.temperature(endpoint);
+ },
+ exposes: [e.power(), e.current(), e.voltage(), e.switch(), e.temperature()],
+ },
+
+ {
+ zigbeeModel: ['HAN'],
+ model: 'Datek_HAN',
+ vendor: 'Datek',
+ description: 'Eva AMS HAN power-meter sensor',
+ fromZigbee: [fz.metering, fz.electrical_measurement],
+ toZigbee: [],
+ ota: ota.zigbeeOTA,
+ meta: {configureKey: 3},
+ configure: async (device, coordinatorEndpoint, logger) => {
+ const endpoint = device.getEndpoint(1);
+ await reporting.bind(endpoint, coordinatorEndpoint, ['haElectricalMeasurement', 'seMetering']);
+ await reporting.readEletricalMeasurementMultiplierDivisors(endpoint);
+ await reporting.rmsVoltage(endpoint);
+ await reporting.rmsCurrent(endpoint);
+ await reporting.readMeteringMultiplierDivisor(endpoint);
+ await reporting.instantaneousDemand(endpoint);
+ await reporting.currentSummDelivered(endpoint);
+ await reporting.currentSummReceived(endpoint);
},
- exposes: [e.power(), e.current(), e.voltage(), e.switch()],
+ exposes: [e.power(), e.energy(), e.current(), e.voltage(), e.current_phase_b(), e.voltage_phase_b(), e.current_phase_c(),
+ e.voltage_phase_c()],
},
// Prolight
|
Updated Datek APEX and added Datek HAN adapter (#<I>)
* Updated Datek APEX and added Datek HAN adapter
* Fixed trailing spaces
* Update devices.js
|
Koenkk_zigbee-shepherd-converters
|
train
|
6ec6b5a46d24fad6d55dbfb68382e5bedc58703f
|
diff --git a/src/Components/RowAction.php b/src/Components/RowAction.php
index <HASH>..<HASH> 100644
--- a/src/Components/RowAction.php
+++ b/src/Components/RowAction.php
@@ -80,6 +80,6 @@ abstract class RowAction
*/
protected function tag($tag, $content, array $attributes = [])
{
- return $this->grid->getHtmlBuilder()->tag($tag, $content, $attributes);
+ return $this->grid->getGridHelper()->getHtmlBuilder()->tag($tag, $content, $attributes);
}
}
|
call html builder by getGridHelper
|
adam-boduch_laravel-grid
|
train
|
df721027d3c36ce8465d66a9b95b3c78fefe0d3e
|
diff --git a/configgtm-v1_3/asmap_test.go b/configgtm-v1_3/asmap_test.go
index <HASH>..<HASH> 100644
--- a/configgtm-v1_3/asmap_test.go
+++ b/configgtm-v1_3/asmap_test.go
@@ -4,9 +4,8 @@ import (
"testing"
"github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1"
-
+ "github.com/h2non/gock"
"github.com/stretchr/testify/assert"
- "gopkg.in/h2non/gock.v1"
)
var GtmTestAsMap = "testAsMap"
diff --git a/configgtm-v1_3/cidrmap_test.go b/configgtm-v1_3/cidrmap_test.go
index <HASH>..<HASH> 100644
--- a/configgtm-v1_3/cidrmap_test.go
+++ b/configgtm-v1_3/cidrmap_test.go
@@ -5,11 +5,12 @@ import (
"github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1"
+ "github.com/h2non/gock"
"github.com/stretchr/testify/assert"
- "gopkg.in/h2non/gock.v1"
)
var GtmTestCidrMap = "testCidrMap"
+var gtmTestDomain = ""
func instantiateCidrMap() *CidrMap {
diff --git a/configgtm-v1_3/datacenter_test.go b/configgtm-v1_3/datacenter_test.go
index <HASH>..<HASH> 100644
--- a/configgtm-v1_3/datacenter_test.go
+++ b/configgtm-v1_3/datacenter_test.go
@@ -5,8 +5,8 @@ import (
"github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1"
+ "github.com/h2non/gock"
"github.com/stretchr/testify/assert"
- "gopkg.in/h2non/gock.v1"
"fmt"
)
diff --git a/configgtm-v1_3/domain_test.go b/configgtm-v1_3/domain_test.go
index <HASH>..<HASH> 100644
--- a/configgtm-v1_3/domain_test.go
+++ b/configgtm-v1_3/domain_test.go
@@ -5,8 +5,8 @@ import (
"github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1"
+ "github.com/h2non/gock"
"github.com/stretchr/testify/assert"
- "gopkg.in/h2non/gock.v1"
)
func instantiateDomain() *Domain {
diff --git a/configgtm-v1_3/geomap_test.go b/configgtm-v1_3/geomap_test.go
index <HASH>..<HASH> 100644
--- a/configgtm-v1_3/geomap_test.go
+++ b/configgtm-v1_3/geomap_test.go
@@ -5,7 +5,7 @@ import (
"github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1"
- "gopkg.in/h2non/gock.v1"
+ "github.com/golang/mock/mockgen"
"github.com/stretchr/testify/assert"
)
diff --git a/configgtm-v1_3/property_test.go b/configgtm-v1_3/property_test.go
index <HASH>..<HASH> 100644
--- a/configgtm-v1_3/property_test.go
+++ b/configgtm-v1_3/property_test.go
@@ -5,8 +5,8 @@ import (
"github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1"
+ "github.com/h2non/gock"
"github.com/stretchr/testify/assert"
- "gopkg.in/h2non/gock.v1"
"fmt"
)
diff --git a/configgtm-v1_3/resource_test.go b/configgtm-v1_3/resource_test.go
index <HASH>..<HASH> 100644
--- a/configgtm-v1_3/resource_test.go
+++ b/configgtm-v1_3/resource_test.go
@@ -5,8 +5,8 @@ import (
"github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1"
+ "github.com/h2non/gock"
"github.com/stretchr/testify/assert"
- "gopkg.in/h2non/gock.v1"
"fmt"
)
|
[AT-<I>][Change] Back to github gock
|
akamai_AkamaiOPEN-edgegrid-golang
|
train
|
650240f2519ce043b899e4aa941c8d021a2cb47c
|
diff --git a/core/src/elements/ons-carousel.js b/core/src/elements/ons-carousel.js
index <HASH>..<HASH> 100644
--- a/core/src/elements/ons-carousel.js
+++ b/core/src/elements/ons-carousel.js
@@ -340,13 +340,16 @@ export default class CarouselElement extends BaseElement {
}
_compile() {
- if (!this._swiperElement) {
- const swiper = util.create('.swiper', { height: '100%'});
+ const swiper = this._swiperElement || util.create('.swiper', { height: '100%'});
+ if (!swiper.parentNode) {
while (this.firstChild) {
swiper.appendChild(this.firstChild);
}
this.appendChild(swiper);
}
+
+ this.appendChild = this.appendChild.bind(swiper);
+ this.insertBefore = this.insertBefore.bind(swiper);
}
get _swiperElement() {
@@ -630,7 +633,7 @@ export default class CarouselElement extends BaseElement {
_updateAutoRefresh() {
if (this._mutationObserver) {
if (this.hasAttribute('auto-refresh')) {
- this._mutationObserver.observe(this, {childList: true});
+ this._mutationObserver.observe(this._swiperElement, {childList: true});
} else {
this._mutationObserver.disconnect();
}
|
fix(ons-carousel): Redirect child insertion to the new swiper.
|
OnsenUI_OnsenUI
|
train
|
fe41f86e539cf0c10c7a7d97aa77bff1f4cc0192
|
diff --git a/pyspider/fetcher/tornado_fetcher.py b/pyspider/fetcher/tornado_fetcher.py
index <HASH>..<HASH> 100644
--- a/pyspider/fetcher/tornado_fetcher.py
+++ b/pyspider/fetcher/tornado_fetcher.py
@@ -148,7 +148,7 @@ class Fetcher(object):
wait_result.release()
wait_result.acquire()
- self.fetch(task, callback=callback)
+ self.ioloop.add_callback(self.fetch, task, callback)
while 'result' not in _result:
wait_result.wait()
wait_result.release()
|
task should submitted in the main thread
fix #<I>
|
binux_pyspider
|
train
|
b856d2c0c67c15b8ac405344769852f5a1758839
|
diff --git a/src/Validate.php b/src/Validate.php
index <HASH>..<HASH> 100644
--- a/src/Validate.php
+++ b/src/Validate.php
@@ -109,9 +109,17 @@ class Validate
$isWild = strpos($field, '*') !== false;
$overlap = Str::overlapLeft($field, $pattern);
- // Check pattern is present
+ // If pattern is not present
if (!ArrDots::has($data, $pattern, '*')) {
- $validator->addError($pattern, $rule, [':field' => $field, '%value' => implode(',', $values)]);
+ foreach (Validator::getValues($data, $field) as $fieldAttribute => $fieldValue) {
+ if (null === $fieldValue || !in_array($fieldValue, $values)) {
+ continue;
+ }
+
+ $attribute = $isWild ? Str::overlapLeftMerge($overlap, $fieldAttribute, $pattern) : $pattern;
+ $validator->addError($attribute, $rule, [':field' => $fieldAttribute, '%value' => implode(',', $values)]);
+ }
+ return;
}
// Check value is not null
diff --git a/tests/Integration/ValidateRequiredIfTest.php b/tests/Integration/ValidateRequiredIfTest.php
index <HASH>..<HASH> 100644
--- a/tests/Integration/ValidateRequiredIfTest.php
+++ b/tests/Integration/ValidateRequiredIfTest.php
@@ -28,6 +28,17 @@ class ValidateRequiredIfTest extends TestCase
$this->assertEquals($errors, $this->validator->getProcessedErrors());
}
+ public function testValidateRequiredIfInvalidAndNotPresentTrue()
+ {
+ $rules = ['field0' => 'required-if:field1,baz'];
+ $values = ['field1' => 'baz'];
+ $errors = ['errors' => ['field0' => ['required-if' => 'Field0 is required if Field1 equals baz']]];
+ $this->validator->validate($values, $rules);
+
+ $this->assertTrue($this->validator->hasErrors());
+ $this->assertEquals($errors, $this->validator->getProcessedErrors());
+ }
+
public function testValidateRequiredIfValidNullFalse()
{
$rules = ['field0' => 'required-if:field1,baz'];
@@ -37,6 +48,15 @@ class ValidateRequiredIfTest extends TestCase
$this->assertFalse($this->validator->hasErrors());
}
+ public function testValidateRequiredIfValidNullAndNotPresentFalse()
+ {
+ $rules = ['field0' => 'required-if:field1,baz'];
+ $values = ['field1' => null];
+ $this->validator->validate($values, $rules);
+
+ $this->assertFalse($this->validator->hasErrors());
+ }
+
public function testValidateRequiredIfValidUnequalFalse()
{
$rules = ['field0' => 'required-if:field1,baz'];
@@ -80,6 +100,23 @@ class ValidateRequiredIfTest extends TestCase
$this->assertEquals($errors, $this->validator->getProcessedErrors());
}
+ public function testValidateRequiredWithInvalidAndNotPresentTrueDots()
+ {
+ $rules = ['group.*.field1' => 'required-if:group.*.field0,foo'];
+ $values = [
+ 'group' => [
+ [
+ 'field0' => 'foo',
+ ]
+ ]
+ ];
+ $errors = ['errors' => ['group.0.field1' => ['required-if' => 'Group 0 field1 is required if Group 0 field0 equals foo']]];
+ $this->validator->validate($values, $rules);
+
+ $this->assertTrue($this->validator->hasErrors());
+ $this->assertEquals($errors, $this->validator->getProcessedErrors());
+ }
+
public function testValidateRequiredWithValidFalseNullDots()
{
$rules = ['group.*.field1' => 'required-if:group.*.field0,foo'];
@@ -96,6 +133,21 @@ class ValidateRequiredIfTest extends TestCase
$this->assertFalse($this->validator->hasErrors());
}
+ public function testValidateRequiredWithValidFalseNullAndNotPresentDots()
+ {
+ $rules = ['group.*.field1' => 'required-if:group.*.field0,foo'];
+ $values = [
+ 'group' => [
+ [
+ 'field0' => null,
+ ]
+ ]
+ ];
+ $this->validator->validate($values, $rules);
+
+ $this->assertFalse($this->validator->hasErrors());
+ }
+
public function testValidateRequiredWithValidFalseUnequalDots()
{
$rules = ['group.*.field1' => 'required-if:group.*.field0,foo'];
|
[fix] Required If now handles when the required is present but the pattern is not
|
pdscopes_php-form-validator
|
train
|
a7fbabc4d8b42a3ca8b182b7064d67162e65d42e
|
diff --git a/src/BoomCMS/Http/Controllers/Auth/AuthController.php b/src/BoomCMS/Http/Controllers/Auth/AuthController.php
index <HASH>..<HASH> 100644
--- a/src/BoomCMS/Http/Controllers/Auth/AuthController.php
+++ b/src/BoomCMS/Http/Controllers/Auth/AuthController.php
@@ -5,13 +5,11 @@ namespace BoomCMS\Http\Controllers\Auth;
use BoomCMS\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Foundation\Auth\ThrottlesLogins;
-use Illuminate\Foundation\Validation\ValidatesRequests;
class AuthController extends Controller
{
use AuthenticatesUsers;
use ThrottlesLogins;
- use ValidatesRequests;
protected $loginPath = '/boomcms/login';
protected $loginView = 'boomcms::auth.login';
|
Removed duplicate declaration of ValidatesRequests
|
boomcms_boom-core
|
train
|
39fe008a6bdb082f88cebc377eafe377e3c7df5a
|
diff --git a/src/Context/TestContext.php b/src/Context/TestContext.php
index <HASH>..<HASH> 100644
--- a/src/Context/TestContext.php
+++ b/src/Context/TestContext.php
@@ -2,5 +2,31 @@
namespace PaulGibbs\WordpressBehatExtension\Context;
use Behat\Behat\Tester\Exception\PendingException;
+
class TestContext extends RawWordpressContext {
+ /**
+ * @BeforeSuite
+ */
+ public static function omgadebug()
+ {
+ }
+
+ /**
+ * @Given I am on cool
+ */
+ public function iAmOnCool()
+ {
+ $test = $this->getDriver()->switchTheme('hello-dolly');
+
+ die(var_dump( $test ));
+ throw new PendingException();
+ }
+
+ /**
+ * @When I spurglefill in :arg1 with :arg2
+ */
+ public function iSpurglefillInWith($arg1, $arg2)
+ {
+ throw new PendingException();
+ }
}
|
Update TestContext with debug code, to test CLA integration on Github merge requests.
|
paulgibbs_behat-wordpress-extension
|
train
|
98c33b7144bde1e00cd6c21e1bb81428f9316b5b
|
diff --git a/lib/swift/adapter.rb b/lib/swift/adapter.rb
index <HASH>..<HASH> 100644
--- a/lib/swift/adapter.rb
+++ b/lib/swift/adapter.rb
@@ -55,7 +55,8 @@ module Swift
st = prepare_update(model)
resources.map do |resource|
- binds = [resource.properties(:field).values_at(*supply, *model.key.map(&:field))].flatten
+ resource = model.new(resource) unless resource.kind_of?(model)
+ binds = [resource.properties(:field).values_at(*supply, *model.key.map(&:field))].flatten
st.execute(*binds)
end
end
diff --git a/lib/swift/sugar.rb b/lib/swift/sugar.rb
index <HASH>..<HASH> 100644
--- a/lib/swift/sugar.rb
+++ b/lib/swift/sugar.rb
@@ -18,6 +18,14 @@ module Swift
Swift.db(db).prepare(self, "select * from #{resource} #{where} #{limit} #{offset}").execute(*bind, &block)
end
+ def first db, args = {}
+ only(db, args).first
+ end
+
+ def get db, *id
+ db.kind_of?(Symbol) ? Swift.db(db).get(self, *id) : Swift.db(:default).get(self, db, *id)
+ end
+
def create db = :default, attrs = nil
db, attrs = [ :default, db ] unless attrs
raise ArgumentError, "Use Swift::Adapter#create to create multiple instances." if attrs.kind_of?(Array)
@@ -32,8 +40,16 @@ module Swift
def update db = :default, attributes = nil
db, attributes = [:default, db] unless attributes
- model.properties.each{|p| send(:"#{p.name}=", attributes.fetch(p.name, p.default))}
+ model.properties.each{|p| send(:"#{p.name}=", attributes.fetch(p.name, p.default)) if attributes.key?(p.name)}
Swift.db(db).update(model, self)
end
+
+ # TODO should we prepare cache this too ?
+ def destroy db = :default
+ keys = model.key.map(&:field)
+ bind = properties(:field).values_at(*keys)
+ where = keys.map {|key| "#{key} = ?" }.join(' and ')
+ Swift.db(db).execute("delete from #{model.resource} where #{where}", *bind)
+ end
end # Model
end # Swift
|
some fixes to update and bit more sugar
|
shanna_swift
|
train
|
436aa17ef24d1b51b036fa5ac972633ea23ce7b9
|
diff --git a/classes/Gems/Snippets/Upgrade/UpgradeCompatibilitySnippet.php b/classes/Gems/Snippets/Upgrade/UpgradeCompatibilitySnippet.php
index <HASH>..<HASH> 100644
--- a/classes/Gems/Snippets/Upgrade/UpgradeCompatibilitySnippet.php
+++ b/classes/Gems/Snippets/Upgrade/UpgradeCompatibilitySnippet.php
@@ -529,7 +529,7 @@ class UpgradeCompatibilitySnippet extends \MUtil_Snippets_SnippetAbstract
*/
protected function _filterContent($content)
{
- return preg_replace('/class\\s+([^\\s]+)/', '', $content);
+ return preg_replace('/(class|use)\\s+([^\\s]+)/', '', $content);
}
/**
|
Filter out use statements just like we filter out class statements
|
GemsTracker_gemstracker-library
|
train
|
d6ad92158f839143e59d8abc2a6224e33858d3b2
|
diff --git a/src/loader/loader.js b/src/loader/loader.js
index <HASH>..<HASH> 100644
--- a/src/loader/loader.js
+++ b/src/loader/loader.js
@@ -392,7 +392,7 @@
* @param {String} resources.name internal name of the resource
* @param {String} resources.type "audio", binary", "image", "json", "tmx", "tsx"
* @param {String} resources.src path and/or file name of the resource (for audio assets only the path is required)
- * @param {Boolean} [resources.stream] set to true if you don't have to wait for the audio file to be fully downloaded
+ * @param {Boolean} [resources.stream] Set to true to force HTML5 Audio, which allows not to wait for large file to be downloaded before playing.
* @param {function} [onload=me.loader.onload] function to be called when all resources are loaded
* @param {boolean} [switchToLoadState=true] automatically switch to the loading screen
* @example
@@ -453,7 +453,7 @@
* @param {String} resource.name internal name of the resource
* @param {String} resource.type "audio", binary", "image", "json", "tmx", "tsx"
* @param {String} resource.src path and/or file name of the resource (for audio assets only the path is required)
- * @param {Boolean} [resource.stream] set to true if you don't have to wait for the audio file to be fully downloaded
+ * @param {Boolean} [resource.stream] Set to true to force HTML5 Audio, which allows not to wait for large file to be downloaded before playing.
* @param {Function} onload function to be called when the resource is loaded
* @param {Function} onerror function to be called in case of error
* @example
|
[documentation] clarify the use and impact of the `stream` option
|
melonjs_melonJS
|
train
|
c1ab4d6e9ad15d7692e680acf858a3ad428fa9bc
|
diff --git a/cyphi/subsystem.py b/cyphi/subsystem.py
index <HASH>..<HASH> 100644
--- a/cyphi/subsystem.py
+++ b/cyphi/subsystem.py
@@ -30,8 +30,8 @@ class Subsystem:
"""
Args:
nodes (list(Node)): A list of nodes in this subsystem
- current_state (np.ndarray): The current state of this subsystem
- past_state (np.ndarray): The past state of this subsystem
+ current_state (tuple): The current state of this subsystem
+ past_state (tuple): The past state of this subsystem
network (Network): The network the subsystem is part of
"""
# This nodes in this subsystem.
@@ -39,9 +39,6 @@ class Subsystem:
self.current_state = current_state
self.past_state = past_state
- # Make the state and past state immutable (for hashing).
- self.current_state.flags.writeable = False
- self.past_state.flags.writeable = False
# The network this subsystem belongs to.
self.network = network
@@ -67,8 +64,8 @@ class Subsystem:
"""Two subsystems are equal if their sets of nodes, current and past
states, and networks are equal."""
return (set(self.nodes) == set(other.nodes) and
- np.array_equal(self.current_state, other.current_state) and
- np.array_equal(self.past_state, other.past_state) and
+ self.current_state == other.current_state and
+ self.past_state == other.past_state and
self.network == other.network)
def __bool__(self):
@@ -92,8 +89,8 @@ class Subsystem:
return len(self.nodes) < len(other.nodes)
def __hash__(self):
- return hash((frozenset(self.nodes), self.current_state.tostring(),
- self.past_state.tostring(), self.network))
+ return hash((frozenset(self.nodes), self.current_state,
+ self.past_state, self.network))
def cause_repertoire(self, mechanism, purview, cut=None):
"""Return the cause repertoire of a mechanism over a purview.
|
Use tuples for subsystem state
|
wmayner_pyphi
|
train
|
a420cbc0812fa2d8f3b5cbc7584f062cf46673b2
|
diff --git a/src/Sanitizer.php b/src/Sanitizer.php
index <HASH>..<HASH> 100644
--- a/src/Sanitizer.php
+++ b/src/Sanitizer.php
@@ -123,8 +123,8 @@ class Sanitizer implements Contracts\Sanitizer
{
$cast = \igorw\get_in($this->casts, (array) $group);
- if ($cast instanceof Contracts\Cast) {
- return $cast;
+ if (is_subclass_of($cast, Contracts\Cast::class)) {
+ return is_string($cast) ? new $cast() : $cast;
}
}
}
|
Allow to lazy-load cast instance.
|
laravie_codex
|
train
|
821656e6e8a607ed87fef8fc82733f2b540f4c15
|
diff --git a/tasks/CleanupGeneratedPdf.php b/tasks/CleanupGeneratedPdf.php
index <HASH>..<HASH> 100644
--- a/tasks/CleanupGeneratedPdf.php
+++ b/tasks/CleanupGeneratedPdf.php
@@ -7,7 +7,7 @@ class CleanupGeneratedPdfBuildTask extends BuildTask {
go to download them. This is most useful when templates have been changed so users should receive a new copy';
public function run($request) {
- $path = sprintf('%s/%s', BASE_PATH, BasePage::$generated_pdf_path);
+ $path = sprintf('%s/%s', BASE_PATH, BasePage::config()->generated_pdf_path);
if(!file_exists($path)) return false;
exec(sprintf('rm %s/*', $path), $output, $return_val);
|
BUG Fix incorrect access of private static
|
silverstripe_cwp
|
train
|
640a6958833d8313ec1f8e67516e5d0ba38b9dbb
|
diff --git a/kitnirc/client.py b/kitnirc/client.py
index <HASH>..<HASH> 100644
--- a/kitnirc/client.py
+++ b/kitnirc/client.py
@@ -629,7 +629,7 @@ def _parse_msg(client, command, actor, args):
recipient, _, message = args.partition(' :')
chantypes = client.server.features.get("CHANTYPES", "#")
if recipient[0] in chantypes:
- recipient = client.server.channels.get(recipient.lower()) or recipient
+ recipient = client.server.get_channel(recipient) or recipient.lower()
else:
recipient = User(recipient)
client.dispatch_event(command, actor, recipient, message)
|
Convert one more instance to get_channel
|
ayust_kitnirc
|
train
|
ecf6b2577d3857c0061fc8b19e65136e70805a8d
|
diff --git a/hazelcast/src/test/java/com/hazelcast/jet/core/GracefulShutdownTest.java b/hazelcast/src/test/java/com/hazelcast/jet/core/GracefulShutdownTest.java
index <HASH>..<HASH> 100644
--- a/hazelcast/src/test/java/com/hazelcast/jet/core/GracefulShutdownTest.java
+++ b/hazelcast/src/test/java/com/hazelcast/jet/core/GracefulShutdownTest.java
@@ -28,20 +28,16 @@ import com.hazelcast.jet.core.processor.SinkProcessors;
import com.hazelcast.jet.impl.JetServiceBackend;
import com.hazelcast.jet.impl.JobRepository;
import com.hazelcast.map.MapStore;
-import com.hazelcast.test.HazelcastSerialParametersRunnerFactory;
+import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.SlowTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameter;
-import org.junit.runners.Parameterized.Parameters;
import javax.annotation.Nonnull;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -61,9 +57,8 @@ import static java.util.concurrent.TimeUnit.HOURS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-@RunWith(Parameterized.class)
@Category({SlowTest.class, ParallelJVMTest.class})
-@Parameterized.UseParametersRunnerFactory(HazelcastSerialParametersRunnerFactory.class)
+@RunWith(HazelcastSerialClassRunner.class)
public class GracefulShutdownTest extends JetTestSupport {
private static final int NODE_COUNT = 2;
@@ -71,18 +66,6 @@ public class GracefulShutdownTest extends JetTestSupport {
private HazelcastInstance[] instances;
private HazelcastInstance client;
- /**
- * If {@code true} shutdown HazelcastInstance otherwise shutdown
- * JetInstance. See {@link #shutdown(HazelcastInstance)}.
- */
- @Parameter
- public boolean gracefulShutdown;
-
- @Parameters(name = "gracefulShutdown: {0}")
- public static Collection<Boolean> gracefulShutdownFns() {
- return Arrays.asList(true, false);
- }
-
@Before
public void setup() {
TestProcessors.reset(0);
@@ -130,7 +113,7 @@ public class GracefulShutdownTest extends JetTestSupport {
// When
logger.info("Shutting down instance...");
- shutdown(instances[shutDownInstance]);
+ instances[shutDownInstance].shutdown();
logger.info("Joining job...");
job.join();
logger.info("Joined");
@@ -166,7 +149,7 @@ public class GracefulShutdownTest extends JetTestSupport {
dag.newVertex("v", (SupplierEx<Processor>) NoOutputSourceP::new);
Job job = instances[0].getJet().newJob(dag);
assertJobStatusEventually(job, JobStatus.RUNNING, 10);
- Future future = spawn(() -> shutdown(liteMember));
+ Future future = spawn(() -> liteMember.shutdown());
assertTrueAllTheTime(() -> assertEquals(RUNNING, job.getStatus()), 5);
future.get();
}
@@ -180,7 +163,7 @@ public class GracefulShutdownTest extends JetTestSupport {
Future future = spawn(() -> {
HazelcastInstance nonParticipatingMember = createHazelcastInstance();
sleepSeconds(1);
- shutdown(nonParticipatingMember);
+ nonParticipatingMember.shutdown();
});
assertTrueAllTheTime(() -> assertEquals(RUNNING, job.getStatus()), 5);
future.get();
@@ -219,7 +202,7 @@ public class GracefulShutdownTest extends JetTestSupport {
job.restart();
assertTrueEventually(() -> assertTrue("blocking did not happen", BlockingMapStore.wasBlocked), 5);
- Future shutdownFuture = spawn(() -> shutdown(instances[1]));
+ Future shutdownFuture = spawn(() -> instances[1].shutdown());
logger.info("savedCounters=" + EmitIntegersP.savedCounters);
int minCounter = EmitIntegersP.savedCounters.values().stream().mapToInt(Integer::intValue).min().getAsInt();
BlockingMapStore.shouldBlock = false;
@@ -235,14 +218,6 @@ public class GracefulShutdownTest extends JetTestSupport {
assertEquals(expected, actual);
}
- private void shutdown(HazelcastInstance instance) {
- if (gracefulShutdown) {
- instance.shutdown();
- } else {
- instance.getLifecycleService().terminate();
- }
- }
-
private static final class EmitIntegersP extends AbstractProcessor {
static final ConcurrentMap<Integer, Integer> savedCounters = new ConcurrentHashMap<>();
|
Fix c.h.jet.core.GracefulShutdownTest (#<I>)
In hazelcast#<I>, I changed a parameter in this test class to test a
forceful shutdown scenario since I thought it was already doing it.
But, this was a completely wrong assumption. In this PR, removed this
forceful shutdown scenario added by mistake.
|
hazelcast_hazelcast
|
train
|
daa230a3c143c77b2fb8c1225fef65171cae7a12
|
diff --git a/discord.go b/discord.go
index <HASH>..<HASH> 100644
--- a/discord.go
+++ b/discord.go
@@ -16,7 +16,7 @@ package discordgo
import "fmt"
// Discordgo Version, follows Symantic Versioning. (http://semver.org/)
-const VERSION = "0.9.0"
+const VERSION = "0.10.0-alpha"
// New creates a new Discord session and will automate some startup
// tasks if given enough information to do so. Currently you can pass zero
|
Bump dev version to <I>-alpha
|
bwmarrin_discordgo
|
train
|
333193797b6571f5b27d4c17cd5c77b67c0b1b96
|
diff --git a/src/commands/build/IOSBuilder.js b/src/commands/build/IOSBuilder.js
index <HASH>..<HASH> 100644
--- a/src/commands/build/IOSBuilder.js
+++ b/src/commands/build/IOSBuilder.js
@@ -59,6 +59,10 @@ export default class IOSBuilder extends BaseBuilder {
bundleIdentifierIOS: bundleIdentifier,
} } = await Exp.getPublishInfoAsync(this.projectDir);
+ if (!bundleIdentifier) {
+ throw new XDLError(ErrorCode.INVALID_OPTIONS, `Your project must have a bundleIdentifier set in exp.json. See https://docs.getexponent.com/versions/latest/guides/building-standalone-apps.html`);
+ }
+
const credentialMetadata = {
username,
experienceName,
@@ -100,6 +104,16 @@ export default class IOSBuilder extends BaseBuilder {
}
}
+ // ensure that the app id exists or is created
+ try {
+ await Credentials.ensureAppId(credentialMetadata);
+ } catch (e) {
+ throw new XDLError(
+ ErrorCode.CREDENTIAL_ERROR,
+ `It seems like we can't create an app on the Apple developer center with this app id: ${bundleIdentifier}. Please change your bundle identifier to something else.`
+ );
+ }
+
if (!hasPushCert) {
await this.askForPushCerts(credentialMetadata);
} else {
|
Ensure App ID exists on developer portal before fetching certificates
fbshipit-source-id: b<I>f9b
|
expo_exp
|
train
|
a4372a9b5fb5a6e3a881996e66ec5d22a0d070f8
|
diff --git a/lang/en/moodle.php b/lang/en/moodle.php
index <HASH>..<HASH> 100644
--- a/lang/en/moodle.php
+++ b/lang/en/moodle.php
@@ -903,6 +903,7 @@ $string['numattempts'] = '$a failed login attempt(s) ';
$string['numberweeks'] = 'Number of weeks/topics';
$string['numdays'] = '$a days';
$string['numhours'] = '$a hours';
+$string['numletters'] = '$a letters';
$string['numminutes'] = '$a minutes';
$string['numseconds'] = '$a seconds';
$string['numviews'] = '$a views';
|
To count letters in languages without word separators.
|
moodle_moodle
|
train
|
dd6c2125639fd9f417e6ca85c710f76e93f00cc7
|
diff --git a/jacquard/merge.py b/jacquard/merge.py
index <HASH>..<HASH> 100644
--- a/jacquard/merge.py
+++ b/jacquard/merge.py
@@ -151,12 +151,12 @@ def _compile_metaheaders(incoming_headers,
def _write_metaheaders(file_writer, all_headers):
file_writer.write("\n".join(all_headers) + "\n")
-def _create_reader_lists(input_files):
+def _create_reader_lists(file_readers):
buffered_readers = []
vcf_readers = []
- for input_file in input_files:
- vcf_reader = vcf.VcfReader(vcf.FileReader(input_file))
+ for file_reader in file_readers:
+ vcf_reader = vcf.VcfReader(file_reader)
vcf_readers.append(vcf_reader)
vcf_reader.open()
@@ -435,13 +435,14 @@ def execute(args, execution_context):
format_tag_regex = _DEFAULT_INCLUDED_FORMAT_TAGS
input_files = sorted(glob.glob(os.path.join(input_path, "*.vcf")))
+ file_readers = [vcf.FileReader(i) for i in input_files]
+ _validate_consistent_samples(file_readers)
try:
file_writer = vcf.FileWriter(output_path)
file_writer.open()
- buffered_readers, vcf_readers = _create_reader_lists(input_files)
-
+ buffered_readers, vcf_readers = _create_reader_lists(file_readers)
vcf_readers = _sort_readers(vcf_readers, output_path)
all_sample_names, merge_metaheaders = _build_sample_list(vcf_readers)
coordinates = _build_coordinates(vcf_readers)
diff --git a/test/merge_test.py b/test/merge_test.py
index <HASH>..<HASH> 100644
--- a/test/merge_test.py
+++ b/test/merge_test.py
@@ -389,7 +389,7 @@ class MergeTestCase(test_case.JacquardBaseTestCase):
"##source=strelka\n"
"#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tSample_C\tSample_D\n"
"chr2\t32\t.\tA\tT\t.\t.\t.\tDP\t24\t53\n")
- input_files = [fileA, fileB]
+ input_files = [vcf.FileReader(fileA), vcf.FileReader(fileB)]
buffered_readers, vcf_readers = merge._create_reader_lists(input_files)
for vcf_reader in vcf_readers:
|
ex-<I> (jebene) - hooked up sample validation step to merge
|
umich-brcf-bioinf_Jacquard
|
train
|
43f83c0c749b6de615ea18a4f64e64ee3cb6cf42
|
diff --git a/repository-hdfs/src/itest/java/org/elasticsearch/repositories/hdfs/HdfsSnapshotRestoreTest.java b/repository-hdfs/src/itest/java/org/elasticsearch/repositories/hdfs/HdfsSnapshotRestoreTest.java
index <HASH>..<HASH> 100644
--- a/repository-hdfs/src/itest/java/org/elasticsearch/repositories/hdfs/HdfsSnapshotRestoreTest.java
+++ b/repository-hdfs/src/itest/java/org/elasticsearch/repositories/hdfs/HdfsSnapshotRestoreTest.java
@@ -148,6 +148,10 @@ public class HdfsSnapshotRestoreTest extends ElasticsearchIntegrationTest {
assertThat(clusterState.getMetaData().hasIndex("test-idx-2"), equalTo(false));
}
+ private void wipeIndices(String... indices) {
+ cluster().wipeIndices(indices);
+ }
+
@Test
public void testWrongPath() {
Client client = client();
|
Upgrade HDFS repo tests to ES <I>
|
elastic_elasticsearch-hadoop
|
train
|
025a3f8e0b995aa4bfa0d9139cc4c6e000d66758
|
diff --git a/transport/wseb/src/test/java/org/kaazing/gateway/transport/wseb/DuplicateBindTest.java b/transport/wseb/src/test/java/org/kaazing/gateway/transport/wseb/DuplicateBindTest.java
index <HASH>..<HASH> 100644
--- a/transport/wseb/src/test/java/org/kaazing/gateway/transport/wseb/DuplicateBindTest.java
+++ b/transport/wseb/src/test/java/org/kaazing/gateway/transport/wseb/DuplicateBindTest.java
@@ -70,12 +70,12 @@ public class DuplicateBindTest {
service().
name("echo1").
type("echo").
- accept(URI.create("ws://localhost:8000/")).
+ accept(URI.create("wse://localhost:8000/")).
done().
service().
name("echo2").
type("echo").
- accept(URI.create("ws://localhost:8000/")).
+ accept(URI.create("wse://localhost:8000/")).
done().
done();
// @formatter:on
|
Changed accept uri scheme to wse in DuplicateBindTest
|
kaazing_gateway
|
train
|
53308027bb230f7b164448e7ced4b8c78897b464
|
diff --git a/src/continuous.js b/src/continuous.js
index <HASH>..<HASH> 100644
--- a/src/continuous.js
+++ b/src/continuous.js
@@ -71,22 +71,22 @@ export default function continuous(deinterpolate, reinterpolate) {
range = unit,
interpolate = interpolateValue,
clamp = false,
+ piecewise,
output,
input;
function rescale() {
- var map = Math.min(domain.length, range.length) > 2 ? polymap : bimap;
- output = map(domain, range, clamp ? deinterpolateClamp(deinterpolate) : deinterpolate, interpolate);
- input = map(range, domain, deinterpolateLinear, clamp ? reinterpolateClamp(reinterpolate) : reinterpolate);
+ piecewise = Math.min(domain.length, range.length) > 2 ? polymap : bimap;
+ output = input = null;
return scale;
}
function scale(x) {
- return output(+x);
+ return (output || (output = piecewise(domain, range, clamp ? deinterpolateClamp(deinterpolate) : deinterpolate, interpolate)))(+x);
}
scale.invert = function(y) {
- return input(+y);
+ return (input || (input = piecewise(range, domain, deinterpolateLinear, clamp ? reinterpolateClamp(reinterpolate) : reinterpolate)))(+y);
};
scale.domain = function(_) {
|
Defer interpolation creation.
This avoids creating interpolators that are unused, such as a scale that is
never inverted and the intermediate state of a scale during copy.
|
d3_d3-scale
|
train
|
8f7b7b3ea5ab02fac299974588f7756c0af596d5
|
diff --git a/pymc/distributions.py b/pymc/distributions.py
index <HASH>..<HASH> 100755
--- a/pymc/distributions.py
+++ b/pymc/distributions.py
@@ -2799,11 +2799,12 @@ def _inject_dist(distname, kwargs={}, ns=locals()):
Reusable function to inject Stochastic subclasses into module
namespace
"""
- dist_logp, dist_random = name_to_funcs(dist, ns)
- classname = capitalize(dist)
- ns[classname]= stochastic_from_dist(dist, dist_logp,
+ dist_logp, dist_random = name_to_funcs(distname, ns)
+ classname = capitalize(distname)
+ ns[classname]= stochastic_from_dist(distname, dist_logp,
dist_random, **kwargs)
+
for dist in sc_continuous_distributions:
_inject_dist(dist)
@@ -2818,6 +2819,7 @@ for dist in mv_discrete_distributions:
_inject_dist('bernoulli', {'dtype' : np.bool})
+
def uninformative_like(x):
"""
uninformative_like(x)
|
Fixed bug in _inject_dist
|
pymc-devs_pymc
|
train
|
b3bd67d82105474be5bcce7c7a107e9de60472c5
|
diff --git a/src/Framework/ServiceLocator/Loader/ConsoleConfigLoader.php b/src/Framework/ServiceLocator/Loader/ConsoleConfigLoader.php
index <HASH>..<HASH> 100644
--- a/src/Framework/ServiceLocator/Loader/ConsoleConfigLoader.php
+++ b/src/Framework/ServiceLocator/Loader/ConsoleConfigLoader.php
@@ -5,10 +5,15 @@ namespace ExtendsFramework\Console\Framework\ServiceLocator\Loader;
use ExtendsFramework\Console\Framework\ServiceLocator\Factory\ShellFactory;
use ExtendsFramework\Console\Framework\ServiceLocator\Factory\TerminalFactory;
+use ExtendsFramework\Console\Input\InputInterface;
+use ExtendsFramework\Console\Input\Posix\PosixInput;
+use ExtendsFramework\Console\Output\OutputInterface;
+use ExtendsFramework\Console\Output\Posix\PosixOutput;
use ExtendsFramework\Console\Shell\ShellInterface;
use ExtendsFramework\Console\Terminal\TerminalInterface;
use ExtendsFramework\ServiceLocator\Config\Loader\LoaderInterface;
use ExtendsFramework\ServiceLocator\Resolver\Factory\FactoryResolver;
+use ExtendsFramework\ServiceLocator\Resolver\Invokable\InvokableResolver;
use ExtendsFramework\ServiceLocator\ServiceLocatorInterface;
class ConsoleConfigLoader implements LoaderInterface
@@ -24,6 +29,10 @@ class ConsoleConfigLoader implements LoaderInterface
ShellInterface::class => ShellFactory::class,
TerminalInterface::class => TerminalFactory::class,
],
+ InvokableResolver::class => [
+ InputInterface::class => PosixInput::class,
+ OutputInterface::class => PosixOutput::class,
+ ],
],
];
}
diff --git a/test/Framework/ServiceLocator/Loader/ConsoleConfigLoaderTest.php b/test/Framework/ServiceLocator/Loader/ConsoleConfigLoaderTest.php
index <HASH>..<HASH> 100644
--- a/test/Framework/ServiceLocator/Loader/ConsoleConfigLoaderTest.php
+++ b/test/Framework/ServiceLocator/Loader/ConsoleConfigLoaderTest.php
@@ -5,9 +5,14 @@ namespace ExtendsFramework\Console\Framework\ServiceLocator\Loader;
use ExtendsFramework\Console\Framework\ServiceLocator\Factory\ShellFactory;
use ExtendsFramework\Console\Framework\ServiceLocator\Factory\TerminalFactory;
+use ExtendsFramework\Console\Input\InputInterface;
+use ExtendsFramework\Console\Input\Posix\PosixInput;
+use ExtendsFramework\Console\Output\OutputInterface;
+use ExtendsFramework\Console\Output\Posix\PosixOutput;
use ExtendsFramework\Console\Shell\ShellInterface;
use ExtendsFramework\Console\Terminal\TerminalInterface;
use ExtendsFramework\ServiceLocator\Resolver\Factory\FactoryResolver;
+use ExtendsFramework\ServiceLocator\Resolver\Invokable\InvokableResolver;
use ExtendsFramework\ServiceLocator\ServiceLocatorInterface;
use PHPUnit\Framework\TestCase;
@@ -30,6 +35,10 @@ class ConsoleConfigLoaderTest extends TestCase
ShellInterface::class => ShellFactory::class,
TerminalInterface::class => TerminalFactory::class,
],
+ InvokableResolver::class => [
+ InputInterface::class => PosixInput::class,
+ OutputInterface::class => PosixOutput::class,
+ ],
],
], $loader->load());
}
|
Added InputInterface and OutputInterface to framework config loader.
|
extendsframework_extends-console
|
train
|
2894a683268307ce5573b6da6877ba0117b72656
|
diff --git a/lib/roar/representer/transport/net_http.rb b/lib/roar/representer/transport/net_http.rb
index <HASH>..<HASH> 100644
--- a/lib/roar/representer/transport/net_http.rb
+++ b/lib/roar/representer/transport/net_http.rb
@@ -31,7 +31,7 @@ module Roar
private
def do_request(what, uri, as, body="")
# DISCUSS: can this be made easier?
- uri = URI(uri)
+ uri = parse_uri(uri)
http = Net::HTTP.new(uri.host, uri.port)
req = what.new(uri.request_uri)
@@ -42,6 +42,12 @@ module Roar
http.request(req)
end
+
+ def parse_uri(url)
+ uri = URI(url)
+ raise "Incorrect URL `#{url}`. Maybe you forgot http://?" if uri.instance_of?(URI::Generic)
+ uri
+ end
end
end
end
diff --git a/test/net_http_transport_test.rb b/test/net_http_transport_test.rb
index <HASH>..<HASH> 100644
--- a/test/net_http_transport_test.rb
+++ b/test/net_http_transport_test.rb
@@ -30,7 +30,7 @@ class NetHTTPTransportTest < MiniTest::Spec
end
it "complains with invalid URL" do
- assert_raises do
+ assert_raises RuntimeError do
@transport.get_uri("example.com", as)
end
end
|
raise an exception when URL invalid in Net::Http. this is a common error when people forget to prepend http:// and prevents them from having to debug "undefined method `request_uri' .
|
trailblazer_roar
|
train
|
dd772955331830c2143e39f9fba580fb1c08d758
|
diff --git a/plugins/guests/smartos/cap/rsync.rb b/plugins/guests/smartos/cap/rsync.rb
index <HASH>..<HASH> 100644
--- a/plugins/guests/smartos/cap/rsync.rb
+++ b/plugins/guests/smartos/cap/rsync.rb
@@ -17,7 +17,7 @@ module VagrantPlugins
end
def self.rsync_post(machine, opts)
- machine.communicate.execute("find '#{opts[:guestpath]}' '(' ! -user #{opts[:owner]} -or ! -group #{opts[:group]} ')' -print0 | " +
+ machine.communicate.execute("#{machine.config.smartos.suexec_cmd} find '#{opts[:guestpath]}' '(' ! -user #{opts[:owner]} -or ! -group #{opts[:group]} ')' -print0 | " +
"#{machine.config.smartos.suexec_cmd} xargs -0 chown #{opts[:owner]}:#{opts[:group]}")
end
end
diff --git a/test/unit/plugins/guests/smartos/cap/rsync_test.rb b/test/unit/plugins/guests/smartos/cap/rsync_test.rb
index <HASH>..<HASH> 100644
--- a/test/unit/plugins/guests/smartos/cap/rsync_test.rb
+++ b/test/unit/plugins/guests/smartos/cap/rsync_test.rb
@@ -40,7 +40,7 @@ describe "VagrantPlugins::VagrantPlugins::Cap::Rsync" do
describe ".rsync_post" do
it 'chowns incorrectly owned files in sync dir' do
- communicator.expect_command("find '/sync_dir' '(' ! -user somebody -or ! -group somegroup ')' -print0 | pfexec xargs -0 chown somebody:somegroup")
+ communicator.expect_command("pfexec find '/sync_dir' '(' ! -user somebody -or ! -group somegroup ')' -print0 | pfexec xargs -0 chown somebody:somegroup")
plugin.rsync_post(machine, guestpath: '/sync_dir', owner: 'somebody', group: 'somegroup')
end
end
|
Ensure rsync_post has find permissions on smartos
|
hashicorp_vagrant
|
train
|
0f94ccffc8a1e57bd976e028e90e6ae5c94dda2a
|
diff --git a/firenado/session.py b/firenado/session.py
index <HASH>..<HASH> 100644
--- a/firenado/session.py
+++ b/firenado/session.py
@@ -65,7 +65,6 @@ class SessionEngine(object):
session = self.__renew_session(request_handler)
else:
session.id = session_id
- # TODO: Check if the session is stored
if not self.session_handler.is_session_stored(session_id):
if not cookie_created_on_request:
# Regenerating the session id. Because the
@@ -237,13 +236,26 @@ class SessionHandler(object):
@staticmethod
def create_session_id_cookie(request_handler):
session_id = SessionHandler.__generate_session_id()
- request_handler.set_cookie(
- firenado.conf.session['name'], session_id,
- **SessionHandler.__session_id_cookie_settings())
+ if 'cookie_secret' in request_handler.application.settings:
+ settings = SessionHandler.__session_id_cookie_settings(secret=True)
+ expires_days = settings.pop('expires_days')
+ request_handler.set_secure_cookie(
+ firenado.conf.session['name'], session_id,
+ expires_days=expires_days)
+ else:
+ request_handler.set_cookie(
+ name=firenado.conf.session['name'], value=session_id,
+ **SessionHandler.__session_id_cookie_settings())
return session_id
@staticmethod
def get_session_id_cookie(request_handler):
+ if 'cookie_secret' in request_handler.application.settings:
+ cookie_id = request_handler.get_secure_cookie(
+ firenado.conf.session['name'])
+ if cookie_id is not None:
+ return cookie_id.decode()
+ return cookie_id
return request_handler.get_cookie(firenado.conf.session['name'])
def is_session_stored(self, session_id):
@@ -256,11 +268,13 @@ class SessionHandler(object):
self.settings = settings
@staticmethod
- def __session_id_cookie_settings():
+ def __session_id_cookie_settings(secret=False):
""" Defines some settings to be used with the session id cookie. """
cookie_settings = {}
cookie_settings.setdefault('expires', None)
cookie_settings.setdefault('expires_days', None)
+ if secret:
+ cookie_settings['expires_days'] = 30
return cookie_settings
@staticmethod
|
If cookie_secret is set the session_id cookie will be encripted.
Fixes: #<I>
|
candango_firenado
|
train
|
3ff77426ddabcb2407221b5b40ac4c958439075e
|
diff --git a/mopidy_alarmclock/alarm_manager.py b/mopidy_alarmclock/alarm_manager.py
index <HASH>..<HASH> 100644
--- a/mopidy_alarmclock/alarm_manager.py
+++ b/mopidy_alarmclock/alarm_manager.py
@@ -4,6 +4,8 @@ from __future__ import unicode_literals
import datetime
import os
import time
+import logging
+import mopidy
from threading import Timer
@@ -23,6 +25,7 @@ class AlarmManager(object):
core = None
state = states.DISABLED
idle_timer = None
+ logger = logging.getLogger(__name__)
def get_core(self, core):
self.core = core
@@ -80,15 +83,19 @@ class AlarmManager(object):
self.idle()
- def play(self):
+ def play(self, fallback = False):
+ self.logger.info("AlarmClock alarm started (fallback %s)", fallback)
self.core.playback.stop()
self.core.tracklist.clear()
try:
+ if fallback:
+ raise Exception('Fallback')
self.core.tracklist.add(self.get_playlist().tracks)
if self.core.tracklist.length.get() < 1:
raise Exception('Tracklist empty')
- except:
+ except Exception as e:
+ self.logger.info("AlarmClock using backup alarm, reason: %s", e)
self.core.tracklist.add(None, 0, 'file://' + os.path.join(os.path.dirname(__file__), 'backup-alarm.mp3'))
self.core.tracklist.consume = False
@@ -100,11 +107,25 @@ class AlarmManager(object):
self.core.playback.next()
self.core.playback.mute = False
-
- self.adjust_volume(self.volume, self.volume_increase_seconds, 0)
+ self.core.playback.volume = 0
self.core.playback.play()
+ if not fallback: # do fallback only once
+ self.logger.info("AlarmClock waiting for playback to start")
+ time.sleep(0.5)
+ waited = 0.5
+ while waited <= 30 and (self.core.playback.state != mopidy.core.PlaybackState.PLAYING or self.core.playback.time_position < 100):
+ time.sleep(0.5)
+ waited += 0.5
+ if self.core.playback.state != mopidy.core.PlaybackState.PLAYING or self.core.playback.time_position < 100:
+ self.logger.info("AlarmClock playback did NOT start after %.1f seconds", waited)
+ self.play(True)
+ return
+ self.logger.info("AlarmClock playback started within %.1f seconds", waited)
+
+ self.adjust_volume(self.volume, self.volume_increase_seconds, 0)
+
self.reset()
self.state = states.DISABLED
@@ -126,8 +147,10 @@ class AlarmManager(object):
pass
if step_no == 0 or not isinstance(current_volume, int) or current_volume == int(round(target_volume * (step_no) / (number_of_steps + 1))):
if step_no >= number_of_steps: # this design should prevent floating-point edge-case bugs (in case such bugs could be possible here)
+ self.logger.info("AlarmClock increasing volume to target volume %d", target_volume)
self.core.playback.volume = target_volume
else:
+ self.logger.info("AlarmClock increasing volume to %d", int(round(target_volume * (step_no + 1) / (number_of_steps + 1))))
self.core.playback.volume = int(round(target_volume * (step_no + 1) / (number_of_steps + 1)))
t = Timer(increase_duration / number_of_steps, self.adjust_volume, [target_volume, increase_duration, step_no + 1])
t.start()
|
Improved fallback and added logging
Fallback to built-in backup alarm will happen if no playback is started
within <I> seconds.
Logging has been added for better troubleshooting.
|
DavisNT_mopidy-alarmclock
|
train
|
e4f73c99e639e780c42f77b6300c8a4febee53b1
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -7,14 +7,15 @@ with io.open('README.rst', 'rt', encoding='utf8') as f:
setup(
name='pkg-info',
- version='0.1.1',
+ version='0.1.2',
url='https://github.com/acifani/pkg-info',
license='BSD',
author='Alessandro Cifani',
author_email='alessandro.cifani@gmail.com',
description='Tiny library to fetch package info from PyPI.',
long_description=readme,
- py_modules=["pkg_info"],
+ py_modules=['pkg_info'],
+ install_requires=['requests'],
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
|
Add requests dependency to setup.py
|
acifani_pkg-info
|
train
|
c7deb2aebe1fe6e297e713aa0acf300c22650451
|
diff --git a/moco-core/src/main/java/com/github/dreamhead/moco/resource/ResourceFactory.java b/moco-core/src/main/java/com/github/dreamhead/moco/resource/ResourceFactory.java
index <HASH>..<HASH> 100644
--- a/moco-core/src/main/java/com/github/dreamhead/moco/resource/ResourceFactory.java
+++ b/moco-core/src/main/java/com/github/dreamhead/moco/resource/ResourceFactory.java
@@ -93,7 +93,8 @@ public final class ResourceFactory {
@Override
public final MessageContent readFor(final Request request) {
- return readFor(Optional.fromNullable(request));
+ String text = HttpProtocolVersion.versionOf(version.readFor(request).toString()).text();
+ return content(text);
}
});
}
|
replaced readFor without optional in version resource
|
dreamhead_moco
|
train
|
5e47884a641e7e152ed6abd0259c412fe16e8c1b
|
diff --git a/lib/github.rb b/lib/github.rb
index <HASH>..<HASH> 100644
--- a/lib/github.rb
+++ b/lib/github.rb
@@ -39,7 +39,7 @@ module GitHub
end
def activate(args)
- @options = parse_options(args)
+ parse_options(args)
load 'helpers.rb'
load 'commands.rb'
invoke(args.shift, *args)
@@ -69,7 +69,7 @@ module GitHub
def parse_options(args)
@debug = args.delete('--debug')
- args.inject({}) do |memo, arg|
+ @options = args.inject({}) do |memo, arg|
if arg =~ /^--([^=]+)=(.+)/
args.delete(arg)
memo.merge($1.to_sym => $2)
diff --git a/spec/ui_spec.rb b/spec/ui_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/ui_spec.rb
+++ b/spec/ui_spec.rb
@@ -79,6 +79,7 @@ EOF
def run
self.instance_eval &@block
+ GitHub.parse_options(@args)
GitHub.invoke(@cmd_name, *@args)
@stdout_mock.invoke unless @stdout_mock.nil?
end
|
Parse options before running commands in ui_spec
|
defunkt_github-gem
|
train
|
eb18846754de1471b12062116a9e181df233e146
|
diff --git a/eqcorrscan/utils/stacking.py b/eqcorrscan/utils/stacking.py
index <HASH>..<HASH> 100644
--- a/eqcorrscan/utils/stacking.py
+++ b/eqcorrscan/utils/stacking.py
@@ -120,10 +120,14 @@ def align_traces(trace_list, shift_len, master=False):
master=traces[i]
MAD_master=np.median(np.abs(master.data))
master_no=i
+ else:
+ print 'Using master given by user'
shifts=[]
+ ccs=[]
for i in xrange(len(traces)):
if not master.stats.sampling_rate == traces[i].stats.sampling_rate:
raise ValueError('Sampling rates not the same')
shift, cc=xcorr(master, traces[i], shift_len)
shifts.append(shift/master.stats.sampling_rate)
- return shifts
+ ccs.append(cc)
+ return shifts, ccs
|
Add master option to clustering.align_traces, alignment can be forced to this
Former-commit-id: <I>a5a0e6aaadf<I>a1f6b9ea<I>e<I>eb<I>
|
eqcorrscan_EQcorrscan
|
train
|
8e6def047e149aedb689dde8becc38914e1c9080
|
diff --git a/lib/Process/ChannelledProcess.php b/lib/Process/ChannelledProcess.php
index <HASH>..<HASH> 100644
--- a/lib/Process/ChannelledProcess.php
+++ b/lib/Process/ChannelledProcess.php
@@ -37,7 +37,7 @@ class ChannelledProcess implements ProcessContext, Strand {
];
$options = (\PHP_SAPI === "phpdbg" ? " -b -qrr " : " ") . $this->formatOptions($options);
- $separator = \PHP_BINARY === "phpdbg" ? " -- " : " ";
+ $separator = \PHP_SAPI === "phpdbg" ? " -- " : " ";
$command = \escapeshellarg(\PHP_BINARY) . $options . $separator . \escapeshellarg($path);
$processOptions = [];
|
Fixes the constant used
`\PHP_BINARY` will never give phpdbg, but always the full path to the
binary. You meant to use `\PHP_SAPI` here too just like on the previous
line.
|
amphp_parallel
|
train
|
919723cf4c7dc9272f4a8233ea38b574fe569778
|
diff --git a/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java b/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java
index <HASH>..<HASH> 100644
--- a/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java
+++ b/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java
@@ -632,7 +632,7 @@ public class ClassWriter extends ClassFile {
acount++;
}
acount += writeJavaAnnotations(sym.getRawAttributes());
- acount += writeTypeAnnotations(sym.getRawTypeAttributes());
+ acount += writeTypeAnnotations(sym.getRawTypeAttributes(), false);
return acount;
}
@@ -759,7 +759,7 @@ public class ClassWriter extends ClassFile {
return attrCount;
}
- int writeTypeAnnotations(List<Attribute.TypeCompound> typeAnnos) {
+ int writeTypeAnnotations(List<Attribute.TypeCompound> typeAnnos, boolean inCode) {
if (typeAnnos.isEmpty()) return 0;
ListBuffer<Attribute.TypeCompound> visibles = ListBuffer.lb();
@@ -798,6 +798,8 @@ public class ClassWriter extends ClassFile {
continue;
}
}
+ if (tc.position.type.isLocal() != inCode)
+ continue;
if (!tc.position.emitToClassfile())
continue;
switch (types.getRetention(tc)) {
@@ -1241,6 +1243,9 @@ public class ClassWriter extends ClassFile {
endAttr(alenIdx);
acount++;
}
+
+ acount += writeTypeAnnotations(code.meth.getRawTypeAttributes(), true);
+
endAttrs(acountIdx, acount);
}
//where
@@ -1627,7 +1632,7 @@ public class ClassWriter extends ClassFile {
out = null;
} finally {
if (out != null) {
- // if we are propogating an exception, delete the file
+ // if we are propagating an exception, delete the file
out.close();
outFile.delete();
outFile = null;
@@ -1741,7 +1746,7 @@ public class ClassWriter extends ClassFile {
acount += writeFlagAttrs(c.flags());
acount += writeJavaAnnotations(c.getRawAttributes());
- acount += writeTypeAnnotations(c.getRawTypeAttributes());
+ acount += writeTypeAnnotations(c.getRawTypeAttributes(), false);
acount += writeEnclosingMethodAttribute(c);
acount += writeExtraClassAttributes(c);
diff --git a/test/tools/javac/annotations/typeAnnotations/referenceinfos/ReferenceInfoUtil.java b/test/tools/javac/annotations/typeAnnotations/referenceinfos/ReferenceInfoUtil.java
index <HASH>..<HASH> 100644
--- a/test/tools/javac/annotations/typeAnnotations/referenceinfos/ReferenceInfoUtil.java
+++ b/test/tools/javac/annotations/typeAnnotations/referenceinfos/ReferenceInfoUtil.java
@@ -28,6 +28,7 @@ import java.util.Map;
import com.sun.tools.classfile.Attribute;
import com.sun.tools.classfile.ClassFile;
+import com.sun.tools.classfile.Code_attribute;
import com.sun.tools.classfile.TypeAnnotation;
import com.sun.tools.classfile.Field;
import com.sun.tools.classfile.Method;
@@ -90,6 +91,20 @@ public class ReferenceInfoUtil {
RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr;
annos.addAll(Arrays.asList(tAttr.annotations));
}
+
+ int cindex = m.attributes.getIndex(cf.constant_pool, Attribute.Code);
+ if (cindex != -1) {
+ Attribute cattr = m.attributes.get(cindex);
+ assert cattr instanceof Code_attribute;
+ Code_attribute cAttr = (Code_attribute)cattr;
+ index = cAttr.attributes.getIndex(cf.constant_pool, name);
+ if (index != -1) {
+ Attribute attr = cAttr.attributes.get(index);
+ assert attr instanceof RuntimeTypeAnnotations_attribute;
+ RuntimeTypeAnnotations_attribute tAttr = (RuntimeTypeAnnotations_attribute)attr;
+ annos.addAll(Arrays.asList(tAttr.annotations));
+ }
+ }
}
// test the result of Attributes.getIndex according to expectations
|
Put "local" type annotations into the Code attribute, not the Method attribute.
|
wmdietl_jsr308-langtools
|
train
|
cb705b51c5761e65d664ed8f9c344c96f816298d
|
diff --git a/quilt_server/views.py b/quilt_server/views.py
index <HASH>..<HASH> 100644
--- a/quilt_server/views.py
+++ b/quilt_server/views.py
@@ -307,3 +307,19 @@ def access(auth_user, owner, package_name, user):
db.session.commit()
else:
abort(request.codes.bad_request)
+
+@app.route('/api/access/<owner>/<package_name>', methods=['GET'])
+@api()
+@as_json
+def access_list(auth_user, owner, package_name):
+ accesses = (
+ Access.query
+ .join(Access.package)
+ .filter_by(owner=owner, name=package_name)
+ )
+
+ can_access = [access.user for access in accesses]
+ if not auth_user in can_access:
+ abort(404)
+
+ return dict(users=can_access)
diff --git a/tests/access_test.py b/tests/access_test.py
index <HASH>..<HASH> 100644
--- a/tests/access_test.py
+++ b/tests/access_test.py
@@ -28,7 +28,7 @@ class AccessTestCase(QuiltTestCase):
pkghash = '123'
bucket = app.config['PACKAGE_BUCKET_NAME']
pkgurl = '/api/package/{usr}/{pkg}/'.format(usr=user, pkg=pkg)
-
+
# Push a package.
resp = self.app.put(
pkgurl,
@@ -82,9 +82,8 @@ class AccessTestCase(QuiltTestCase):
sharewith = "anotheruser"
pkg = "pkgtoshare"
pkghash = '123'
- bucket = app.config['PACKAGE_BUCKET_NAME']
pkgurl = '/api/package/{usr}/{pkg}/'.format(usr=user, pkg=pkg)
-
+
# Push a package.
resp = self.app.put(
pkgurl,
@@ -118,7 +117,7 @@ class AccessTestCase(QuiltTestCase):
'Authorization': user
}
)
-
+
assert resp.status_code == requests.codes.ok
# Test that the recipient can't read the package
@@ -139,9 +138,8 @@ class AccessTestCase(QuiltTestCase):
user = "test_user"
pkg = "pkg"
pkghash = '123'
- bucket = app.config['PACKAGE_BUCKET_NAME']
pkgurl = '/api/package/{usr}/{pkg}/'.format(usr=user, pkg=pkg)
-
+
# Push a package.
resp = self.app.put(
pkgurl,
@@ -178,7 +176,7 @@ class AccessTestCase(QuiltTestCase):
pkghash = '123'
bucket = app.config['PACKAGE_BUCKET_NAME']
pkgurl = '/api/package/{usr}/{pkg}/'.format(usr=user, pkg=pkg)
-
+
# Push a package.
resp = self.app.put(
pkgurl,
@@ -236,7 +234,7 @@ class AccessTestCase(QuiltTestCase):
newhash = '234'
bucket = app.config['PACKAGE_BUCKET_NAME']
pkgurl = '/api/package/{usr}/{pkg}/'.format(usr=user, pkg=pkg)
-
+
# Push a package.
resp = self.app.put(
pkgurl,
@@ -284,3 +282,56 @@ class AccessTestCase(QuiltTestCase):
)
assert resp.status_code == requests.codes.ok
+
+ def testListAccess(self):
+ """
+ Push a package, share it and test that
+ both the owner and recipient are included
+ in the access list
+ """
+ user = "test_user"
+ sharewith = "anotheruser"
+ pkg = "pkgtoshare"
+ pkghash = '123'
+ pkgurl = '/api/package/{usr}/{pkg}/'.format(usr=user, pkg=pkg)
+
+ # Push a package.
+ resp = self.app.put(
+ pkgurl,
+ data=json.dumps(dict(
+ hash=pkghash
+ )),
+ content_type='application/json',
+ headers={
+ 'Authorization': user
+ }
+ )
+
+ assert resp.status_code == requests.codes.ok
+
+ # Share the package.
+ resp = self.app.put(
+ '/api/access/{owner}/{pkg}/{usr}'.format(owner=user, usr=sharewith, pkg=pkg),
+ content_type='application/json',
+ headers={
+ 'Authorization': user
+ }
+ )
+
+ assert resp.status_code == requests.codes.ok
+
+ # List the access for the package
+ resp = self.app.get(
+ '/api/access/{owner}/{pkg}'.format(owner=user, pkg=pkg),
+ headers={
+ 'Authorization': sharewith
+ }
+ )
+
+ assert resp.status_code == requests.codes.ok
+
+ data = json.loads(resp.data.decode('utf8'))
+ can_access = data.get('users')
+ assert len(can_access) == 2
+ assert user in can_access
+ assert sharewith in can_access
|
Implement list access
List the users who can access a data package (only allowed for users
who have access).
|
quiltdata_quilt
|
train
|
68a190c8f7b62ab7b8afd62bf6bcd75248efb260
|
diff --git a/templates/web/prod/thesaurus.js b/templates/web/prod/thesaurus.js
index <HASH>..<HASH> 100644
--- a/templates/web/prod/thesaurus.js
+++ b/templates/web/prod/thesaurus.js
@@ -474,7 +474,7 @@ function T_search(menuItem, menu, cmenu, e, label)
v = '*:"' + term.replace("(", "[").replace(")", "]") + '"';
var nck = 0;
- $('#adv_search :checkbox[name=bas\[\]]').each(function(a)
+ $('#searchForm .adv_options :checkbox[name="bases[]"]').each(function(a)
{
bas2sbas["b"+this.value].ckobj = this;
bas2sbas["b"+this.value].waschecked = this.checked;
@@ -776,7 +776,7 @@ function CXdblClick(e)
function doThesSearch(type, sbid, term, field)
{
var nck = 0;
- $('#adv_search input[name="bases[]"]').each(
+ $('#searchForm .adv_options :checkbox[name="bases[]"]').each(
function(i,n)
{
var base_id = $(n).val();
diff --git a/www/skins/prod/jquery.main-prod.js b/www/skins/prod/jquery.main-prod.js
index <HASH>..<HASH> 100644
--- a/www/skins/prod/jquery.main-prod.js
+++ b/www/skins/prod/jquery.main-prod.js
@@ -1412,6 +1412,9 @@ $(document).ready(function(){
$('#idFrameC .tabs').tabs({
activate: function(event, ui){
+ if(ui.newTab.context.hash == "#thesaurus_tab") {
+ thesau_show();
+ }
p4.WorkZone.open();
}
});
|
Fix #<I> : Thesaurus queries don't work
|
alchemy-fr_Phraseanet
|
train
|
9f93577cea09e62a678fb812ad5b5edba48c155d
|
diff --git a/pypot/vrep/__init__.py b/pypot/vrep/__init__.py
index <HASH>..<HASH> 100644
--- a/pypot/vrep/__init__.py
+++ b/pypot/vrep/__init__.py
@@ -14,7 +14,6 @@ import time as sys_time
class vrep_time():
-
def __init__(self, vrep_io):
self.io = vrep_io
@@ -108,8 +107,12 @@ def from_vrep(config, vrep_host, vrep_port, vrep_scene,
if tracked_collisions:
vct.stop()
+ vc.stop()
+
vrep_io.restart_simulation()
+ vc.start()
+
if tracked_objects:
vot.start()
diff --git a/pypot/vrep/io.py b/pypot/vrep/io.py
index <HASH>..<HASH> 100644
--- a/pypot/vrep/io.py
+++ b/pypot/vrep/io.py
@@ -231,7 +231,7 @@ class VrepIO(AbstractIO):
time.sleep(VrepIO.TIMEOUT)
if any(err):
- msg = ' '.join([vrep_error[i] for i, e in enumerate(err) if e])
+ msg = ' '.join([vrep_error[2 ** i] for i, e in enumerate(err) if e])
raise VrepIOError(msg)
return res
|
Fix a bug in the v-rep checking error.
Also stop the motor controller when resetting the v-rep simulation.
|
poppy-project_pypot
|
train
|
debadb6a71eb40498a1dd43ed9e53ce78e1e0f8a
|
diff --git a/src/Console.php b/src/Console.php
index <HASH>..<HASH> 100644
--- a/src/Console.php
+++ b/src/Console.php
@@ -83,11 +83,17 @@ class Console
* Logs current time with optional message
*
* @param string $name
+ * @param float $literalTime
*/
- public function logSpeed($name = 'Point in Time')
+ public function logSpeed($name = 'Point in Time', $literalTime = null)
{
+ $time = microtime(true);
+ if (!is_null($literalTime) && is_float($literalTime)) {
+ $time = $literalTime;
+ }
+
array_push($this->store, array(
- 'data' => microtime(true),
+ 'data' => $time,
'name' => $name,
'type' => 'speed'
));
|
Adds option to pass in literal timestamp
|
jacobemerick_pqp
|
train
|
38677eabfcedf655d4405de6a151edcd72528b1c
|
diff --git a/aws/resource_aws_route53_record_test.go b/aws/resource_aws_route53_record_test.go
index <HASH>..<HASH> 100644
--- a/aws/resource_aws_route53_record_test.go
+++ b/aws/resource_aws_route53_record_test.go
@@ -1079,6 +1079,7 @@ func testAccErrorCheckSkipRoute53(t *testing.T) resource.ErrorCheckFunc {
return testAccErrorCheckSkipMessagesContaining(t,
"Operations related to PublicDNS",
"Regional control plane current does not support",
+ "NoSuchHostedZone: The specified hosted zone",
)
}
|
tests/route<I>: Skip no such host error
|
terraform-providers_terraform-provider-aws
|
train
|
0f827b13c9ef3a09083c8cfd173c7094a2a36dad
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,7 @@ CHANGELOG
* BC: The Session component implements HttpServerInterface instead of WsServerInterface
* BC: PHP 5.3 no longer supported
* BC: Update to newer version of react/socket dependency
+ * BC: WAMP topics reduced to 0 subscriptions are deleted, new subs to same name will result in new Topic instance
* Significant performance enhancements
* 0.3.6 (2017-01-06)
diff --git a/src/Ratchet/Wamp/Topic.php b/src/Ratchet/Wamp/Topic.php
index <HASH>..<HASH> 100644
--- a/src/Ratchet/Wamp/Topic.php
+++ b/src/Ratchet/Wamp/Topic.php
@@ -6,13 +6,6 @@ use Ratchet\ConnectionInterface;
* A topic/channel containing connections that have subscribed to it
*/
class Topic implements \IteratorAggregate, \Countable {
- /**
- * If true the TopicManager will destroy this object if it's ever empty of connections
- * @deprecated in v0.4
- * @type bool
- */
- public $autoDelete = false;
-
private $id;
private $subscribers;
diff --git a/src/Ratchet/Wamp/TopicManager.php b/src/Ratchet/Wamp/TopicManager.php
index <HASH>..<HASH> 100644
--- a/src/Ratchet/Wamp/TopicManager.php
+++ b/src/Ratchet/Wamp/TopicManager.php
@@ -118,7 +118,7 @@ class TopicManager implements WsServerInterface, WampServerInterface {
$this->topicLookup[$topic->getId()]->remove($conn);
- if ($topic->autoDelete && 0 === $topic->count()) {
+ if (0 === $topic->count()) {
unset($this->topicLookup[$topic->getId()]);
}
}
diff --git a/tests/unit/Wamp/TopicManagerTest.php b/tests/unit/Wamp/TopicManagerTest.php
index <HASH>..<HASH> 100644
--- a/tests/unit/Wamp/TopicManagerTest.php
+++ b/tests/unit/Wamp/TopicManagerTest.php
@@ -185,21 +185,18 @@ class TopicManagerTest extends \PHPUnit_Framework_TestCase {
}
public static function topicConnExpectationProvider() {
- return array(
- array(true, 'onClose', 0)
- , array(true, 'onUnsubscribe', 0)
- , array(false, 'onClose', 1)
- , array(false, 'onUnsubscribe', 1)
- );
+ return [
+ [ 'onClose', 0]
+ , ['onUnsubscribe', 0]
+ ];
}
/**
* @dataProvider topicConnExpectationProvider
*/
- public function testTopicRetentionFromLeavingConnections($autoDelete, $methodCall, $expectation) {
+ public function testTopicRetentionFromLeavingConnections($methodCall, $expectation) {
$topicName = 'checkTopic';
list($topic, $attribute) = $this->topicProvider($topicName);
- $topic->autoDelete = $autoDelete;
$this->mngr->onSubscribe($this->conn, $topicName);
call_user_func_array(array($this->mngr, $methodCall), array($this->conn, $topicName));
|
Remove Topic autoDelete option from WAMP
When a Topic reaches 0 subscribers it will be removed
New subscriptions to Topics that had the same name will create new Topics
refs #<I>, #<I>
|
ratchetphp_Ratchet
|
train
|
abb21789b2e5c07aa790170f1a34398214399b04
|
diff --git a/xray/core/variable.py b/xray/core/variable.py
index <HASH>..<HASH> 100644
--- a/xray/core/variable.py
+++ b/xray/core/variable.py
@@ -410,7 +410,12 @@ class Variable(common.AbstractArray, utils.NdimSizeLenMixin):
If `deep=True`, the data array is loaded into memory and copied onto
the new object. Dimensions, attributes and encodings are always copied.
"""
- data = self.values.copy() if deep else self._data
+ if deep and not isinstance(self.data, dask_array_type):
+ # dask arrays don't have a copy method
+ # https://github.com/blaze/dask/issues/911
+ data = self.data.copy()
+ else:
+ data = self._data
# note:
# dims is already an immutable tuple
# attributes and encoding will be copied when the new Array is created
diff --git a/xray/test/test_dask.py b/xray/test/test_dask.py
index <HASH>..<HASH> 100644
--- a/xray/test/test_dask.py
+++ b/xray/test/test_dask.py
@@ -67,6 +67,11 @@ class TestVariable(DaskTestCase):
self.assertEqual(self.data.chunks, v.chunks)
self.assertArrayEqual(self.values, v)
+ def test_copy(self):
+ self.assertLazyAndIdentical(self.eager_var, self.lazy_var.copy())
+ self.assertLazyAndIdentical(self.eager_var,
+ self.lazy_var.copy(deep=True))
+
def test_chunk(self):
for chunks, expected in [(None, ((2, 2), (2, 2, 2))),
(3, ((3, 1), (3, 3))),
|
Don't unnecessarily copy dask arrays
|
pydata_xarray
|
train
|
33713d06e51419c276ed25764c334cb39eb38419
|
diff --git a/src/Server.php b/src/Server.php
index <HASH>..<HASH> 100644
--- a/src/Server.php
+++ b/src/Server.php
@@ -29,43 +29,45 @@ class Server extends StandardServer
// JWT?
$jwtKey = $container->getParameter('jwt_key');
- if ($jwtKey[0]=='/') {
- if (!file_exists($jwtKey)) {
- throw new RuntimeException("File not found: $jwtKey");
- }
- $jwtKey = file_get_contents($jwtKey);
- $container->setParameter('jwt_key', $jwtKey);
- }
if ($jwtKey) {
- $jwt = null;
- if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
- $auth = $_SERVER['HTTP_AUTHORIZATION'];
- $authPart = explode(' ', $auth);
- if (count($authPart)!=2) {
- throw new RuntimeException("Invalid authorization header");
- }
- if ($authPart[0]!='Bearer') {
- throw new RuntimeException("Invalid authorization type");
+ if ($jwtKey[0]=='/') {
+ if (!file_exists($jwtKey)) {
+ throw new RuntimeException("File not found: $jwtKey");
}
- $jwt = $authPart[1];
- }
- if (isset($_GET['jwt'])) {
- $jwt = $_GET['jwt'];
+ $jwtKey = file_get_contents($jwtKey);
+ $container->setParameter('jwt_key', $jwtKey);
}
+ if ($jwtKey) {
+ $jwt = null;
+ if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
+ $auth = $_SERVER['HTTP_AUTHORIZATION'];
+ $authPart = explode(' ', $auth);
+ if (count($authPart)!=2) {
+ throw new RuntimeException("Invalid authorization header");
+ }
+ if ($authPart[0]!='Bearer') {
+ throw new RuntimeException("Invalid authorization type");
+ }
+ $jwt = $authPart[1];
+ }
+ if (isset($_GET['jwt'])) {
+ $jwt = $_GET['jwt'];
+ }
- if (!$jwt) {
- throw new RuntimeException("Token required");
- }
- $token = null;
- try {
- $token = (array)JWT::decode($jwt, $jwtKey, array('RS256'));
- } catch (\Exception $e) {
- throw new RuntimeException("Token invalid");
- }
- if (!$token) {
- throw new RuntimeException("Invalid JWT");
+ if (!$jwt) {
+ throw new RuntimeException("Token required");
+ }
+ $token = null;
+ try {
+ $token = (array)JWT::decode($jwt, $jwtKey, array('RS256'));
+ } catch (\Exception $e) {
+ throw new RuntimeException("Token invalid");
+ }
+ if (!$token) {
+ throw new RuntimeException("Invalid JWT");
+ }
+ $rootValue['token'] = $token;
}
- $rootValue['token'] = $token;
}
|
Allow configurations with empty JWT
|
linkorb_graphael
|
train
|
c6afa3393095b27a967045b6e9ea03aac11ec6bf
|
diff --git a/lancet/__init__.py b/lancet/__init__.py
index <HASH>..<HASH> 100644
--- a/lancet/__init__.py
+++ b/lancet/__init__.py
@@ -1639,19 +1639,19 @@ class QLauncher(Launcher):
# Launch Helper #
#===============#
-class using(param.Parameterized):
+class applying(param.Parameterized):
"""
Utility to use Python code (callables) with a specifier, optionally creating
a log of the arguments used. By default data is passed in as keywords but
positional arguments can be specified using the 'args' parameter.
Accumulate the return values of any callable (functions or classes) as
- follows: incremented = using(LinearArgs('value', 1, 10))(add_one)
+ follows: incremented = applying(LinearArgs('value', 1, 10))(add_one)
May also be used as a function decorator that are called for their
side-effects:
- @using(LinearArgs('value', 1, 10))
+ @applying(LinearArgs('value', 1, 10))
def add_one(value=None):
print "%d + 1 = %d" % (value, value+1)
... 1 + 1 = 2
@@ -1676,7 +1676,7 @@ class using(param.Parameterized):
group of results.''')
def __init__(self, specifier, **kwargs):
- super(using, self).__init__(specifier=specifier, **kwargs)
+ super(applying, self).__init__(specifier=specifier, **kwargs)
@property
def kwargs(self):
@@ -1714,14 +1714,14 @@ class using(param.Parameterized):
return accumulator
def __repr__(self):
- return 'using(%r%s)' % (self.specifier, ', args=%r' % self.args if self.args else '')
+ return 'applying(%r%s)' % (self.specifier, ', args=%r' % self.args if self.args else '')
def __str__(self):
arg_str = ',\n args=%r' % self.args if self.args else ''
- return 'using(\n specifier=%s%s\n)' % (self.specifier._pprint(level=2), arg_str)
+ return 'applying(\n specifier=%s%s\n)' % (self.specifier._pprint(level=2), arg_str)
def _repr_pretty_(self, p, cycle):
- p.text(self._pprint(cycle, annotate=True))
+ p.text(str(self))
class review_and_launch(param.Parameterized):
"""
|
Renamed 'using' to 'applying' - clearer than both previous names
The name of this utility should now be settled. In common useage
'applying' and 'using' have similar semantics but 'applying' has the
more correct technical term (see Python's apply built-in).
|
ioam_lancet
|
train
|
83155fce5bb61fb26770d6eb16ad1bae56e29ade
|
diff --git a/config.php b/config.php
index <HASH>..<HASH> 100644
--- a/config.php
+++ b/config.php
@@ -1,8 +1,8 @@
<?php
// database settings
define('DB_NAME', 'jsbin');
-define('DB_USER', 'root'); // Your MySQL username
-define('DB_PASSWORD', ''); // ...and password
+define('DB_USER', 'jsbin_user'); // Your MySQL username
+define('DB_PASSWORD', 'jsbin_password'); // ...and password
define('DB_HOST', 'localhost'); // 99% chance you won't need to change this value
// change this to suite your offline detection
|
Some fixes for IE9 (because of bugs in IE9 around testing the console object)
|
jsbin_jsbin
|
train
|
7ff7e34d90b006a009621635d9552daeb026c096
|
diff --git a/presto-kafka/src/main/java/com/facebook/presto/kafka/KafkaInternalFieldDescription.java b/presto-kafka/src/main/java/com/facebook/presto/kafka/KafkaInternalFieldDescription.java
index <HASH>..<HASH> 100644
--- a/presto-kafka/src/main/java/com/facebook/presto/kafka/KafkaInternalFieldDescription.java
+++ b/presto-kafka/src/main/java/com/facebook/presto/kafka/KafkaInternalFieldDescription.java
@@ -22,10 +22,15 @@ import com.facebook.presto.spi.type.Type;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;
+import java.util.Map;
+
import static com.facebook.presto.spi.type.VarcharType.createUnboundedVarcharType;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.isNullOrEmpty;
+import static com.google.common.collect.ImmutableMap.toImmutableMap;
+import static java.util.Arrays.stream;
import static java.util.Objects.requireNonNull;
+import static java.util.function.Function.identity;
/**
* Describes an internal (managed by the connector) field which is added to each table row. The definition itself makes the row
@@ -90,6 +95,17 @@ public enum KafkaInternalFieldDescription
*/
KEY_LENGTH_FIELD("_key_length", BigintType.BIGINT, "Total number of key bytes");
+ private static final Map<String, KafkaInternalFieldDescription> BY_COLUMN_NAME =
+ stream(KafkaInternalFieldDescription.values())
+ .collect(toImmutableMap(KafkaInternalFieldDescription::getColumnName, identity()));
+
+ public static KafkaInternalFieldDescription forColumnName(String columnName)
+ {
+ KafkaInternalFieldDescription description = BY_COLUMN_NAME.get(columnName);
+ checkArgument(description != null, "Unknown internal column name %s", columnName);
+ return description;
+ }
+
private final String columnName;
private final Type type;
private final String comment;
|
Allow lookup of KafkaInternalFieldDescription by column name
|
prestodb_presto
|
train
|
aa580e07e09d4f126c83335ce04a0a19c1890b51
|
diff --git a/code/Debug/Block/Config.php b/code/Debug/Block/Config.php
index <HASH>..<HASH> 100644
--- a/code/Debug/Block/Config.php
+++ b/code/Debug/Block/Config.php
@@ -46,7 +46,14 @@ class Magneto_Debug_Block_Config extends Magneto_Debug_Block_Abstract
public function getToggleTranslateHintsUrl($forStore=null)
{
+ if (!$forStore) {
+ $forStore = Mage::app()->getStore()->getId();
+ }
+ return Mage::getUrl('debug/index/toggleTranslateInline', array(
+ 'store' => $forStore,
+ '_store' => self::DEFAULT_STORE_ID,
+ '_nosid' => true));
}
}
diff --git a/code/Debug/controllers/IndexController.php b/code/Debug/controllers/IndexController.php
index <HASH>..<HASH> 100644
--- a/code/Debug/controllers/IndexController.php
+++ b/code/Debug/controllers/IndexController.php
@@ -192,12 +192,14 @@ class Magneto_Debug_IndexController extends Mage_Core_Controller_Front_Action
*/
public function toggleTranslateInlineAction()
{
- $currentStatus = Mage::getStoreConfig('dev/translate_inline/active');
+ $forStore = $this->getRequest()->getParam('store', 1);
+
+ $currentStatus = Mage::getStoreConfig('dev/translate_inline/active', $forStore);
$newStatus = !$currentStatus;
$config = Mage::app()->getConfig();
- $config->saveConfig('dev/translate_inline/active', $newStatus);
- $config->saveConfig('dev/translate_inline/active_admin', $newStatus);
+ $config->saveConfig('dev/translate_inline/active', $newStatus, 'stores', $forStore);
+ $config->saveConfig('dev/translate_inline/active_admin', $newStatus, 'stores', $forStore);
// Toggle translate cache too
$allTypes = Mage::app()->useCache();
@@ -205,7 +207,7 @@ class Magneto_Debug_IndexController extends Mage_Core_Controller_Front_Action
Mage::app()->saveUseCache($allTypes);
// clear cache
- Mage::app()->getCacheInstance()->flush();
+ Mage::app()->cleanCache(array(Mage_Core_Model_Config::CACHE_TAG, Mage_Core_Model_Translate::CACHE_TAG));
Mage::getSingleton('core/session')->addSuccess('Translate inline set to ' . var_export($newStatus, true));
$this->_redirectReferer();
diff --git a/design/template/debug/config.phtml b/design/template/debug/config.phtml
index <HASH>..<HASH> 100644
--- a/design/template/debug/config.phtml
+++ b/design/template/debug/config.phtml
@@ -4,7 +4,7 @@
<a class="toggleTemplate" href="<?php echo $this->getToggleHintsUrl() ?>">
<?php echo $this->__("Toggle Template Hints") ?>
</a>
- <a class="toggleTemplate" href="<?php echo Mage::getUrl('debug/index/toggleTranslateInline') ?>">
+ <a class="toggleTemplate" href="<?php echo $this->getToggleTranslateHintsUrl() ?>">
<?php echo $this->__("Toggle Translate Inline") ?>
</a>
</strong></dt>
|
toggle inline translation functionality updated: allow to toggle per store and on admin
|
madalinoprea_magneto-debug
|
train
|
d605bb67c8204d09afb5a35ad2d84c37960f4156
|
diff --git a/src/core.js b/src/core.js
index <HASH>..<HASH> 100755
--- a/src/core.js
+++ b/src/core.js
@@ -137,6 +137,15 @@
* @memberOf me.sys
*/
scale : 1.0,
+
+ /**
+ * Global gravity settings <br>
+ * will override entities init value if defined<br>
+ * default value : undefined
+ * @type {Number}
+ * @memberOf me.sys
+ */
+ gravity : undefined,
/**
* Use native "requestAnimFrame" function if supported <br>
diff --git a/src/entity/entity.js b/src/entity/entity.js
index <HASH>..<HASH> 100644
--- a/src/entity/entity.js
+++ b/src/entity/entity.js
@@ -930,7 +930,7 @@
* @type Number
* @name me.ObjectEntity#gravity
*/
- this.gravity = 0.98;
+ this.gravity = (me.sys.gravity!=undefined)?me.sys.gravity:0.98;
// just to identify our object
this.isEntity = true;
|
Added a global gravity setting that will override entities default value if defined
|
melonjs_melonJS
|
train
|
7d2500c2c81a77987fac1f59931200700e377a86
|
diff --git a/bulbs/special_coverage/models.py b/bulbs/special_coverage/models.py
index <HASH>..<HASH> 100644
--- a/bulbs/special_coverage/models.py
+++ b/bulbs/special_coverage/models.py
@@ -56,20 +56,10 @@ class SpecialCoverage(models.Model):
}
}
}
- try:
- res = es.create(index=index, doc_type=self.get_doc_type(), body=q, id=self.es_id, refresh=True)
- except Exception, e:
- res = e
- else:
- res = None
- return res
+ res = es.create(index=index, doc_type=self.get_doc_type(), body=q, id=self.es_id, refresh=True)
def _delete_percolator(self):
- try:
- res = es.delete(index=index, doc_type=self.get_doc_type(), id=self.es_id, refresh=True)
- except Exception, e:
- res = e
- return res
+ es.delete(index=index, doc_type=self.get_doc_type(), id=self.es_id, refresh=True, ignore=404)
def get_content(self):
"""performs es search and gets content objects
diff --git a/tests/special_coverage/test_spec_cov_es.py b/tests/special_coverage/test_spec_cov_es.py
index <HASH>..<HASH> 100644
--- a/tests/special_coverage/test_spec_cov_es.py
+++ b/tests/special_coverage/test_spec_cov_es.py
@@ -417,39 +417,57 @@ class BaseCustomSearchFilterTests(BaseIndexableTestCase):
)
-class SpecialCoverageQueryTests(BaseCustomSearchFilterTests):
- def setUp(self):
- super(SpecialCoverageQueryTests, self).setUp()
+class SpecialCoverageQueryTests(BaseIndexableTestCase):
def test_get_doc_type(self):
assert SpecialCoverage.get_doc_type() == ".percolator"
def test_es_id(self):
- sc = SpecialCoverage.objects.create(
+ sc = SpecialCoverage(
+ id=101,
name="All Obama, Baby",
description="All Obama, Baby"
)
- es_id = "specialcoverage.{}".format(sc.id)
- assert sc.es_id == es_id
+ assert sc.es_id == "specialcoverage.101"
def test_save_percolator(self):
- query = self.search_expectations[1][0]
- sc = SpecialCoverage.objects.create(
- name="All Obama, Baby",
- description="All Obama, Baby",
- query=query
- )
- res = sc._save_percolator()
- assert isinstance(res, dict)
+ joe_biden_condition = {
+ "values": [{
+ "value": "joe-biden",
+ "label": "Joe Biden"
+ }],
+ "type": "all",
+ "field": "tag.slug"
+ }
- def test_delete_percolator(self):
- query = self.search_expectations[1][0]
- sc = SpecialCoverage.objects.create(
- name="All Obama, Baby",
- description="All Obama, Baby",
+ query = {
+ "label": "Uncle Joe",
+ "query": {
+ "groups": [{
+ "conditions": [joe_biden_condition]
+ }]
+ },
+ }
+
+ sc = SpecialCoverage(
+ id=93,
+ name="Uncle Joe",
+ description="Classic Joeseph Biden",
query=query
)
+
+ # Manually index this percolator
res = sc._save_percolator()
- assert isinstance(res, dict)
- res = sc._delete_percolator()
- assert isinstance(res, dict)
+
+
+ # def test_delete_percolator(self):
+ # query = self.search_expectations[1][0]
+ # sc = SpecialCoverage.objects.create(
+ # name="All Obama, Baby",
+ # description="All Obama, Baby",
+ # query=query
+ # )
+ # res = sc._save_percolator()
+ # assert isinstance(res, dict)
+ # res = sc._delete_percolator()
+ # assert isinstance(res, dict)
|
Starting to refactor this a little bit
|
theonion_django-bulbs
|
train
|
32f7585ec73ace5e420d72af1a38d848869cf434
|
diff --git a/src/main/java/de/biomedical_imaging/traJ/simulation/AnomalousDiffusionWMSimulation.java b/src/main/java/de/biomedical_imaging/traJ/simulation/AnomalousDiffusionWMSimulation.java
index <HASH>..<HASH> 100644
--- a/src/main/java/de/biomedical_imaging/traJ/simulation/AnomalousDiffusionWMSimulation.java
+++ b/src/main/java/de/biomedical_imaging/traJ/simulation/AnomalousDiffusionWMSimulation.java
@@ -36,11 +36,22 @@ public class AnomalousDiffusionWMSimulation extends AbstractSimulator {
t.add(new Point3d(0, 0, 0));
double[] incrx = generateIncrements();
double[] incry = generateIncrements();
+
+ /*
+ * This factor was calculated by regression analysis using R:
+ * x<-c(100,200,300,400,500,600,700,800)
+ * y<-c(1.0610,1.030076,1.02126,1.01446,1.012958,1.01055,1.008500,1.007809)
+ * fit <- lm(log(y)~log(x))
+ * plot(log(x),log(y))
+ * abline(fit)
+ * print(fit)
+ */
+ double fact = Math.sqrt(diffusioncoefficient/(Math.exp(6.7426-0.9704*Math.log(numberOfSteps))));
for(int i = 1; i <= numberOfSteps; i++) {
Point3d pos = new Point3d();
- pos.setX(t.get(i-1).x + incrx[i-1]); //Math.sqrt(2*diffusioncoefficient*timelag);
- pos.setY(t.get(i-1).y + incry[i-1]); //Math.sqrt(2*diffusioncoefficient*timelag));
+ pos.setX(t.get(i-1).x + incrx[i-1]*2*fact);//)*fact2); Math.sqrt(2*diffusioncoefficient*timelag)
+ pos.setY(t.get(i-1).y + incry[i-1]*2*fact);//*fact2);
t.add(pos);
}
|
Step increments are now scaled in such a way, that the
for alpha = 1 the msd curve has a slope of 4 D.
|
thorstenwagner_TraJ
|
train
|
b78f34e391c97afd2a58df746923ded494c2e019
|
diff --git a/spikeextractors/extractors/axonaunitrecordingextractor/axonaunitrecordingextractor.py b/spikeextractors/extractors/axonaunitrecordingextractor/axonaunitrecordingextractor.py
index <HASH>..<HASH> 100644
--- a/spikeextractors/extractors/axonaunitrecordingextractor/axonaunitrecordingextractor.py
+++ b/spikeextractors/extractors/axonaunitrecordingextractor/axonaunitrecordingextractor.py
@@ -93,7 +93,9 @@ class AxonaUnitRecordingExtractor(NeoBaseRecordingExtractor):
t = int(t // (timebase_sr / sampling_rate)) # timestamps are sampled at higher frequency
t = t - start_frame
- if t - samples_pre < 0:
+ if (t - samples_pre < 0) and (t + samples_post > traces.shape[1]):
+ traces[itrc:itrc + nch, :] = wf[:, samples_pre - t:traces.shape[1] - (t - samples_pre)]
+ elif t - samples_pre < 0:
traces[itrc:itrc + nch, :t + samples_post] = wf[:, samples_pre - t:]
elif t + samples_post > traces.shape[1]:
traces[itrc:itrc + nch, t - samples_pre:] = wf[:, :traces.shape[1] - (t - samples_pre)]
|
get_traces: consider case where user requests seg smaller than a single waveform
|
SpikeInterface_spikeextractors
|
train
|
ec62838bb22a8b1bbf85c2bb1daf318df41d5a91
|
diff --git a/cmd/inspect_test.go b/cmd/inspect_test.go
index <HASH>..<HASH> 100644
--- a/cmd/inspect_test.go
+++ b/cmd/inspect_test.go
@@ -51,7 +51,7 @@ func TestDoInspect(t *testing.T) {
res := `{
"manifest": {"revision": "rev", "roots": ["foo", "bar", "fuz", "baz", "a", "x"]},
"signatures_config": {},
- "namespaces": {"": ["/data.json"], "data.foo": ["/example/foo.rego"]}
+ "namespaces": {"data": ["/data.json"], "data.foo": ["/example/foo.rego"]}
}`
exp := util.MustUnmarshalJSON([]byte(res))
@@ -131,7 +131,7 @@ NAMESPACES:
+-----------------------------+----------------------------------------------------+
| NAMESPACE | FILE |
+-----------------------------+----------------------------------------------------+
-| | /data.json |
+| data | /data.json |
| data.a.b.y | /a/b/y/foo.rego |
| | /a/...xxxxxxxxxxxxxx/yyyyyyyyyyyyyyyyyyyy/foo.rego |
| data.foo | /example/foo.rego |
diff --git a/internal/bundle/inspect/inspect.go b/internal/bundle/inspect/inspect.go
index <HASH>..<HASH> 100644
--- a/internal/bundle/inspect/inspect.go
+++ b/internal/bundle/inspect/inspect.go
@@ -126,7 +126,7 @@ func (bi *Info) getBundleDataWasmAndSignatures(name string) error {
path := fmt.Sprintf("%v.%v", ast.DefaultRootDocument, strings.Join(key, "."))
bi.Namespaces[path] = append(bi.Namespaces[path], value)
} else {
- bi.Namespaces[""] = append(bi.Namespaces[""], value) // data file at bundle root
+ bi.Namespaces[ast.DefaultRootDocument.String()] = append(bi.Namespaces[ast.DefaultRootDocument.String()], value) // data file at bundle root
}
}
diff --git a/internal/bundle/inspect/inspect_test.go b/internal/bundle/inspect/inspect_test.go
index <HASH>..<HASH> 100644
--- a/internal/bundle/inspect/inspect_test.go
+++ b/internal/bundle/inspect/inspect_test.go
@@ -48,7 +48,7 @@ func TestGenerateBundleInfoWithFileDir(t *testing.T) {
}
expectedNamespaces := map[string][]string{
- "": {filepath.Join(rootDir, "data.json")},
+ "data": {filepath.Join(rootDir, "data.json")},
"data.bar": {filepath.Join(rootDir, "base.rego")},
"data.foo": {filepath.Join(rootDir, "baz/authz.rego"), filepath.Join(rootDir, "foo/policy.rego")},
"data.fuz": {filepath.Join(rootDir, "fuz/fuz.rego"), filepath.Join(rootDir, "fuz/data.json")},
@@ -114,7 +114,7 @@ func TestGenerateBundleInfoWithFile(t *testing.T) {
}
expectedNamespaces := map[string][]string{
- "": {"/data.json"},
+ "data": {"/data.json"},
"data.b.c": {"/policy.rego"},
}
@@ -181,7 +181,7 @@ func TestGenerateBundleInfoWithBundleTarGz(t *testing.T) {
expectedNamespaces := map[string][]string{
"data.example": {"/example/example.rego"},
- "": {"/data.json"},
+ "data": {"/data.json"},
"data.a.b.c": {"/a/b/c/data.json"},
"data.a.b.d": {"/a/b/d/data.json"},
"data.a.b.y": {"/a/b/y/foo.rego", "/a/b/y/data.yaml"},
|
cmd/inspect: Add namespace for data file at root
Earlier we used an empty namespace for data file located
at bundle root. This change now uses "data" as the
namespace for a data file at root.
Fixes: #<I>
|
open-policy-agent_opa
|
train
|
fcc0af9f5b2751b2a7a281e9f691575df74ac05d
|
diff --git a/docker.go b/docker.go
index <HASH>..<HASH> 100644
--- a/docker.go
+++ b/docker.go
@@ -76,10 +76,9 @@ func (docker *Docker) Destroy(container *Container) error {
if err := container.Mountpoint.Umount(); err != nil {
log.Printf("Unable to umount container %v: %v", container.Id, err)
}
-
- if err := container.Mountpoint.Deregister(); err != nil {
- log.Printf("Unable to deregiser mountpoint %v: %v", container.Mountpoint.Root, err)
- }
+ }
+ if err := container.Mountpoint.Deregister(); err != nil {
+ log.Printf("Unable to deregiser mountpoint %v: %v", container.Mountpoint.Root, err)
}
if err := os.RemoveAll(container.Root); err != nil {
log.Printf("Unable to remove filesystem for %v: %v", container.Id, err)
|
Fix undeleted mountpoint on destroy
Issue #<I>, Now mountpoints are always deleted even when not currently mounted.
|
containers_storage
|
train
|
e7e587fad2b6200f365ab44e89f7a322aa91a821
|
diff --git a/src/Extensions.php b/src/Extensions.php
index <HASH>..<HASH> 100644
--- a/src/Extensions.php
+++ b/src/Extensions.php
@@ -276,16 +276,53 @@ class Extensions
{
$name = $extension->getName();
- // Attempt to get extension YAML config
+ try {
+ $this->loadExtensionConfig($extension, $name);
+ $this->loadExtensionInitialize($extension, $name);
+ $this->loadExtensionTwigGlobal($extension, $name);
+ $this->loadExtensionTwig($extension, $name);
+ $this->loadExtensionSnippets($extension, $name);
+ } catch (\Exception $e) {
+ // Should be already caught, go into slient mode
+ }
+
+ // Flag the extension as initialised
+ $this->initialized[$name] = $extension;
+
+ // If an extension makes it known it sends email, increase the counter
+ if (is_callable(array($extension, 'sendsMail')) && $extension->sendsMail()) {
+ $this->mailsenders++;
+ }
+ }
+
+ /**
+ * Attempt to get extension YAML config.
+ *
+ * @param ExtensionInterface $extension
+ * @param string $name
+ *
+ * @throws \Exception
+ */
+ private function loadExtensionConfig(ExtensionInterface $extension, $name)
+ {
try {
$extension->getConfig();
} catch (\Exception $e) {
$this->logInitFailure('Failed to load YAML config', $name, $e, Logger::ERROR);
-
- return;
+ throw $e;
}
+ }
- // Call extension initialize()
+ /**
+ * Initialise the extension.
+ *
+ * @param ExtensionInterface $extension
+ * @param string $name
+ *
+ * @throws \Exception
+ */
+ private function loadExtensionInitialize(ExtensionInterface $extension, $name)
+ {
try {
$extension->initialize();
@@ -300,36 +337,90 @@ class Extensions
return $twig;
}
- )
- );
+ ));
}
} catch (\Exception $e) {
$this->logInitFailure('Initialisation failed', $name, $e, Logger::ERROR);
- return;
+ throw $e;
}
+ }
- // Flag the extension as initialised
- $this->initialized[$name] = $extension;
+ /**
+ * Get the extension defined snippets.
+ *
+ * @param ExtensionInterface $extension
+ * @param string $name
+ *
+ * @throws \Exception
+ */
+ private function loadExtensionSnippets(ExtensionInterface $extension, $name)
+ {
+ try {
+ $snippets = $extension->getSnippets();
+
+ if (!empty($snippets)) {
+ foreach ($snippets as $snippet) {
+ // Make sure 'snippet[2]' is the correct name.
+ $snippet[2] = $name;
+ if (!isset($snippet[3])) {
+ $snippet[3] = '';
+ }
+ $this->insertSnippet($snippet[0], $snippet[1], $snippet[2], $snippet[3]);
+ }
+ }
- // If an extension makes it known it sends email, increase the counter
- if (is_callable(array($extension, 'sendsMail')) && $extension->sendsMail()) {
- $this->mailsenders++;
+ } catch (\Exception $e) {
+ $this->logInitFailure('Snippet loading failed', $name, $e, Logger::ERROR);
+
+ throw $e;
}
+ }
- // Get the extension defined snippets
+ /**
+ * Add an object of this extension to the global Twig scope.
+ *
+ * @param ExtensionInterface $extension
+ * @param string $name
+ *
+ * @throws \Exception
+ */
+ private function loadExtensionTwigGlobal(ExtensionInterface $extension, $name)
+ {
try {
- $this->getSnippets($name);
+ $namespace = $this->getNamespace($extension);
+ if (!empty($namespace)) {
+ $this->app['twig'] = $this->app->share(
+ $this->app->extend(
+ 'twig',
+ function (\Twig_Environment $twig) use ($namespace, $extension) {
+ $twig->addGlobal($namespace, $extension);
+
+ return $twig;
+ }
+ ));
+ }
} catch (\Exception $e) {
- $this->logInitFailure('Snippet loading failed', $name, $e, Logger::ERROR);
+ $this->logInitFailure('Initialisation failed', $name, $e, Logger::ERROR);
- return;
+ throw $e;
}
+ }
- // Add Twig extensions
+ /**
+ * Add Twig extensions.
+ *
+ * @param ExtensionInterface $extension
+ * @param string $name
+ *
+ * @throws \Exception
+ */
+ private function loadExtensionTwig(ExtensionInterface $extension, $name)
+ {
if (!is_callable(array($extension, 'getTwigExtensions'))) {
return;
}
+
/** @var \Twig_Extension[] $extensions */
$twigExtensions = $extension->getTwigExtensions();
$addTwigExFunc = array($this, 'addTwigExtension');
@@ -342,8 +433,7 @@ class Extensions
return $twig;
}
- )
- );
+ ));
if (!is_callable(array($extension, 'isSafe')) || !$extension->isSafe()) {
continue;
@@ -356,8 +446,7 @@ class Extensions
return $twig;
}
- )
- );
+ ));
}
}
@@ -573,25 +662,6 @@ class Extensions
}
/**
- * Call the 'getSnippets' function of an initialized extension, and make sure the snippets are initialized.
- */
- public function getSnippets($extensionname)
- {
- $snippets = $this->initialized[$extensionname]->getSnippets();
-
- if (!empty($snippets)) {
- foreach ($snippets as $snippet) {
- // Make sure 'snippet[2]' is the correct name.
- $snippet[2] = $extensionname;
- if (!isset($snippet[3])) {
- $snippet[3] = '';
- }
- $this->insertSnippet($snippet[0], $snippet[1], $snippet[2], $snippet[3]);
- }
- }
- }
-
- /**
* Insert a snippet. And by 'insert' we actually mean 'add it to the queue, to be processed later'.
*
* @param $location
|
Refactor Extensions::initializeExtension()
|
bolt_bolt
|
train
|
a973f924748502349e495ec8e9cb11449eff9a92
|
diff --git a/src/main/java/io/resourcepool/ssdp/client/request/SsdpDiscovery.java b/src/main/java/io/resourcepool/ssdp/client/request/SsdpDiscovery.java
index <HASH>..<HASH> 100644
--- a/src/main/java/io/resourcepool/ssdp/client/request/SsdpDiscovery.java
+++ b/src/main/java/io/resourcepool/ssdp/client/request/SsdpDiscovery.java
@@ -27,7 +27,9 @@ public abstract class SsdpDiscovery {
sb.append("MAN: \"ssdp:discover\"\r\n");
sb.append("MX: " + options.getMaxWaitTimeSeconds() + "\r\n");
sb.append("USER-AGENT: " + options.getUserAgent() + "\r\n");
- sb.append((serviceType == null || serviceType.trim().isEmpty()) ? "ST: ssdp:all\r\n" : "ST: " + serviceType + "\r\n\r\n");
+ sb.append((serviceType == null || serviceType.trim().isEmpty()) ? "ST: ssdp:all\r\n" : "ST: " + serviceType + "\r\n");
+ sb.append("\r\n");
+
byte[] content = sb.toString().getBytes(UTF_8);
return new DatagramPacket(content, content.length, SsdpParams.getSsdpMulticastAddress(), SsdpParams.getSsdpMulticastPort());
}
diff --git a/src/main/java/io/resourcepool/ssdp/model/DiscoveryOptions.java b/src/main/java/io/resourcepool/ssdp/model/DiscoveryOptions.java
index <HASH>..<HASH> 100644
--- a/src/main/java/io/resourcepool/ssdp/model/DiscoveryOptions.java
+++ b/src/main/java/io/resourcepool/ssdp/model/DiscoveryOptions.java
@@ -76,7 +76,7 @@ public class DiscoveryOptions {
* @return the current builder
*/
public Builder userAgent(String userAgent) {
- if (userAgent != null && !userAgent.trim().isEmpty()) {
+ if (userAgent == null || userAgent.trim().isEmpty()) {
throw new IllegalArgumentException("User-agent cannot be empty");
}
this.userAgent = userAgent;
|
Added a missing newline character after the headers, and fixed the null or empty check while setting a custom user agent.
|
resourcepool_ssdp-client
|
train
|
ecd9fd151d0ab454f9a7326d46856ce19cb54990
|
diff --git a/test/datetimepicker.spec.js b/test/datetimepicker.spec.js
index <HASH>..<HASH> 100644
--- a/test/datetimepicker.spec.js
+++ b/test/datetimepicker.spec.js
@@ -359,7 +359,7 @@ describe('datepicker directive with initial date of 2013-01-22 1:15 and startVie
selectedElement.trigger('click');
expect(jQuery('.active', element).text()).toBe(moment($rootScope.date).format('H:mm'));
- expect($rootScope.date.getTime()).toEqual(moment("2013-01-22T01:00:00.000Z").toDate().getTime());
+ expect($rootScope.date).toEqual(new Date(1358816400000));
});
});
describe('datepicker directive with no initial date, minView="year"', function () {
@@ -379,7 +379,7 @@ describe('datepicker directive with no initial date, minView="year"', function (
selectedElement.trigger('click');
expect(jQuery('.active', element).text()).toBe('2020');
- expect($rootScope.date).toEqual(moment(1577808000000).toDate());
+ expect($rootScope.date).toEqual(new Date(1577808000000));
});
});
describe('datepicker directive with initial date of "2020-01-01T00:00:00.000Z", startView="month" minView="month"', function () {
@@ -401,7 +401,7 @@ describe('datepicker directive with initial date of "2020-01-01T00:00:00.000Z",
selectedElement.trigger('click');
expect(jQuery('.active', element).text()).toBe('Dec');
- expect($rootScope.date).toEqual(moment(1606752000000).toDate());
+ expect($rootScope.date).toEqual(new Date(1606752000000));
});
});
describe('datepicker directive with initial date of "2020-01-01T00:00:00.000Z", startView="day" minView="day"', function () {
@@ -424,7 +424,7 @@ describe('datepicker directive with initial date of "2020-01-01T00:00:00.000Z",
selectedElement.trigger('click');
expect(jQuery('.active', element).text()).toBe('11');
- expect($rootScope.date).toEqual(moment(1578672000000).toDate());
+ expect($rootScope.date).toEqual(new Date(1578672000000));
});
});
describe('datepicker directive with initial date of "2020-01-01T00:00:00.000Z", startView="hour" minView="hour", minuteStep: 15', function () {
@@ -447,7 +447,7 @@ describe('datepicker directive with initial date of "2020-01-01T00:00:00.000Z",
selectedElement.trigger('click');
expect(jQuery('.active', element).text()).toBe('3:00');
- expect($rootScope.date).toEqual(moment(1577818800000).toDate());
+ expect($rootScope.date).toEqual(new Date(1577818800000));
});
});
// ToDo: Test dropdownSelector
|
Update tests to account for changes in time zone handling.
|
dalelotts_angularjs-bootstrap-datetimepicker
|
train
|
9b565e3a6e0465936eee8e9e606685f05a0291e5
|
diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_reload_repository_location.py b/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_reload_repository_location.py
index <HASH>..<HASH> 100644
--- a/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_reload_repository_location.py
+++ b/python_modules/dagster-graphql/dagster_graphql_tests/client_tests/test_reload_repository_location.py
@@ -1,6 +1,10 @@
import pytest
from dagster_graphql import DagsterGraphQLClientError, ReloadRepositoryLocationStatus
+from ..graphql.graphql_context_test_suite import (
+ GraphQLContextVariant,
+ make_graphql_context_test_suite,
+)
from .conftest import MockClient, python_client_test_suite
@@ -80,3 +84,17 @@ def test_failure_with_query_error(mock_client: MockClient):
with pytest.raises(DagsterGraphQLClientError) as _:
mock_client.python_client.reload_repository_location("foo")
+
+
+class TestReloadRepositoryLocationWithClient(
+ make_graphql_context_test_suite(
+ context_variants=[
+ GraphQLContextVariant.non_launchable_in_memory_instance_managed_grpc_env()
+ ]
+ )
+):
+ def test_reload_location_real(self, graphql_client):
+ assert (
+ graphql_client.reload_repository_location("test").status
+ == ReloadRepositoryLocationStatus.SUCCESS
+ )
diff --git a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py
index <HASH>..<HASH> 100644
--- a/python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py
+++ b/python_modules/dagster-graphql/dagster_graphql_tests/graphql/graphql_context_test_suite.py
@@ -1,6 +1,7 @@
import tempfile
from abc import ABC, abstractmethod
from contextlib import contextmanager
+from unittest.mock import patch
import pytest
from dagster import check, file_relative_path
@@ -26,6 +27,8 @@ from dagster.grpc.server import GrpcServerProcess
from dagster.utils import merge_dicts
from dagster.utils.test import FilesystemTestScheduler
from dagster.utils.test.postgres_instance import TestPostgresInstance
+from dagster_graphql import DagsterGraphQLClient
+from dagster_graphql.test.utils import execute_dagster_graphql
def get_main_recon_repo():
@@ -819,6 +822,20 @@ def make_graphql_context_test_suite(context_variants, recon_repo=None):
with self.graphql_context_for_request(request) as graphql_context:
yield graphql_context
+ @pytest.fixture(name="graphql_client")
+ def yield_graphql_client(self, graphql_context):
+ class MockedGraphQLClient:
+ def execute(self, gql_query, variable_values=None):
+ return execute_dagster_graphql(
+ graphql_context,
+ gql_query,
+ variable_values,
+ ).data
+
+ with patch("dagster_graphql.client.client.Client") as mock_client:
+ mock_client.return_value = MockedGraphQLClient()
+ yield DagsterGraphQLClient("localhost")
+
def recon_repo(self):
return recon_repo
|
Add a way to run the python graphql client against the existing graphql_context fixtures (using the real graphql schema)
Summary: this adds a test that <URL>
|
dagster-io_dagster
|
train
|
64e0553032ee2f7e92f0ee1ff0d0070fde317442
|
diff --git a/src/Keboola/OAuth/OAuth20.php b/src/Keboola/OAuth/OAuth20.php
index <HASH>..<HASH> 100644
--- a/src/Keboola/OAuth/OAuth20.php
+++ b/src/Keboola/OAuth/OAuth20.php
@@ -18,7 +18,9 @@ class OAuth20 extends AbstractOAuth
{
$url = $this->authUrl;
$url = str_replace('%%redirect_uri%%', $callbackUrl, $url);
+ // DEPRECATED by %%app_key%%
$url = str_replace('%%client_id%%', $this->appKey, $url);
+ $url = str_replace('%%app_key%%', $this->appKey, $url);
return ['url' => $url];
}
|
feat: replaced client_id by app_key for oauth_<I>
|
keboola_php-oauth
|
train
|
33f31232c9ea441d0d368c0a9e364b4d9dee41db
|
diff --git a/lib/rich/i18n/actionpack/action_controller/dispatcher.rb b/lib/rich/i18n/actionpack/action_controller/dispatcher.rb
index <HASH>..<HASH> 100644
--- a/lib/rich/i18n/actionpack/action_controller/dispatcher.rb
+++ b/lib/rich/i18n/actionpack/action_controller/dispatcher.rb
@@ -8,7 +8,7 @@ unless defined?(Rich::I18n::CONTROLLER_HOOKED)
}
if Rails::VERSION::MAJOR >= 3
- Rich::Cms::Engine.config.to_prepare do
+ ActionController::Base.config.to_prepare do
procedure.call
end
else
|
Corrected the to_prepare hook within the Rails 3 ActionController Dispatcher
|
archan937_rich_i18n
|
train
|
1d343163373ad5f9fa7fe5e11e44d4f7af9eabae
|
diff --git a/dist.py b/dist.py
index <HASH>..<HASH> 100644
--- a/dist.py
+++ b/dist.py
@@ -294,15 +294,16 @@ class Distribution:
def parse_config_files (self, filenames=None):
from ConfigParser import ConfigParser
+ from distutils.core import DEBUG
if filenames is None:
filenames = self.find_config_files()
- print "Distribution.parse_config_files():"
+ if DEBUG: print "Distribution.parse_config_files():"
parser = ConfigParser()
for filename in filenames:
- print " reading", filename
+ if DEBUG: print " reading", filename
parser.read(filename)
for section in parser.sections():
options = parser.options(section)
@@ -370,7 +371,6 @@ class Distribution:
# latter, we omit the display-only options and show help for
# each command listed on the command line.
if self.help:
- print "showing 'global' help; commands=", self.commands
self._show_help(parser,
display_options=len(self.commands) == 0,
commands=self.commands)
@@ -440,7 +440,6 @@ class Distribution:
parser.set_negative_aliases (negative_opt)
(args, opts) = parser.getopt (args[1:])
if hasattr(opts, 'help') and opts.help:
- print "showing help for command", cmd_class
self._show_help(parser, display_options=0, commands=[cmd_class])
return
@@ -643,10 +642,12 @@ class Distribution:
object for 'command' is in the cache, then we either create and
return it (if 'create' is true) or return None.
"""
+ from distutils.core import DEBUG
cmd_obj = self.command_obj.get(command)
if not cmd_obj and create:
- print "Distribution.get_command_obj(): " \
- "creating '%s' command object" % command
+ if DEBUG:
+ print "Distribution.get_command_obj(): " \
+ "creating '%s' command object" % command
klass = self.get_command_class(command)
cmd_obj = self.command_obj[command] = klass(self)
|
Only print debugging output if DEBUG true (and deleted some of the more
extraneous debug prints).
|
pypa_setuptools
|
train
|
dac50ecfa9a71e56840982c22cb1f3fd1ec215c1
|
diff --git a/src/core/renderers/webgl/managers/MaskManager.js b/src/core/renderers/webgl/managers/MaskManager.js
index <HASH>..<HASH> 100644
--- a/src/core/renderers/webgl/managers/MaskManager.js
+++ b/src/core/renderers/webgl/managers/MaskManager.js
@@ -34,12 +34,17 @@ export default class MaskManager extends WebGLManager
*/
pushMask(target, maskData)
{
+ // TODO the root check means scissor rect will not
+ // be used on render textures more info here:
+ // https://github.com/pixijs/pixi.js/pull/3545
+
if (maskData.texture)
{
this.pushSpriteMask(target, maskData);
}
else if (this.enableScissor
&& !this.scissor
+ && this.renderer._activeRenderTarget.root
&& !this.renderer.stencilManager.stencilMaskStack.length
&& maskData.isFastRect())
{
|
added check for root (#<I>)
* added check for root
* Added note to future us..
|
pixijs_pixi.js
|
train
|
fad92778d059cf2503d485335fed4e7200b8aeab
|
diff --git a/abydos/phonetic.py b/abydos/phonetic.py
index <HASH>..<HASH> 100644
--- a/abydos/phonetic.py
+++ b/abydos/phonetic.py
@@ -3131,7 +3131,7 @@ def phonet(word, ml=1):
letters_a_to_z = 'abcdefghijklmnopqrstuvwxyz'
# Output debug information if set True.
- trace = False
+ trace = True
phonet_hash = Counter()
alpha_pos = Counter()
@@ -3141,10 +3141,10 @@ def phonet(word, ml=1):
def _trace_info(text, n, err_text):
"""Output debug information.
"""
- s = '(NULL)' if _phonet_rules[n] == None else _phonet_rules[n]
+ s = '(NULL)' if _phonet_rules[n] == None else _phonet_rules[n]
s2 = '(NULL)' if (_phonet_rules[n + 1] == None) else _phonet_rules[n + 1]
s3 = '(NULL)' if (_phonet_rules[n + 2] == None) else _phonet_rules[n + 2]
- print("%s %d: \"%s\"%s\"%s\" %s\n", text, ((n / 3) + 1), s, s2, s3, err_text)
+ print('"{} {}: "{}"{}"{}" {}'.format(text, ((n / 3) + 1), s, s2, s3, err_text))
def _initialize_phonet():
# German and international umlauts
@@ -3252,8 +3252,7 @@ def phonet(word, ml=1):
c = src[i]
if trace:
- print('\ncheck position %d: src = "%s",', j, src[i:])
- print(' dest = "%s"\n', dest[:j])
+ print('\ncheck position {}: src = "{}", dest = "{}'.format(j, src[i:], dest[:j]))
n = alpha_pos[c]
|
fixed debugging output for phonet
|
chrislit_abydos
|
train
|
ec859ed9af546214e62e5b6f066e47dbc62d6865
|
diff --git a/lib/acquire.js b/lib/acquire.js
index <HASH>..<HASH> 100644
--- a/lib/acquire.js
+++ b/lib/acquire.js
@@ -142,7 +142,7 @@
// // …
//
// return myPackage;
-// })
+// })();
//
// /* lib/myPackage/subModule.js */
// (function(){
@@ -151,4 +151,50 @@
// // …
//
// return subModule;
-// })
+// })();
+(function () {
+
+ // ============
+ // = Plumbing =
+ // ============
+
+ // === Basic acquires
+ var acquirePackage = function () {};
+
+ var acquireRelative = function () {};
+
+ var acquireAbsolute = function () {};
+
+ // =============
+ // = Porcelain =
+ // =============
+
+ // We have to define our `acquire` object (the namespace for the entire API)
+ // all the way down here, because it has to be the same function called by
+ // `acquire.package()`.
+ var acquire = acquirePackage;
+ acquire['package'] = acquirePackage;
+ acquire['relative'] = acquireRelative;
+ acquire['absolute'] = acquireAbsolute;
+
+ // For the moment, this file has to be dual-compatible with both `acquire()`
+ // *and* the old ‘securable modules’ `require()` system (as that is the only
+ // easy method for people wishing to get `acquire()` into their code to do
+ // so). For that reason, we’re going to ensure `module.exports` exists, and
+ // then attach our `acquire` namespace to that.
+ //
+ // In ‘the future’ (/dun dun dun+/), I’m hoping that this code will be
+ // merged into Node.js and used to replace the ‘securable modules’
+ // system as the primary code-acquisition system, and `acquire` will simply
+ // be available. Until then, to make upgrading (if that happens) easier, I
+ // suggest something like `process.mixin(require('poopy.js/acquire'));`, or,
+ // if you don’t want to screw with the `GLOBAL` namespace,
+ // `var acquire = require('poopy.js/acquire')['acquire'];`. It’s hacky, I
+ // know, but necessary, if I want the `acquire` namespace object itself to
+ // be a function… and for ease of use, I do.
+ if (typeof module == 'undefined') {
+ var module = {} && module['exports'] = {}}
+
+ module.exports['acquire'] = acquire;
+ return module.exports;
+})();
|
Some basic structure for acquire.js
|
ELLIOTTCABLE_from
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.