hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
e707168cf268369327127a43c56663f28c7ccb87 | diff --git a/spyder/utils/introspection/manager.py b/spyder/utils/introspection/manager.py
index <HASH>..<HASH> 100644
--- a/spyder/utils/introspection/manager.py
+++ b/spyder/utils/introspection/manager.py
@@ -33,7 +33,7 @@ dependencies.add('rope',
_("Editor's code completion, go-to-definition and help"),
required_version=ROPE_REQVER)
-JEDI_REQVER = '>=0.8.1'
+JEDI_REQVER = '=0.9.0'
dependencies.add('jedi',
_("Editor's code completion, go-to-definition and help"),
required_version=JEDI_REQVER) | Introspection: Change Jedi required version to <I> | spyder-ide_spyder | train |
06e66b6dc6e2ac1498a76e31a3e7111a38bc0d11 | diff --git a/dynaphopy/__init__.py b/dynaphopy/__init__.py
index <HASH>..<HASH> 100644
--- a/dynaphopy/__init__.py
+++ b/dynaphopy/__init__.py
@@ -66,10 +66,6 @@ class Quasiparticle:
self._power_spectrum_direct = None
self.force_constants_clear()
-# self._renormalized_force_constants = None
-# self._renormalized_bands = None
-# self._commensurate_points_data = None
-
def force_constants_clear(self):
self._renormalized_force_constants = None
self._renormalized_bands = None
@@ -256,19 +252,20 @@ class Quasiparticle:
renormalized_frequencies = data['frequencies']
eigenvectors = data['eigenvectors']
linewidths = data['linewidths']
+ fc_supercell = data['fc_supercell']
plt.suptitle('Renormalized phonon dispersion relations')
sup_lim = pho_interface.get_renormalized_force_constants(renormalized_frequencies + linewidths / 2,
eigenvectors,
self.dynamic.structure,
- self._renormalized_fc_supercell,
+ fc_supercell,
symmetrize=self.parameters.symmetrize)
inf_lim = pho_interface.get_renormalized_force_constants(renormalized_frequencies - linewidths / 2,
eigenvectors,
self.dynamic.structure,
- self._renormalized_fc_supercell,
+ fc_supercell,
symmetrize=self.parameters.symmetrize)
if plot_linewidths:
@@ -845,15 +842,13 @@ class Quasiparticle:
print ('set frequency range: {} - {}'.format(self.get_frequency_range()[0],
self.get_frequency_range()[-1]))
- #if self.parameters.use_MD_cell_commensurate:
- # self.dynamic.structure.set_supercell_phonon_renormalized(np.diag(self.dynamic.get_supercell_matrix()))
-
- self._renormalized_fc_supercell = self.dynamic.structure.get_supercell_phonon()
+ # This has to be improved (looking for a better solution)
+ fc_supercell = self.dynamic.structure.get_supercell_phonon()
if self._parameters.use_MD_cell_commensurate:
- self._renormalized_fc_supercell = np.diag(self.dynamic.get_supercell_matrix())
+ fc_supercell = np.diag(self.dynamic.get_supercell_matrix())
com_points = pho_interface.get_commensurate_points(self.dynamic.structure,
- self._renormalized_fc_supercell)
+ fc_supercell)
initial_reduced_q_point = self.get_reduced_q_vector()
@@ -912,7 +907,8 @@ class Quasiparticle:
self._commensurate_points_data = {'frequencies': renormalized_frequencies,
'eigenvectors': eigenvectors,
'linewidths': linewidths,
- 'q_points': q_points_list}
+ 'q_points': q_points_list,
+ 'fc_supercell': fc_supercell}
self.set_reduced_q_vector(initial_reduced_q_point)
@@ -923,13 +919,14 @@ class Quasiparticle:
data = self.get_commensurate_points_data()
renormalized_frequencies = data['frequencies']
eigenvectors = data['eigenvectors']
+ fc_supercell = data['fc_supercell']
if self._renormalized_force_constants is None:
self._renormalized_force_constants = pho_interface.get_renormalized_force_constants(
renormalized_frequencies,
eigenvectors,
self.dynamic.structure,
- self._renormalized_fc_supercell,
+ fc_supercell,
symmetrize=self.parameters.symmetrize)
return self._renormalized_force_constants | Fix bug in plot renormalized phonon dispersion | abelcarreras_DynaPhoPy | train |
2074886ca89a22ebb687b0dfafa28926022c84cb | diff --git a/examples/sarsa_cartpole.py b/examples/sarsa_cartpole.py
index <HASH>..<HASH> 100644
--- a/examples/sarsa_cartpole.py
+++ b/examples/sarsa_cartpole.py
@@ -44,4 +44,4 @@ sarsa.fit(env, nb_steps=5000, visualize=False, verbose=2)
sarsa.save_weights('sarsa_{}_weights.h5f'.format(ENV_NAME), overwrite=True)
# Finally, evaluate our algorithm for 5 episodes.
-sarsa.test(env, nb_episodes=5, visualize=False)
+sarsa.test(env, nb_episodes=5, visualize=True) | Added visualisation for evaluation rounds (#<I>) | keras-rl_keras-rl | train |
11da0c1ea4d944e28e4ab236d0e812be16dd5fcf | diff --git a/warehouse/forklift/legacy.py b/warehouse/forklift/legacy.py
index <HASH>..<HASH> 100644
--- a/warehouse/forklift/legacy.py
+++ b/warehouse/forklift/legacy.py
@@ -1139,7 +1139,9 @@ def file_upload(request):
releases = (
request.db.query(Release)
.filter(Release.project == project)
- .options(orm.load_only(Release._pypi_ordering))
+ .options(
+ orm.load_only(Release.project_id, Release.version, Release._pypi_ordering)
+ )
.all()
)
for i, r in enumerate( | Fix N<I> Queries on the upload API (#<I>) | pypa_warehouse | train |
feec7564b34f2200cb92d36c27651fdaecf4cf24 | diff --git a/cachestore/cloud/src/main/java/org/infinispan/loaders/cloud/CloudCacheStore.java b/cachestore/cloud/src/main/java/org/infinispan/loaders/cloud/CloudCacheStore.java
index <HASH>..<HASH> 100644
--- a/cachestore/cloud/src/main/java/org/infinispan/loaders/cloud/CloudCacheStore.java
+++ b/cachestore/cloud/src/main/java/org/infinispan/loaders/cloud/CloudCacheStore.java
@@ -292,11 +292,11 @@ public class CloudCacheStore extends BucketBasedCacheStore {
Bucket bucket = readFromBlob(blob, blobName);
if (bucket != null) {
if (bucket.removeExpiredEntries()) {
- lockForWriting(bucket.getBucketId());
+ upgradeLock(bucket.getBucketId());
try {
updateBucket(bucket);
} finally {
- unlock(bucket.getBucketId());
+ downgradeLock(bucket.getBucketId());
}
}
} else { | during purge a RL is already acquired on all the entries. What we need to do is to upgrade that to an WL, otherwise the WL acquisition will block forever. | infinispan_infinispan | train |
b160e63d827a35efb3da909da6003f4665607be5 | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -30,14 +30,27 @@ logger.error('dis is broke m8');
logger.fatal('shit went wrong D:');
```
+Now execute the script:
```sh
+# Prints all messages
DEBUG='*' node logger.js
+
+# Prints only warnings
+DEBUG=*WARN* node logger.js
+
+# Prints only messages in your namespace
+DEBUG=*myNamespace* node logger.js
```
## API
-The logger API consists of 8 methods, namely `fatal`, `error`, `success`, `warn`, `info`, `debug` and `log`. All methods act like the native console API and take as many arguments as you like.
+The logger API consists of 8 methods, namely `fatal`, `error`, `success`, `warn`, `info`, `debug` and `log`.
+
+The `fatal` method is the only one with divergent behavior:
+* It traces the log up to the source file which triggered it which helps to debug the exception if necessary.
+* It will always be rendered and does not use the `DEBUG` environment variable / the `debug` module since it doesn't make sense to not to print fatal errors at any time.
+* It exits the process with code `1` which identifies the Node process as crashed.
-The `fatal` method also exits the process with code `1` which identifies the Node process as crashed.
+All methods act like the native console API and take as many arguments as you like.
## Code style
Please make sure that you adhere to the code style which is based upon [xo](https://github.com/sindresorhus/eslint-config-xo).
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -32,7 +32,8 @@ function createLogger(namespace) {
return {
fatal(...args) {
- log('fatal', ...args);
+ console.log(' ', colorsByType.fatal(`${iconsByType.fatal} FATAL::${namespace}:`), ...args);
+ console.trace(...args);
try {
process.exit(1);
diff --git a/src/index.spec.js b/src/index.spec.js
index <HASH>..<HASH> 100644
--- a/src/index.spec.js
+++ b/src/index.spec.js
@@ -33,19 +33,34 @@ describe('createLogger()', () => {
describe('createLogger().fatal()', () => {
let exit;
+ let log;
+ let trace;
beforeEach(() => {
exit = sinon.stub(process, 'exit');
+ trace = sinon.stub(console, 'trace');
+ log = sinon.stub(console, 'log');
});
afterEach(() => {
exit.restore();
+ trace.restore();
+ log.restore();
});
it('should be a function.', () => {
expect(typeof createLogger).toBe('function');
});
+ it('should call the console.log and console.trace method with the provided arguments.', () => {
+ createLogger('foo').fatal('foo');
+
+ expect(trace.callCount).toBe(1);
+ expect(trace.args[0]).toContain('foo');
+ expect(log.callCount).toBe(1);
+ expect(log.args[0]).toContain('foo');
+ });
+
it('should call the process.exit method with exit code `1`.', () => {
createLogger('foo').fatal('foo'); | FEATURE: Trace the fatal method and do not swallow fatal exceptions based on the DEBUG env variable | Inkdpixels_log-fancy | train |
f6130d4ebbea0cbb761196fe59304ff658e99e2c | diff --git a/auth.go b/auth.go
index <HASH>..<HASH> 100644
--- a/auth.go
+++ b/auth.go
@@ -12,7 +12,9 @@ import (
//
// This encapsulates the different authentication schemes in use
type Authenticator interface {
+ // Request creates an http.Request for the auth - return nil if not needed
Request(*Connection) (*http.Request, error)
+ // Response parses the http.Response
Response(resp *http.Response) error
// The public storage URL - set Internal to true to read
// internal/service net URL
diff --git a/swift.go b/swift.go
index <HASH>..<HASH> 100644
--- a/swift.go
+++ b/swift.go
@@ -300,31 +300,33 @@ again:
if err != nil {
return
}
- timer := time.NewTimer(c.ConnectTimeout)
- var resp *http.Response
- resp, err = c.doTimeoutRequest(timer, req)
- if err != nil {
- return
- }
- defer func() {
- checkClose(resp.Body, &err)
- // Flush the auth connection - we don't want to keep
- // it open if keepalives were enabled
- flushKeepaliveConnections(c.Transport)
- }()
- if err = c.parseHeaders(resp, authErrorMap); err != nil {
- // Try again for a limited number of times on
- // AuthorizationFailed or BadRequest. This allows us
- // to try some alternate forms of the request
- if (err == AuthorizationFailed || err == BadRequest) && retries > 0 {
- retries--
- goto again
+ if req != nil {
+ timer := time.NewTimer(c.ConnectTimeout)
+ var resp *http.Response
+ resp, err = c.doTimeoutRequest(timer, req)
+ if err != nil {
+ return
+ }
+ defer func() {
+ checkClose(resp.Body, &err)
+ // Flush the auth connection - we don't want to keep
+ // it open if keepalives were enabled
+ flushKeepaliveConnections(c.Transport)
+ }()
+ if err = c.parseHeaders(resp, authErrorMap); err != nil {
+ // Try again for a limited number of times on
+ // AuthorizationFailed or BadRequest. This allows us
+ // to try some alternate forms of the request
+ if (err == AuthorizationFailed || err == BadRequest) && retries > 0 {
+ retries--
+ goto again
+ }
+ return
+ }
+ err = c.Auth.Response(resp)
+ if err != nil {
+ return
}
- return
- }
- err = c.Auth.Response(resp)
- if err != nil {
- return
}
c.StorageUrl = c.Auth.StorageUrl(c.Internal)
c.AuthToken = c.Auth.Token() | Make Request/Response optional in custom Auth by returning nil
If you don't actually want your custom Auth to make an HTTP request
(let's say you are getting the token from a database) then just return
nil from the Request method. This will skip the HTTP transaction and
parsing it with the Response method. | ncw_swift | train |
6aeadb934084c8a6e2abe8d348b636e7530994f1 | diff --git a/src/Translation/Translator.php b/src/Translation/Translator.php
index <HASH>..<HASH> 100644
--- a/src/Translation/Translator.php
+++ b/src/Translation/Translator.php
@@ -40,7 +40,7 @@ class Translator
private static function translate(Application $app, $fn, $args, $key, $replace, $domain = 'contenttypes')
{
if ($fn == 'transChoice') {
- $trans = $app['translator']->transChoice(
+ $trans = self::transChoice(
$key,
$args[1],
self::htmlencodeParams($replace),
@@ -48,7 +48,7 @@ class Translator
isset($args[4]) ? $args[4] : $app['request']->getLocale()
);
} else {
- $trans = $app['translator']->trans(
+ $trans = self::trans(
$key,
self::htmlencodeParams($replace),
isset($args[2]) ? $args[2] : $domain,
@@ -161,7 +161,7 @@ class Translator
$key_name = 'contenttypes.' . $ctype . '.name.' . (($key_arg == '%contenttype%') ? 'singular' : 'plural');
$key_ctname = ($key_arg == '%contenttype%') ? 'singular_name' : 'name';
- $ctname = $app['translator']->trans($key_name, array(), 'contenttypes', $app['request']->getLocale());
+ $ctname = self::trans($key_name, array(), 'contenttypes', $app['request']->getLocale());
if ($ctname === $key_name) {
$ctypes = $app['config']->get('contenttypes');
$ctname = empty($ctypes[$ctype][$key_ctname]) ? ucfirst($ctype) : $ctypes[$ctype][$key_ctname]; | Convert further direct usages of trans() | bolt_bolt | train |
9a54bb37ea9507cecc4657d7cbcc887c6ed10f37 | diff --git a/core/core.go b/core/core.go
index <HASH>..<HASH> 100644
--- a/core/core.go
+++ b/core/core.go
@@ -91,6 +91,12 @@ func (a *api) reset(ctx context.Context) error {
}
func (a *api) info(ctx context.Context) (map[string]interface{}, error) {
+ if a.config == nil {
+ // never configured
+ return map[string]interface{}{
+ "is_configured": false,
+ }, nil
+ }
if leader.IsLeading() {
return a.leaderInfo(ctx)
} else {
@@ -99,13 +105,6 @@ func (a *api) info(ctx context.Context) (map[string]interface{}, error) {
}
func (a *api) leaderInfo(ctx context.Context) (map[string]interface{}, error) {
- if a.config == nil {
- // never configured
- return map[string]interface{}{
- "is_configured": false,
- }, nil
- }
-
localHeight := a.c.Height()
var (
generatorHeight interface{} | core: don't call leader for unconfigured core
Closes chain/chainprv#<I>.
Reviewers: @kr | chain_chain | train |
5b242a1d45047abab1614a1d3e44dc4be71bb95f | diff --git a/lib/slimmer/processors/search_remover.rb b/lib/slimmer/processors/search_remover.rb
index <HASH>..<HASH> 100644
--- a/lib/slimmer/processors/search_remover.rb
+++ b/lib/slimmer/processors/search_remover.rb
@@ -9,7 +9,7 @@ module Slimmer::Processors
search = dest.at_css("#global-header #search")
search.remove if search
- search_link = dest.at_css("#global-header a[href='#search']")
+ search_link = dest.at_css("#global-header .search-toggle")
search_link.remove if search_link
end
end
diff --git a/test/processors/search_remover_test.rb b/test/processors/search_remover_test.rb
index <HASH>..<HASH> 100644
--- a/test/processors/search_remover_test.rb
+++ b/test/processors/search_remover_test.rb
@@ -9,7 +9,7 @@ class SearchRemoverTest < MiniTest::Test
</head>
<body>
<div id='global-header'>
- <a href='#search'></a>
+ <button class='search-toggle'></button>
<div id='search'></div>
</div>
<div id='search'></div>
@@ -43,7 +43,7 @@ class SearchRemoverTest < MiniTest::Test
headers,
).filter(nil, @template)
- assert_not_in @template, "#global-header a[href='#search']"
+ assert_not_in @template, "#global-header .search-toggle"
end
def test_should_not_remove_search_link_from_template_if_header_is_not_set
@@ -52,6 +52,6 @@ class SearchRemoverTest < MiniTest::Test
headers,
).filter(nil, @template)
- assert_in @template, "#global-header a[href='#search']"
+ assert_in @template, "#global-header .search-toggle"
end
end | Amend toggle button selector
The code in search_remover.rb assumes that the search toggle button is a
link.
This is an issue as work is being done to change the markup of this
button for accessibility purposes.
Change the search toggle button selector to a class selector instead to
ensure that functionality is preserved when we change the anchor tag to
a button tag. | alphagov_slimmer | train |
5ffa38da11ea7c778fb9b4dc74083802aa20257f | diff --git a/lib/codemirror.js b/lib/codemirror.js
index <HASH>..<HASH> 100644
--- a/lib/codemirror.js
+++ b/lib/codemirror.js
@@ -1589,7 +1589,7 @@ var CodeMirror = (function() {
if (selectionChanged && options.matchBrackets)
setTimeout(operation(function() {
if (bracketHighlighted) {bracketHighlighted(); bracketHighlighted = null;}
- matchBrackets(false);
+ if (posEq(sel.from, sel.to)) matchBrackets(false);
}), 20);
var tc = textChanged; // textChanged can be reset by cursoractivity callback
if (selectionChanged && options.onCursorActivity) | Only match brackets when nothing is selected | codemirror_CodeMirror | train |
439223cde9467af3d51c7a20d06738916d58af06 | diff --git a/core/src/test/java/io/undertow/util/FileSystemWatcherTestCase.java b/core/src/test/java/io/undertow/util/FileSystemWatcherTestCase.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/io/undertow/util/FileSystemWatcherTestCase.java
+++ b/core/src/test/java/io/undertow/util/FileSystemWatcherTestCase.java
@@ -14,7 +14,8 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
-import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.BlockingDeque;
+import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
/**
@@ -29,8 +30,7 @@ public class FileSystemWatcherTestCase {
public static final String EXISTING_FILE_NAME = "a.txt";
public static final String EXISTING_DIR = "existingDir";
- private volatile CountDownLatch latch = new CountDownLatch(1);
- private Collection<FileChangeEvent> results = null;
+ private final BlockingDeque<Collection<FileChangeEvent>> results = new LinkedBlockingDeque<Collection<FileChangeEvent>>();
File rootDir;
File existingSubDir;
@@ -90,11 +90,9 @@ public class FileSystemWatcherTestCase {
watcher.addPath(rootDir, new FileChangeCallback() {
@Override
public void handleChanges(Collection<FileChangeEvent> changes) {
- results = changes;
- latch.countDown();
+ results.add(changes);
}
});
- reset();
//first add a file
File added = new File(rootDir, "newlyAddedFile.txt").getAbsoluteFile();
touchFile(added);
@@ -125,7 +123,6 @@ public class FileSystemWatcherTestCase {
checkResult(added, FileChangeEvent.Type.REMOVED);
-
} finally {
watcher.stop();
}
@@ -133,18 +130,18 @@ public class FileSystemWatcherTestCase {
}
private void checkResult(File file, FileChangeEvent.Type type) throws InterruptedException {
- latch.await(10, TimeUnit.SECONDS);
+ Collection<FileChangeEvent> results = this.results.poll(10, TimeUnit.SECONDS);
Assert.assertNotNull(results);
Assert.assertEquals(1, results.size());
FileChangeEvent res = results.iterator().next();
+ if (type == FileChangeEvent.Type.REMOVED && res.getType() == FileChangeEvent.Type.MODIFIED) {
+ //sometime OS's will give a MODIFIED event before the REMOVED one
+ results = this.results.poll(10, TimeUnit.SECONDS);
+ Assert.assertNotNull(results);
+ Assert.assertEquals(1, results.size());
+ res = results.iterator().next();
+ }
Assert.assertEquals(file, res.getFile());
Assert.assertEquals(type, res.getType());
- reset();
}
-
- void reset() {
- latch = new CountDownLatch(1);
- results = null;
- }
-
} | Possible fix for issue running tests on Windows | undertow-io_undertow | train |
e77843aa1f500bf98827dab3ec8819caecc289da | diff --git a/ncclient/transport/ssh.py b/ncclient/transport/ssh.py
index <HASH>..<HASH> 100644
--- a/ncclient/transport/ssh.py
+++ b/ncclient/transport/ssh.py
@@ -521,7 +521,7 @@ class SSHSession(Session):
saved_exception = None
for key_filename in key_filenames:
- for cls in (paramiko.RSAKey, paramiko.DSSKey, paramiko.ECDSAKey):
+ for cls in (paramiko.RSAKey, paramiko.DSSKey, paramiko.ECDSAKey, paramiko.Ed25519Key):
try:
key = cls.from_private_key_file(key_filename, password)
self.logger.debug("Trying key %s from %s", | add Ed<I>Key to class tuple used for private key auth | ncclient_ncclient | train |
74681514a003a4831193f6c56fb23daf9895a087 | diff --git a/lib/drivers/saucelabs.js b/lib/drivers/saucelabs.js
index <HASH>..<HASH> 100644
--- a/lib/drivers/saucelabs.js
+++ b/lib/drivers/saucelabs.js
@@ -175,7 +175,7 @@ SauceLabsClient.prototype = util.merge(new TunnelClient, {
//.setContext('tunnel-identifier:' + (!existingTunnel && TUNNEL_ID || ''))
.open(parsed.pathname + parsed.search + EPOCH)
.waitForPageToLoad(10000)
- .getEval('window.jetrunner', function(stream) { jetstream = new JetStream(stream); })
+ .getEval('window.jetstream', function(stream) { jetstream = new JetStream(stream); })
.end(function(err) {
var results = jetstream.output,
failed = results === NOT_IMPLEMENTED ? NOT_IMPLEMENTED : !!results.failed;
@@ -188,11 +188,11 @@ SauceLabsClient.prototype = util.merge(new TunnelClient, {
Logger.log('JetRunner client (' + name + ') - finished remote job "' + job +'": ' + (failed && IndicatorsEnum.FAILURE || IndicatorsEnum.SUCCESS));
if(failed == NOT_IMPLEMENTED) {
- Logger.log('Results: '.grey + 'JetStream.NOT_IMPLEMENTED'.red);
+ Logger.log('Results: '.grey + 'JetStream.NOT_IMPLEMENTED'.grey);
Logger.log('\nNote: IE 8/Windows XP is not currently supported! And if that\'s not your problem,'.yellow);
- Logger.log(('then try using another port other than ' + port + ' (see https://saucelabs.com/docs/connect for available ports.)\n').yellow);
+ Logger.log(('then try using another port other than ' + port + ' (see https://saucelabs.com/docs/connect for available ports...)\n').yellow);
} else {
- Logger.log('Results: '.grey + JSON.stringify(results).green);
+ Logger.log('Results: '.grey + JSON.stringify(results).grey);
}
Logger.log('SauceLabs job URL: '.grey + browser.jobUrl.cyan);
diff --git a/lib/server.js b/lib/server.js
index <HASH>..<HASH> 100644
--- a/lib/server.js
+++ b/lib/server.js
@@ -40,7 +40,8 @@ function Server(config, done) {
src: req.param('src') || '',
test: req.param('test') || '',
ui: runner.method,
- reporter: client.reporter
+ reporter: client.reporter,
+ DEBUG: config.debug && 'true' || 'false'
});
});
diff --git a/templates/default-bdd.jade b/templates/default-bdd.jade
index <HASH>..<HASH> 100644
--- a/templates/default-bdd.jade
+++ b/templates/default-bdd.jade
@@ -10,6 +10,13 @@ html(lang="en")
pre(style="white-space:normal;border:solid 1px #ccc;background:#ebebeb;padding:20px;")
script
document.write(decodeURIComponent(location));
+ div#jetrunner-stream-debug
+ script
+ if(#{DEBUG}) {
+ window.onerror = function(err, url, line) {
+ document.getElementById('jetrunner-stream-debug').innerHTML += '<p>' + [err, '[' + decodeURIComponent(url) + ':' + line + ']'].join(' ') + '</p>';
+ }
+ }
div#mocha
each script in scripts
script(src="#{script}")
@@ -28,6 +35,6 @@ html(lang="en")
// Run Mocha:
reporter = (this.mochaPhantomJS || mocha).run(function() {
// JetRunner remote reporting integration (via SauceLabs, BrowserStack, etc.):
- jetrunner = [reporter.stats.failures, reporter.stats.passes, reporter.stats.tests, reporter.stats.duration];
+ jetstream = [reporter.stats.failures, reporter.stats.passes, reporter.stats.tests, reporter.stats.duration];
}); | Adding debug mode for test runner | peteromano_jetrunner | train |
c04735b7b0a1a5bc1212e4cdcdf3697dcdc2a25e | diff --git a/lib/neo4apis/base.rb b/lib/neo4apis/base.rb
index <HASH>..<HASH> 100644
--- a/lib/neo4apis/base.rb
+++ b/lib/neo4apis/base.rb
@@ -120,15 +120,22 @@ module Neo4Apis
def create_node_query(node_proxy)
return if node_proxy.props.empty?
+ props = node_proxy.props
+ extra_labels = props.delete(:_extra_labels)
+
cypher = <<-QUERY
MERGE (node:`#{node_proxy.label}` {#{node_proxy.uuid_field}: {uuid_value}})
- SET #{set_attributes(:node, node_proxy.props.keys)}
+ SET #{set_attributes(:node, props.keys)}
QUERY
cypher << " SET node:`#{self.class.common_label}`" if self.class.common_label
+ (extra_labels || []).each do |label|
+ cypher << " SET node:`#{label}`"
+ end
+
OpenStruct.new({to_cypher: cypher,
- merge_params: {uuid_value: node_proxy.uuid_value, props: node_proxy.props}})
+ merge_params: {uuid_value: node_proxy.uuid_value, props: props}})
end
def create_relationship_query(type, source, target, props) | Support _extra_labels property for when we want to import more than just one label | neo4jrb_neo4apis | train |
55727a19fdeb8ef7a59068f4edc59f9841a2a4c0 | diff --git a/clam/clamservice.py b/clam/clamservice.py
index <HASH>..<HASH> 100755
--- a/clam/clamservice.py
+++ b/clam/clamservice.py
@@ -916,7 +916,9 @@ class Project:
errors = "yes"
errormsg = "An error occurred within the system. Please inspect the error log for details"
printlog("Child process failed, exited with non zero-exit code.")
- customhtml = settings.CUSTOMHTML_PROJECTDONE
+ customhtml = settings.CUSTOMHTML_PROJECTFAILED
+ else:
+ customhtml = settings.CUSTOMHTML_PROJECTDONE
else:
outputpaths = [] #pylint: disable=redefined-variable-type
@@ -2668,11 +2670,17 @@ def set_defaults():
else:
settings.CUSTOMHTML_PROJECTSTART = ""
if not 'CUSTOMHTML_PROJECTDONE' in settingkeys:
- if os.path.exists(settings.CLAMDIR + '/static/custom/' + settings.SYSTEM_ID + '_projectstart.html'):
- with io.open(settings.CLAMDIR + '/static/custom/' + settings.SYSTEM_ID + '_projectstart.html','r',encoding='utf-8') as f:
+ if os.path.exists(settings.CLAMDIR + '/static/custom/' + settings.SYSTEM_ID + '_projectdone.html'):
+ with io.open(settings.CLAMDIR + '/static/custom/' + settings.SYSTEM_ID + '_projectdone.html','r',encoding='utf-8') as f:
settings.CUSTOMHTML_PROJECTDONE = f.read()
else:
settings.CUSTOMHTML_PROJECTDONE = ""
+ if not 'CUSTOMHTML_PROJECTFAILED' in settingkeys:
+ if os.path.exists(settings.CLAMDIR + '/static/custom/' + settings.SYSTEM_ID + '_projectfailed.html'):
+ with io.open(settings.CLAMDIR + '/static/custom/' + settings.SYSTEM_ID + '_projectfailed.html','r',encoding='utf-8') as f:
+ settings.CUSTOMHTML_PROJECTFAILED = f.read()
+ else:
+ settings.CUSTOMHTML_PROJECTFAILED = ""
if not 'CUSTOM_FORMATS' in settingkeys:
settings.CUSTOM_FORMATS = [] | Implemented CUSTOMHTML_PROJECTFAILED (+ fix for CUSTOMHTML_PROJECTDONE) #<I> | proycon_clam | train |
8db0bbe71bf9def44f06c24738bd93c596cedd60 | diff --git a/src/AbstractQuantity.php b/src/AbstractQuantity.php
index <HASH>..<HASH> 100644
--- a/src/AbstractQuantity.php
+++ b/src/AbstractQuantity.php
@@ -131,7 +131,7 @@ abstract class AbstractQuantity
// Multiply the amount by the conversion factor and create a new
// Weight with the new Unit
- return new Weight(
+ return new static(
$this->getAmount()->multiply($conversionFactor),
$uom
); | Bug fix for using new Weight instead of new static | phospr_quantity | train |
802ab1baa92f90c79fbf1d22b38ae85702471787 | diff --git a/lib/types.js b/lib/types.js
index <HASH>..<HASH> 100644
--- a/lib/types.js
+++ b/lib/types.js
@@ -221,8 +221,8 @@ var typeEncoder = (function(){
function decodeTimestamp (bytes) {
var value = decodeBigNumber(bytes);
- if (isFinite(value)) {
- return new Date(value.valueOf());
+ if (value.greaterThan(Long.fromNumber(Number.MIN_VALUE)) && value.lessThan(Long.fromNumber(Number.MAX_VALUE))) {
+ return new Date(value.toNumber());
}
return value;
}
@@ -691,20 +691,16 @@ FrameHeader.prototype.toBuffer = function () {
/**
* Long constructor, wrapper of the internal library used.
*/
-var Long = require('node-int64');
+var Long = require('long');
/**
* Returns a long representation.
* Used internally for deserialization
*/
-Long.fromBuffer = function (buf) {
- return new Long(buf);
-};
-
-/**
- * Returns a Long representing the given value
- */
-Long.fromNumber = function (value) {
- return new Long(value);
+Long.fromBuffer = function (value) {
+ if (!(value instanceof Buffer)) {
+ throw new TypeError('Expected Buffer', value, Buffer);
+ }
+ return new Long(value.readInt32BE(4), value.readInt32BE(0, 4));
};
/**
@@ -715,7 +711,10 @@ Long.toBuffer = function (value) {
if (!(value instanceof Long)) {
throw new TypeError('Expected Long', value, Long);
}
- return value.buffer;
+ var buffer = new Buffer(8);
+ buffer.writeUInt32BE(value.getHighBitsUnsigned(), 0);
+ buffer.writeUInt32BE(value.getLowBitsUnsigned(), 4);
+ return buffer;
};
/**
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "node-cassandra-cql",
- "version": "0.4.0",
+ "version": "0.4.1",
"description": "Node.js driver for Apache Cassandra",
"author": "Jorge Bay <[email protected]>",
"contributors" :[
@@ -10,7 +10,8 @@
"Adrian Pike",
"Suguru Namura",
"Jan Schmidle",
- "Sam Grönblom"
+ "Sam Grönblom",
+ "Daniel Smedegaard Buus"
],
"keywords": [
"cassandra",
@@ -27,7 +28,7 @@
],
"dependencies": {
"async": ">= 0.2.5",
- "node-int64": ">= 0.3.0",
+ "long": ">= 1.2.0",
"node-uuid": "1.4.0"
},
"devDependencies": {
diff --git a/test/basicTests.js b/test/basicTests.js
index <HASH>..<HASH> 100644
--- a/test/basicTests.js
+++ b/test/basicTests.js
@@ -77,7 +77,7 @@ describe('types', function () {
describe('#encode() and #decode', function () {
var typeEncoder = types.typeEncoder;
it('should encode and decode maps', function () {
- var value = {value1: 'Surprise', value2: 'Mothafucka'};
+ var value = {value1: 'Surprise', value2: 'Madafaka'};
var encoded = typeEncoder.encode({hint: dataTypes.map, value: value});
var decoded = typeEncoder.decode(encoded, [dataTypes.map, [[dataTypes.text], [dataTypes.text]]]);
assert.strictEqual(util.inspect(decoded), util.inspect(value));
@@ -99,6 +99,32 @@ describe('types', function () {
})
});
+ describe('Long', function () {
+ var Long = types.Long;
+ it('should convert from and to Buffer', function () {
+ [
+ //int64 decimal value //hex value
+ ['-123456789012345678', 'fe4964b459cf0cb2'],
+ ['-800000000000000000', 'f4e5d43d13b00000'],
+ ['-888888888888888888', 'f3aa0843dcfc71c8'],
+ ['-555555555555555555', 'f84a452a6a1dc71d'],
+ ['-789456', 'fffffffffff3f430'],
+ ['-911111111111111144', 'f35b15458f4f8e18'],
+ ['-9007199254740993', 'ffdfffffffffffff'],
+ ['-1125899906842624', 'fffc000000000000'],
+ ['555555555555555555', '07b5bad595e238e3'],
+ ['789456' , '00000000000c0bd0'],
+ ['888888888888888888', '0c55f7bc23038e38']
+ ].forEach(function (item) {
+ var buffer = new Buffer(item[1], 'hex');
+ var value = Long.fromBuffer(buffer);
+ assert.strictEqual(value.toString(), item[0]);
+ assert.strictEqual(Long.toBuffer(value).toString('hex'), buffer.toString('hex'),
+ 'Hexadecimal values should match for ' + item[1]);
+ });
+ });
+ });
+
describe('ResultStream', function () {
it('should be readable as soon as it has data', function (done) {
var buf = [];
@@ -182,7 +208,7 @@ describe('types', function () {
});
});
- describe ('Row', function () {
+ describe('Row', function () {
it('should get the value by column name or index', function () {
var columnList = [{name: 'first'}, {name: 'second'}];
var row = new types.Row(columnList); | Replaced usage of node-int<I> to Closure Library Long.js | jorgebay_node-cassandra-cql | train |
b1e79fc4b37befb3f0495005b79e59b165c014be | diff --git a/lib/paper_trail/version.rb b/lib/paper_trail/version.rb
index <HASH>..<HASH> 100644
--- a/lib/paper_trail/version.rb
+++ b/lib/paper_trail/version.rb
@@ -4,7 +4,7 @@ class Version < ActiveRecord::Base
attr_accessible :item_type, :item_id, :event, :whodunnit, :object, :object_changes
def self.with_item_keys(item_type, item_id)
- scoped(:conditions => { :item_type => item_type, :item_id => item_id })
+ where :item_type => item_type, :item_id => item_id
end
def self.creates
@@ -20,21 +20,21 @@ class Version < ActiveRecord::Base
end
scope :subsequent, lambda { |version|
- where(["#{self.primary_key} > ?", version]).order("#{self.primary_key} ASC")
+ where("#{self.primary_key} > ?", version).order("#{self.primary_key} ASC")
}
scope :preceding, lambda { |version|
- where(["#{self.primary_key} < ?", version]).order("#{self.primary_key} DESC")
+ where("#{self.primary_key} < ?", version).order("#{self.primary_key} DESC")
}
scope :following, lambda { |timestamp|
# TODO: is this :order necessary, considering its presence on the has_many :versions association?
- where(["#{PaperTrail.timestamp_field} > ?", timestamp]).
+ where("#{PaperTrail.timestamp_field} > ?", timestamp).
order("#{PaperTrail.timestamp_field} ASC, #{self.primary_key} ASC")
}
scope :between, lambda { |start_time, end_time|
- where(["#{PaperTrail.timestamp_field} > ? AND #{PaperTrail.timestamp_field} < ?", start_time, end_time ]).
+ where("#{PaperTrail.timestamp_field} > ? AND #{PaperTrail.timestamp_field} < ?", start_time, end_time).
order("#{PaperTrail.timestamp_field} ASC, #{self.primary_key} ASC")
} | Updating syntax on Version class's :item_with_keys class method to use arel syntax instead of the outdated 'scoped' syntax. | paper-trail-gem_paper_trail | train |
6d812d7ac3cccbecf9f9cece07f52dcdc96f5d1d | diff --git a/lib/disk/modules/VhdxDisk.rb b/lib/disk/modules/VhdxDisk.rb
index <HASH>..<HASH> 100644
--- a/lib/disk/modules/VhdxDisk.rb
+++ b/lib/disk/modules/VhdxDisk.rb
@@ -519,6 +519,7 @@ module VhdxDisk
def parent_disk(path)
@parent_ostruct = OpenStruct.new
@parent_ostruct.fileName = path
+ @parent_ostruct.scvmm = @scvmm
@parent_ostruct.driveType = @scvmm.get_drivetype(path)
@parent_ostruct.hyperv_connection = @hyperv_connection if @hyperv_connection
parent = MiqDisk.getDisk(@parent_ostruct) | Pre-existing Checkpoint Issue
Handling SSA on a VM with pre-existing checkpoints
on Hyper-V hosts is causing an issue because there is
an attempt to use an uninitialized "@scvmm" variable
when attempting to open the second disk in the chain.
Not sure why this never happened before but it works now. | ManageIQ_manageiq-smartstate | train |
0716650744b4b5f21995b8e01d299f51bf183b04 | diff --git a/logging/init_test.go b/logging/init_test.go
index <HASH>..<HASH> 100644
--- a/logging/init_test.go
+++ b/logging/init_test.go
@@ -16,12 +16,15 @@ var (
LONG_CURL_TIMEOUT = 2 * time.Minute
)
-var context helpers.SuiteContext
+var (
+ context helpers.SuiteContext
+ config helpers.Config
+)
func TestLogging(t *testing.T) {
RegisterFailHandler(Fail)
- config := helpers.LoadConfig()
+ config = helpers.LoadConfig()
if config.DefaultTimeout > 0 {
DEFAULT_TIMEOUT = config.DefaultTimeout * time.Second
diff --git a/operator/init_test.go b/operator/init_test.go
index <HASH>..<HASH> 100644
--- a/operator/init_test.go
+++ b/operator/init_test.go
@@ -16,12 +16,15 @@ var (
LONG_CURL_TIMEOUT = 2 * time.Minute
)
-var context helpers.SuiteContext
+var (
+ context helpers.SuiteContext
+ config helpers.Config
+)
func TestOperator(t *testing.T) {
RegisterFailHandler(Fail)
- config := helpers.LoadConfig()
+ config = helpers.LoadConfig()
if config.DefaultTimeout > 0 {
DEFAULT_TIMEOUT = config.DefaultTimeout * time.Second
diff --git a/services/services_suite_test.go b/services/services_suite_test.go
index <HASH>..<HASH> 100644
--- a/services/services_suite_test.go
+++ b/services/services_suite_test.go
@@ -11,12 +11,15 @@ import (
. "github.com/cloudfoundry/cf-acceptance-tests/helpers/services"
)
-var context helpers.SuiteContext
+var (
+ context helpers.SuiteContext
+ config helpers.Config
+)
func TestApplications(t *testing.T) {
RegisterFailHandler(Fail)
- config := helpers.LoadConfig()
+ config = helpers.LoadConfig()
if config.DefaultTimeout > 0 {
DEFAULT_TIMEOUT = config.DefaultTimeout * time.Second | Make config global in all suites
[#<I>] | cloudfoundry_cf-acceptance-tests | train |
d77c65790c05de50ae2fbadb0daef8c926be8579 | diff --git a/digitalocean/Action.py b/digitalocean/Action.py
index <HASH>..<HASH> 100644
--- a/digitalocean/Action.py
+++ b/digitalocean/Action.py
@@ -18,12 +18,12 @@ class Action(BaseAPI):
super(Action, self).__init__(*args, **kwargs)
@classmethod
- def get_object(cls, api_token, droplet_id, action_id):
+ def get_object(cls, api_token, action_id):
"""
- Class method that will return a Action object by ID and Droplet ID.
+ Class method that will return a Action object by ID.
"""
- action = cls(token=api_token, droplet_id=droplet_id, id=action_id)
- action.load()
+ action = cls(token=api_token, id=action_id)
+ action.load_directly()
return action
def load_directly(self): | The class method to get the object from a specific ID does not required the Droplet ID anymore. | koalalorenzo_python-digitalocean | train |
58e9b1893053d2dd678b220aa08e2b83598cdaec | diff --git a/xtuml/model.py b/xtuml/model.py
index <HASH>..<HASH> 100644
--- a/xtuml/model.py
+++ b/xtuml/model.py
@@ -236,6 +236,8 @@ class BaseObject(object):
__m__ = None # store a handle to the meta model which created the instance
__c__ = dict() # store a cached results from queries
__a__ = list() # store a list of attributes (name, type)
+ __i__ = set() # set of identifying attributes
+ __d__ = set() # set of derived attributes
def __init__(self):
self.__c__.clear()
@@ -359,6 +361,7 @@ class MetaModel(object):
'''
Cls = type(kind, (BaseObject,), dict(__r__=dict(), __q__=dict(),
__c__=dict(), __m__=self,
+ __i__=set(), __d__=set(),
__a__=attributes, __doc__=doc))
kind = kind.upper()
self.classes[kind] = Cls
@@ -419,6 +422,9 @@ class MetaModel(object):
Source = self.classes[source_kind]
Target = self.classes[target_kind]
+ Source.__d__ |= set(ass.source.ids)
+ Target.__i__ |= set(ass.target.ids)
+
if rel_id not in Source.__r__:
Source.__r__[rel_id] = set() | model: keep track of identifying and derived attributes | xtuml_pyxtuml | train |
47ae09467576f23b72292ba64694a9a4a36b221d | diff --git a/src/openseadragon.js b/src/openseadragon.js
index <HASH>..<HASH> 100644
--- a/src/openseadragon.js
+++ b/src/openseadragon.js
@@ -1725,6 +1725,21 @@ window.OpenSeadragon = window.OpenSeadragon || function( options ){
return value ? value : null;
},
+ /**
+ * Retrieves the protocol used by the url. The url can either be absolute
+ * or relative.
+ * @function
+ * @param {String} url The url to retrieve the protocol from.
+ * @return {String} The protocol (http:, https:, file:, ftp: ...)
+ */
+ getUrlProtocol: function( url ) {
+ var match = url.match(/^([a-z]+:)\/\//i);
+ if ( match === null ) {
+ // Relative URL, retrive the protocol from window.location
+ return window.location.protocol;
+ }
+ return match[1].toLowerCase();
+ },
createAjaxRequest: function(){
var request;
@@ -1778,10 +1793,13 @@ window.OpenSeadragon = window.OpenSeadragon || function( options ){
if ( request.readyState == 4 ) {
request.onreadystatechange = function(){};
- if ( request.status == 200 ) {
+ var protocol = $.getUrlProtocol( url );
+ var successStatus =
+ protocol === "http:" || protocol === "https:" ? 200 : 0;
+ if ( request.status === successStatus ) {
onSuccess( request );
} else {
- $.console.log( "AJAX request returned %s: %s", request.status, url );
+ $.console.log( "AJAX request returned %d: %s", request.status, url );
if ( $.isFunction( onError ) ) {
onError( request );
diff --git a/test/basic.js b/test/basic.js
index <HASH>..<HASH> 100644
--- a/test/basic.js
+++ b/test/basic.js
@@ -56,7 +56,7 @@
equal($(".openseadragon-message").length, 1, "Open failures should display a message");
- ok(testLog.log.contains('["AJAX request returned %s: %s",404,"/test/data/not-a-real-file"]'),
+ ok(testLog.log.contains('["AJAX request returned %d: %s",404,"/test/data/not-a-real-file"]'),
"AJAX failures should be logged to the console");
start();
diff --git a/test/utils.js b/test/utils.js
index <HASH>..<HASH> 100644
--- a/test/utils.js
+++ b/test/utils.js
@@ -87,6 +87,30 @@
);
});
+ test("getUrlProtocol", function() {
+
+ equal(OpenSeadragon.getUrlProtocol("test"), window.location.protocol,
+ "'test' url protocol should be window.location.protocol");
+
+ equal(OpenSeadragon.getUrlProtocol("/test"), window.location.protocol,
+ "'/test' url protocol should be window.location.protocol");
+
+ equal(OpenSeadragon.getUrlProtocol("//test"), window.location.protocol,
+ "'//test' url protocol should be window.location.protocol");
+
+ equal(OpenSeadragon.getUrlProtocol("http://test"), "http:",
+ "'http://test' url protocol should be http:");
+
+ equal(OpenSeadragon.getUrlProtocol("https://test"), "https:",
+ "'https://test' url protocol should be https:");
+
+ equal(OpenSeadragon.getUrlProtocol("file://test"), "file:",
+ "'file://test' url protocol should be file:");
+
+ equal(OpenSeadragon.getUrlProtocol("FTP://test"), "ftp:",
+ "'FTP://test' url protocol should be ftp:");
+ });
+
// ----------
asyncTest("requestAnimationFrame", function() {
var timeWatcher = Util.timeWatcher(); | Fix ajax call for file: and ftp: #<I> | openseadragon_openseadragon | train |
03843715a5ea26483e8d546d1d0ba90542678fc4 | diff --git a/src/AcuityScheduling.php b/src/AcuityScheduling.php
index <HASH>..<HASH> 100644
--- a/src/AcuityScheduling.php
+++ b/src/AcuityScheduling.php
@@ -103,7 +103,7 @@ class AcuityScheduling {
/**
* Verify a message signature using your API key.
*/
- public static function verifyMessageSignature ($secret, $body = null, $signature = null) {
+ public static function verifyMessageSignature($secret, $body = null, $signature = null) {
// Compute hash of message using shared secret:
$body = is_null($body) ? file_get_contents('php://input') : $body;
@@ -115,4 +115,19 @@ class AcuityScheduling {
throw new Exception('This message was forged!');
}
}
+
+ public static function getEmbedCode($owner, $options)
+ {
+ $owner = htmlspecialchars($owner);
+ $defaults = [
+ 'height' => '800',
+ 'width' => '100%'
+ ];
+ foreach ($options as $key => $option) {
+ $defaults[$key] = htmlspecialchars($option);
+ }
+ return
+ "<iframe src=\"https://app.acuityscheduling.com/schedule.php?owner={$owner}\" width=\"{$defaults['width']}\" height=\"{$defaults['height']}\" frameBorder=\"0\"></iframe>".
+ '<script src="https://d3gxy7nm8y4yjr.cloudfront.net/js/embed.js" type="text/javascript"></script>';
+ }
} | Initial scheduler embed-code builder. | AcuityScheduling_acuity-php | train |
33ae504a9928437d76142eaaa3c79232148adaad | diff --git a/functions/i18n.php b/functions/i18n.php
index <HASH>..<HASH> 100644
--- a/functions/i18n.php
+++ b/functions/i18n.php
@@ -64,9 +64,9 @@ function hybrid_override_load_textdomain( $override, $domain, $mofile ) {
* a text string with the given domain. The purpose of this function is to simply check if the translation files
* are loaded.
*
- * @since 1.3.0
- * @access private This is only used internally by the framework for checking translations.
- * @param string $domain The textdomain to check translations for.
+ * @since 1.3.0
+ * @access public This is only used internally by the framework for checking translations.
+ * @param string $domain The textdomain to check translations for.
*/
function hybrid_is_textdomain_loaded( $domain ) {
global $hybrid;
@@ -78,18 +78,17 @@ function hybrid_is_textdomain_loaded( $domain ) {
* Loads an empty MO file for the framework textdomain. This will be overwritten. The framework domain
* will be merged with the theme domain.
*
- * @since 1.3.0
- * @access private
- * @uses load_textdomain() Loads an MO file into the domain for the framework.
- * @param string $domain The name of the framework's textdomain.
- * @return true|false Whether the MO file was loaded.
+ * @since 1.3.0
+ * @access public
+ * @param string $domain The name of the framework's textdomain.
+ * @return bool Whether the MO file was loaded.
*/
function hybrid_load_framework_textdomain( $domain ) {
return load_textdomain( $domain, '' );
}
/**
- * @since 0.7.0
+ * @since 0.7.0
* @deprecated 1.3.0
*/
function hybrid_get_textdomain() {
@@ -104,11 +103,10 @@ function hybrid_get_textdomain() {
* Important! Do not use this for translation functions in your theme. Hardcode your textdomain string. Your
* theme's textdomain should match your theme's folder name.
*
- * @since 1.3.0
- * @access private
- * @uses get_template() Defines the theme textdomain based on the template directory.
+ * @since 1.3.0
+ * @access public
* @global object $hybrid The global Hybrid object.
- * @return string $hybrid->textdomain The textdomain of the theme.
+ * @return string The textdomain of the theme.
*/
function hybrid_get_parent_textdomain() {
global $hybrid;
@@ -134,11 +132,10 @@ function hybrid_get_parent_textdomain() {
* Important! Do not use this for translation functions in your theme. Hardcode your textdomain string. Your
* theme's textdomain should match your theme's folder name.
*
- * @since 1.2.0
- * @access private
- * @uses get_stylesheet() Defines the child theme textdomain based on the stylesheet directory.
+ * @since 1.2.0
+ * @access public
* @global object $hybrid The global Hybrid object.
- * @return string $hybrid->child_theme_textdomain The textdomain of the child theme.
+ * @return string The textdomain of the child theme.
*/
function hybrid_get_child_textdomain() {
global $hybrid;
@@ -166,11 +163,11 @@ function hybrid_get_child_textdomain() {
* of the mofile for translations. This allows child themes to have a folder called /languages with translations
* of their parent theme so that the translations aren't lost on a parent theme upgrade.
*
- * @since 1.3.0
- * @access private
- * @param string $mofile File name of the .mo file.
- * @param string $domain The textdomain currently being filtered.
- * @return $mofile
+ * @since 1.3.0
+ * @access public
+ * @param string $mofile File name of the .mo file.
+ * @param string $domain The textdomain currently being filtered.
+ * @return string
*/
function hybrid_load_textdomain_mofile( $mofile, $domain ) { | i<I>n.php cleanup. | justintadlock_hybrid-core | train |
e984065e3c98532224d507b828b2be69325a8b5b | diff --git a/src/Sampler/RateLimitingSampler.php b/src/Sampler/RateLimitingSampler.php
index <HASH>..<HASH> 100644
--- a/src/Sampler/RateLimitingSampler.php
+++ b/src/Sampler/RateLimitingSampler.php
@@ -19,7 +19,7 @@ class RateLimitingSampler extends AbstractSampler
{
$key = $this->generator->generate($tracerId, $operationName);
$ttl = max((int)(1 / $this->rate + 1), 1);
- if (false !== ($current = apcu_add($key, sprintf('%s:%d', time(), 1), $ttl))) {
+ if (apcu_add($key, sprintf('%s:%d', time(), 1), $ttl)) {
return new SamplerResult(
true, 0x01, [
new SamplerTypeTag('ratelimiting'),
@@ -30,15 +30,17 @@ class RateLimitingSampler extends AbstractSampler
);
}
- while (true) {
+ $retries = 0;
+ while ($retries < 5) {
if (false === ($current = apcu_fetch($key))) {
return $this->doDecide($tracerId, $operationName);
}
list ($timestamp, $count) = explode(':', $current);
- if ($count / (time() - $timestamp) > $this->rate) {
+ if ((int)$count / (time() - (int)$timestamp) > $this->rate) {
return new SamplerResult(false, 0);
}
- if (false === apcu_cas($key, $current, sprintf('%s:%d', $timestamp, $count + 1))) {
+ if (false === apcu_cas($key, $current, sprintf('%s:%d', $timestamp, (int)$count + 1))) {
+ $retries++;
continue;
} | Fixed possible infinte loop in adaptive sampler | code-tool_jaeger-client-php | train |
ca3505f17ea70f0ebaa1d0ac33d6863a5e854475 | diff --git a/exchangelib/attachments.py b/exchangelib/attachments.py
index <HASH>..<HASH> 100644
--- a/exchangelib/attachments.py
+++ b/exchangelib/attachments.py
@@ -185,13 +185,14 @@ class FileAttachment(Attachment):
def __getstate__(self):
# The fp does not need to be pickled
- state = self.__dict__.copy()
+ state = {k: getattr(self, k) for k in self.__slots__}
del state['_fp']
return state
def __setstate__(self, state):
# Restore the fp
- self.__dict__.update(state)
+ for k in self.__slots__:
+ setattr(self, k, state.get(k))
self._fp = None
diff --git a/tests/__init__.py b/tests/__init__.py
index <HASH>..<HASH> 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -2245,10 +2245,11 @@ class AccountTest(EWSTest):
def test_pickle(self):
# Test that we can pickle various objects
item = Message(folder=self.account.inbox, subject='XXX', categories=self.categories).save()
- pickle.dumps(item)
+ attachment = FileAttachment(name='pickle_me.txt', content=b'')
try:
for o in (
item,
+ attachment,
self.account.protocol,
self.account.root,
self.account.inbox, | Fix and test pickling of attachments. Refs #<I> | ecederstrand_exchangelib | train |
d6135f743fd604066c298c43c1631da0fd2a3b38 | diff --git a/command/agent/cache/api_proxy.go b/command/agent/cache/api_proxy.go
index <HASH>..<HASH> 100644
--- a/command/agent/cache/api_proxy.go
+++ b/command/agent/cache/api_proxy.go
@@ -36,6 +36,11 @@ func (ap *APIProxy) Send(ctx context.Context, req *SendRequest) (*SendResponse,
return nil, err
}
client.SetToken(req.Token)
+
+ // http.Transport will transparently request gzip and decompress the response, but only if
+ // the client doesn't manually set the header. Removing any Accept-Encoding header allows the
+ // transparent compression to occur.
+ req.Request.Header.Del("Accept-Encoding")
client.SetHeaders(req.Request.Header)
fwReq := client.NewRequest(req.Request.Method, req.Request.URL.Path) | Fix Agent handling of gzipped responses (#<I>)
* Fix Agent handling of gzipped responses
Fixes #<I>
* Only remove "gzip" member, if present
* Simplify to just removing Accept-Encoding altogether | hashicorp_vault | train |
738c3af32a8d581720006fa601937282f2d33d28 | diff --git a/src/fire.js b/src/fire.js
index <HASH>..<HASH> 100644
--- a/src/fire.js
+++ b/src/fire.js
@@ -1,5 +1,5 @@
_.fire = function(target, events, props, data) {
- if (typeof props === "object" &&
+ if (typeof props === "object" && !(props instanceof Event) &&
('bubbles' in props || 'detail' in props || 'cancelable' in props)) {
props.data = data;
} else { | events are more likely to be data than props (and cause warnings as props) | esha_Eventi | train |
8053534418cd1016c2f9182a009aefee406e1bfe | diff --git a/TwitterAPIExchange.php b/TwitterAPIExchange.php
index <HASH>..<HASH> 100755
--- a/TwitterAPIExchange.php
+++ b/TwitterAPIExchange.php
@@ -246,13 +246,13 @@ class TwitterAPIExchange
*/
public function performRequest($return = true)
{
- if (!is_bool($return))
- {
- throw new Exception('performRequest parameter must be true or false');
+ if (!is_bool($return))
+ {
+ throw new Exception('performRequest parameter must be true or false');
}
$header = array($this->buildAuthorizationHeader($this->oauth), 'Expect:');
-
+
$getfield = $this->getGetfield();
$postfields = $this->getPostfields();
@@ -279,6 +279,14 @@ class TwitterAPIExchange
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
+
+ if (($error = curl_error($feed)) !== '')
+ {
+ curl_close($feed);
+
+ throw new \Exception($error);
+ }
+
curl_close($feed);
return $json; | cURL errors now throw exceptions | J7mbo_twitter-api-php | train |
17ee146c4aa75b9dadd630b4d0b07c661bdf7281 | diff --git a/public/javascripts/fileupload/application.js b/public/javascripts/fileupload/application.js
index <HASH>..<HASH> 100644
--- a/public/javascripts/fileupload/application.js
+++ b/public/javascripts/fileupload/application.js
@@ -21,7 +21,7 @@ $(function () {
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload();
- $('#fileupload').bind("fileuploadstop", function(){
+ $('#fileupload').bind("fileuploadstop", function(){
if ((files_done == filestoupload)&&(files_done >0)){
//var loc = $("#redirect-loc").html()+"?file_count="+filestoupload
var loc = $("#redirect-loc").html()
@@ -36,7 +36,7 @@ $(function () {
$("#errmsg").html(error_string)
$("#errmsg").fadeIn('slow')
}
- });
+ });
// count the number of uploaded files to send to edit
$('#fileupload').bind("fileuploadadd", function(e, data){
@@ -44,8 +44,17 @@ $(function () {
});
// count the number of files completed and ready to send to edit
- $('#fileupload').bind("fileuploaddone", function(){
- files_done++;
+ $('#fileupload').bind("fileuploaddone", function(e, data){
+ var file = ($.isArray(data.result) && data.result[0]) || {error: 'emptyResult'};
+ if (!file.error) {
+ files_done++;
+ }else {
+ if (error_string.length > 0) {
+ error_string +='<br/>';
+ }
+ error_string +=file.error;
+ }
+
});
// on fail if abort (aka cancel) decrease the number of uploaded files to send
diff --git a/public/javascripts/fileupload/jquery.fileupload.js b/public/javascripts/fileupload/jquery.fileupload.js
index <HASH>..<HASH> 100644
--- a/public/javascripts/fileupload/jquery.fileupload.js
+++ b/public/javascripts/fileupload/jquery.fileupload.js
@@ -599,6 +599,13 @@
(that._chunkedUpload(options) || $.ajax(options))) ||
that._getXHRPromise(false, options.context, args)
).done(function (result, textStatus, jqXHR) {
+ // this is in here to handel the issue where sometimes no files are sent over the pipe to generic files
+ if (result[0].error){
+ if (result[0].error == 'Error! No file to save'){
+ that._onSend(null, data);
+ return;
+ }
+ }
that._onDone(result, textStatus, jqXHR, options);
}).fail(function (jqXHR, textStatus, errorThrown) {
that._onFail(jqXHR, textStatus, errorThrown, options);
@@ -623,10 +630,14 @@
nextSlot = that._slots.shift();
}
}
+
});
return jqXHR;
};
this._beforeSend(e, options);
+ if (options.files.length != 1){
+ alert("files missing")
+ }
if (this.options.sequentialUploads ||
(this.options.limitConcurrentUploads &&
this.options.limitConcurrentUploads <= this._sending)) { | Added capture of no files error to send so that it can be resent. Also added a check for our errors so that zero length file errors will be shown to the user. refs #<I> | samvera_hyrax | train |
0eb8df33cb7a950b9bf6d1031f70a798b0403740 | diff --git a/src/utils.js b/src/utils.js
index <HASH>..<HASH> 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -1,5 +1,5 @@
/*
- * isObject, extend and isFunction are taken from undescore/lodash in
+ * isObject, extend, isFunction, and bind are taken from undescore/lodash in
* order to remove the dependency
*/
@@ -36,9 +36,11 @@ exports.handleDefaultCallback = function (listener, listenable, defaultCallback)
if (listenable.getDefaultData && isFunction(listenable.getDefaultData)) {
data = listenable.getDefaultData();
if (data && data.then && isFunction(data.then)) {
- data.then(defaultCallback.bind(listener));
+ data.then(function() {
+ defaultCallback.apply(listener, arguments);
+ });
} else {
- defaultCallback.bind(listener)(data);
+ defaultCallback.call(listener, data);
}
}
} | Changed bind calls to use apply and call instead | reflux_refluxjs | train |
1f512dc35acea1c94360c66a472156b488e03cb2 | diff --git a/bokeh/plotting.py b/bokeh/plotting.py
index <HASH>..<HASH> 100644
--- a/bokeh/plotting.py
+++ b/bokeh/plotting.py
@@ -496,6 +496,9 @@ class GlyphFunction(object):
legend_name = kwargs.pop("legend", None)
plot = self._get_plot(kwargs)
+ if 'name' in kwargs:
+ plot._id = kwargs['name']
+
select_tool = self._get_select_tool(plot)
# Process the glyph dataspec parameters
@@ -511,7 +514,6 @@ class GlyphFunction(object):
kwargs.update(glyph_params)
glyph = self.glyphclass(**kwargs)
-
nonselection_glyph = glyph.clone()
nonselection_glyph.fill_alpha = 0.1
nonselection_glyph.line_alpha = 0.1
diff --git a/examples/plotting/file/iris.py b/examples/plotting/file/iris.py
index <HASH>..<HASH> 100644
--- a/examples/plotting/file/iris.py
+++ b/examples/plotting/file/iris.py
@@ -9,12 +9,16 @@ def iris():
flowers['color'] = flowers['species'].map(lambda x: colormap[x])
- scatter(flowers["petal_length"], flowers["petal_width"],
- color=flowers["color"], fill_alpha=0.2, radius=5)
+ #setting the name kwarg will give this scatter plot a user
+ #friendly id, and the corresponding embed.js will have a nice name
+ #too
+
+ scatter(flowers["petal_length"], flowers["petal_width"],
+ color=flowers["color"], fill_alpha=0.2, radius=5, name="iris")
return curplot()
if __name__ == "__main__":
- iris()
+ iris().script_direct_inject()
# open a browser
show() | added the name parameter to plot creation, this maps to the _id field, making for much better named embed.js files | bokeh_bokeh | train |
2151285c3268f9b6e2e49e4ddba594f72ed3ae79 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -19,7 +19,7 @@ import logging
setup(
name='fedmsg',
- version='0.0.1',
+ version='0.0.2',
description="Fedora Messaging Client API",
long_description=long_description,
author='Ralph Bean', | Starting work on <I>. | fedora-infra_fedmsg | train |
b331a06998e479700b4a2ac1dcd2940696eabf83 | diff --git a/src/java/voldemort/store/metadata/MetadataStore.java b/src/java/voldemort/store/metadata/MetadataStore.java
index <HASH>..<HASH> 100644
--- a/src/java/voldemort/store/metadata/MetadataStore.java
+++ b/src/java/voldemort/store/metadata/MetadataStore.java
@@ -531,31 +531,40 @@ public class MetadataStore extends AbstractStorageEngine<ByteArray, byte[], byte
String key = ByteUtils.getString(keyBytes.get(), "UTF-8");
if(METADATA_KEYS.contains(key) || this.storeNames.contains(key)) {
- List<Versioned<byte[]>> values = Lists.newArrayList();
+ try {
+ List<Versioned<byte[]>> values = Lists.newArrayList();
- // Get the cached value and convert to string
- Versioned<String> value = convertObjectToString(key, metadataCache.get(key));
+ // Get the cached value and convert to string
+ Versioned<String> value = convertObjectToString(key, metadataCache.get(key));
- // Metadata debugging information
- if(logger.isTraceEnabled())
- logger.trace("Key " + key + " requested, returning: " + value.getValue());
+ // Metadata debugging information
+ if(logger.isTraceEnabled())
+ logger.trace("Key " + key + " requested, returning: " + value.getValue());
- values.add(new Versioned<byte[]>(ByteUtils.getBytes(value.getValue(), "UTF-8"),
- value.getVersion()));
+ values.add(new Versioned<byte[]>(ByteUtils.getBytes(value.getValue(), "UTF-8"),
+ value.getVersion()));
- return values;
+ return values;
+ } catch(Exception e) {
+ throw new VoldemortException("Failed to read metadata key:"
+ + ByteUtils.getString(keyBytes.get(),
+ "UTF-8")
+ + " delete config/.temp config/.version directories and restart.",
+ e);
+ }
} else {
- throw new VoldemortException("Unhandled Key:" + key + " for MetadataStore get()");
+ // This exception can be thrown in two cases.
+ // 1. An operator running vadmin.sh meta get <key> mistype the <key>
+ // 2. Client doing getStoreClient passed in a store name that does not exist
+ // Since there is no way to tell the difference between 1&2, the error message
+ // is focused on use case 2. In the future, if that is a problem the error message
+ // can be made to reflect both the cases.
+ throw new VoldemortException("Store " + key + " does not exist on node "
+ + this.getNodeId());
}
- } catch(Exception e) {
- throw new VoldemortException("Failed to read metadata key:"
- + ByteUtils.getString(keyBytes.get(), "UTF-8")
- + " delete config/.temp config/.version directories and restart.",
- e);
} finally {
readLock.unlock();
}
-
}
public List<Versioned<byte[]>> get(String key, String transforms) throws VoldemortException { | When store is missing, error message is not clear
When a store is missing on the Server, Voldemort error message on
the client used to say
Failed to read metadata key:"XXX" delete config/.temp config/.version directories and restart.
Now it says store XXX does not exist on node YY
This will be easier to reason from the client perspective. | voldemort_voldemort | train |
bd502e8bd5d126c4a273ed9b402e0605dfdf7222 | diff --git a/java/api/src/main/java/io/ray/api/call/BaseActorCreator.java b/java/api/src/main/java/io/ray/api/call/BaseActorCreator.java
index <HASH>..<HASH> 100644
--- a/java/api/src/main/java/io/ray/api/call/BaseActorCreator.java
+++ b/java/api/src/main/java/io/ray/api/call/BaseActorCreator.java
@@ -1,6 +1,5 @@
package io.ray.api.call;
-import io.ray.api.Ray;
import io.ray.api.options.ActorCreationOptions;
import io.ray.api.placementgroup.PlacementGroup;
import java.util.Map;
@@ -14,9 +13,7 @@ public class BaseActorCreator<T extends BaseActorCreator> {
protected ActorCreationOptions.Builder builder = new ActorCreationOptions.Builder();
/**
- * Set the actor name of a named actor. This named actor is only accessible from this job by this
- * name via {@link Ray#getActor(java.lang.String)}. If you want create a named actor that is
- * accessible from all jobs, use {@link BaseActorCreator#setGlobalName(java.lang.String)} instead.
+ * Set the actor name of a named actor.
*
* @param name The name of the named actor.
* @return self | [Java] Remove out of date comment. (#<I>)
The semantic of `setName` API is changed, but the comment is out of date. This PR fixes it. | ray-project_ray | train |
3826c1e5428a2b1a52a8a1c60a9c00c480000edf | diff --git a/examples/variational_autoencoder.py b/examples/variational_autoencoder.py
index <HASH>..<HASH> 100644
--- a/examples/variational_autoencoder.py
+++ b/examples/variational_autoencoder.py
@@ -117,7 +117,7 @@ if __name__ == '__main__':
def print_perf(combined_params, iter, grad):
if iter % 10 == 0:
gen_params, rec_params = combined_params
- bound = np.mean(objective(combined_params, iter))
+ bound = objective(combined_params, iter)
print("{:15}|{:20}".format(iter//num_batches, bound))
fake_data = generate_from_prior(gen_params, 20, latent_dim, seed) | Remove unnecessary mean from vae example (#<I>)
A very minor point... `objective` is already a scalar, so taking its mean here does nothing. | HIPS_autograd | train |
ffaced9cda93afb92af7761b59f545f4d0e39cf3 | diff --git a/lib/oauth/client/em_http.rb b/lib/oauth/client/em_http.rb
index <HASH>..<HASH> 100644
--- a/lib/oauth/client/em_http.rb
+++ b/lib/oauth/client/em_http.rb
@@ -33,7 +33,12 @@ class EventMachine::HttpClient
:timestamp => nil }.merge(options)
@oauth_helper = OAuth::Client::Helper.new(self, options)
- self.send("set_oauth_#{options[:scheme]}")
+
+ # TODO this isn't executing properly, so it's currently hard-coded to the
+ # only supported scheme
+ # self.send("set_oauth_#{options[:scheme]}")
+
+ set_oauth_header
end
# Create a string suitable for signing for an HTTP request. This process involves parameter
@@ -91,4 +96,4 @@ private
raise NotImplementedError, 'please use the set_oauth_header method instead'
end
-end
\ No newline at end of file
+end
diff --git a/test/test_em_http_client.rb b/test/test_em_http_client.rb
index <HASH>..<HASH> 100644
--- a/test/test_em_http_client.rb
+++ b/test/test_em_http_client.rb
@@ -21,7 +21,7 @@ class EmHttpClientTest < Test::Unit::TestCase
assert_equal 'GET', request.method
assert_equal '/test', request.normalize_uri.path
assert_equal "key=value", request.normalize_uri.query
- assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\"".split(', ').sort, authz_header(request).split(', ').sort
+ assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"1oO2izFav1GP4kEH2EskwXkCRFg%3D\", oauth_version=\"1.0\""[6..-1].split(', ').sort, authz_header(request)[6..-1].split(', ').sort
end
def test_that_using_auth_headers_on_get_requests_works_with_plaintext
@@ -35,7 +35,7 @@ class EmHttpClientTest < Test::Unit::TestCase
assert_equal 'GET', request.method
assert_equal '/test', request.normalize_uri.path
assert_equal "key=value", request.normalize_uri.query
- assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"PLAINTEXT\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"5888bf0345e5d237%263196ffd991c8ebdb\", oauth_version=\"1.0\"".split(', ').sort, authz_header(request).split(', ').sort
+ assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"PLAINTEXT\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"5888bf0345e5d237%263196ffd991c8ebdb\", oauth_version=\"1.0\""[6..-1].split(', ').sort, authz_header(request)[6..-1].split(', ').sort
end
def test_that_using_auth_headers_on_post_requests_works
@@ -45,7 +45,7 @@ class EmHttpClientTest < Test::Unit::TestCase
assert_equal 'POST', request.method
assert_equal '/test', request.uri.path
assert_equal 'key=value', request.normalize_body
- assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\"".split(', ').sort, authz_header(request).split(', ').sort
+ assert_equal "OAuth oauth_nonce=\"225579211881198842005988698334675835446\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"token_411a7f\", oauth_timestamp=\"1199645624\", oauth_consumer_key=\"consumer_key_86cad9\", oauth_signature=\"26g7wHTtNO6ZWJaLltcueppHYiI%3D\", oauth_version=\"1.0\""[6..-1].split(', ').sort, authz_header(request)[6..-1].split(', ').sort
end
protected
@@ -65,4 +65,4 @@ class EmHttpClientTest < Test::Unit::TestCase
headers['Authorization']
end
-end
\ No newline at end of file
+end | fix em_http_client tests | oauth-xx_oauth-ruby | train |
995c4a0e756c09be2aedfc0abd376344df257fb6 | diff --git a/src/conrad.js b/src/conrad.js
index <HASH>..<HASH> 100644
--- a/src/conrad.js
+++ b/src/conrad.js
@@ -581,7 +581,7 @@
/**
* Kills one or more jobs, indicated by their ids. It is only possible to
* kill running jobs or waiting jobs. If you try to kill a job that does not
- * exists or that is already killed, a warning will be thrown.
+ * exist or that is already killed, a warning will be thrown.
*
* @param {Array|String} v1 A string job id or an array of job ids.
* @return {Object} Returns conrad.
@@ -726,7 +726,7 @@
}
/**
- * Unreference every jobs that are stored in the _doneJobs object. It will
+ * Unreference every job that is stored in the _doneJobs object. It will
* not be possible anymore to get stats about these jobs, but it will release
* the memory.
* | Fixed grammar
Fixed grammar in line <I> and <I> | jacomyal_sigma.js | train |
84b5728e3392921a1d0f02e8a5cce8b2a8da24c3 | diff --git a/lib/jets/application.rb b/lib/jets/application.rb
index <HASH>..<HASH> 100644
--- a/lib/jets/application.rb
+++ b/lib/jets/application.rb
@@ -132,13 +132,18 @@ class Jets::Application
effect: "Allow",
resource: "arn:aws:logs:#{Jets.aws.region}:#{Jets.aws.account}:log-group:/aws/lambda/#{project_namespace}-*",
}
- s3_glob = "#{Jets.aws.s3_bucket}*"
- s3 = {
- action: ["s3:*"],
+ s3_bucket = Jets.aws.s3_bucket
+ s3_readonly = {
+ action: ["s3:Get*", "s3:List*"],
effect: "Allow",
- resource: "arn:aws:s3:::#{s3_glob}",
+ resource: "arn:aws:s3:::#{s3_bucket}*",
}
- policies = [logs, s3]
+ s3_bucket = {
+ action: ["s3:ListAllMyBuckets", "s3:HeadBucket"],
+ effect: "Allow",
+ resource: "arn:aws:s3:::*", # scoped to all buckets
+ }
+ policies = [logs, s3_readonly, s3_bucket]
if Jets::Stack.has_resources?
cloudformation = { | improve default iam policy readonly access to s3 bucket | tongueroo_jets | train |
d04ba61c259cce2913a082851b1c9b9c4d109755 | diff --git a/test/plugin/test_buffer.rb b/test/plugin/test_buffer.rb
index <HASH>..<HASH> 100644
--- a/test/plugin/test_buffer.rb
+++ b/test/plugin/test_buffer.rb
@@ -25,11 +25,6 @@ module FluentPluginBufferTest
@purged = false
@failing = false
end
- def append(data)
- @append_count += 1
- raise DummyMemoryChunkError if @failing
- super
- end
def concat(data, size)
@append_count += 1
raise DummyMemoryChunkError if @failing
diff --git a/test/plugin/test_buffer_chunk.rb b/test/plugin/test_buffer_chunk.rb
index <HASH>..<HASH> 100644
--- a/test/plugin/test_buffer_chunk.rb
+++ b/test/plugin/test_buffer_chunk.rb
@@ -30,7 +30,7 @@ class BufferChunkTest < Test::Unit::TestCase
assert chunk.respond_to?(:open)
assert chunk.respond_to?(:write_to)
assert chunk.respond_to?(:msgpack_each)
- assert_raise(NotImplementedError){ chunk.append(nil) }
+ assert_raise(NotImplementedError){ chunk.append([]) }
assert_raise(NotImplementedError){ chunk.commit }
assert_raise(NotImplementedError){ chunk.rollback }
assert_raise(NotImplementedError){ chunk.bytesize } | fix tests to fit shrinked code | fluent_fluentd | train |
656159a5959b6a578fc890348284f5194f1c5917 | diff --git a/ctypeslib/codegen/cursorhandler.py b/ctypeslib/codegen/cursorhandler.py
index <HASH>..<HASH> 100644
--- a/ctypeslib/codegen/cursorhandler.py
+++ b/ctypeslib/codegen/cursorhandler.py
@@ -757,7 +757,11 @@ class CursorHandler(ClangHandler):
log.debug('Fixup_struct: Member:%s offsetbits:%d->%d expecting offset:%d',
member.name, member.offset, member.offset + member.bits, offset)
if member.offset < 0:
- # FIXME INCOMPLETEARRAY
+ # FIXME INCOMPLETEARRAY (clang bindings?)
+ # All fields have offset == -2. No padding will be done.
+ # But the fields are ordered and code will be produces with typed info.
+ # so in most cases, it will work. if there is a structure with incompletearray
+ # and padding or alignement issue, it will produce wrong results
# just exit
return
if member.offset > offset: | Fixes #<I>, but introduce another bug.
Incomplete array is complicated.
Probably a bug/corner case in clang bindings.
Correct Field offset should be produced by Clang bindings. | trolldbois_ctypeslib | train |
654997ac4d485f77a61a95b6046c5e74b787b697 | diff --git a/server/src/main/java/net/kuujo/copycat/raft/server/state/PassiveState.java b/server/src/main/java/net/kuujo/copycat/raft/server/state/PassiveState.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/net/kuujo/copycat/raft/server/state/PassiveState.java
+++ b/server/src/main/java/net/kuujo/copycat/raft/server/state/PassiveState.java
@@ -31,7 +31,7 @@ import java.util.concurrent.atomic.AtomicLong;
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
-public class PassiveState extends AbstractState {
+class PassiveState extends AbstractState {
protected boolean transition;
public PassiveState(RaftServerState context) { | Make PassiveState package private. | atomix_atomix | train |
5f67cf6ac7c00cd63f653d71b6a7193ad15a4654 | diff --git a/spec/dragonfly/analysis/file_command_analyser_spec.rb b/spec/dragonfly/analysis/file_command_analyser_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/dragonfly/analysis/file_command_analyser_spec.rb
+++ b/spec/dragonfly/analysis/file_command_analyser_spec.rb
@@ -36,20 +36,11 @@ describe Dragonfly::Analysis::FileCommandAnalyser do
@analyser.mime_type(@temp_object)
@temp_object.instance_eval{@tempfile}.should be_nil
end
-
- {
- :jpg => 'image/jpeg',
- :png => 'image/png',
- :gif => 'image/gif',
- :tif => 'image/tiff'
- }.each do |format, mime_type|
- it "should work properly (without a broken pipe error) for big files of format #{format}" do
- data = Dragonfly::ImageMagick::Generator.new.plasma(1000, 1000, format).first
- temp_object = Dragonfly::TempObject.new(data)
- @analyser.mime_type(temp_object).should == mime_type
- end
+ it "should work properly (without a broken pipe error) for big files of format jpg" do
+ data = Dragonfly::ImageMagick::Generator.new.plasma(1000, 1000, :jpg).first
+ temp_object = Dragonfly::TempObject.new(data)
+ @analyser.mime_type(temp_object).should == "image/jpeg"
end
-
end
end | Got rid of slow FileCommandAnalyser tests when we could do with just one of em | markevans_dragonfly | train |
a1a470f428179d69e06310992b9bcab3e66441ac | diff --git a/src/mappers/har.js b/src/mappers/har.js
index <HASH>..<HASH> 100644
--- a/src/mappers/har.js
+++ b/src/mappers/har.js
@@ -31,8 +31,7 @@ module.exports = {
useragent(true);
return map;
- },
- separator: '\n'
+ }
};
function map (data, referer, userAgent) { | Remove separator from HAR mapper. | springernature_boomcatch | train |
82a1834590379e00bb5a1ddb7d01373c697b2157 | diff --git a/test/functional/associations/test_many_documents_as_proxy.rb b/test/functional/associations/test_many_documents_as_proxy.rb
index <HASH>..<HASH> 100644
--- a/test/functional/associations/test_many_documents_as_proxy.rb
+++ b/test/functional/associations/test_many_documents_as_proxy.rb
@@ -179,7 +179,7 @@ class ManyDocumentsAsProxyTest < Test::Unit::TestCase
end
should "work with conditions" do
- comment = @post.comments.first(:conditions => {:body => 'comment2'})
+ comment = @post.comments.first(:conditions => {:body => 'comment2'}, :order => 'body desc')
comment.should == @comment2
end
end | Added explicit order to #first test for as proxy. | mongomapper_mongomapper | train |
db3ec698e9c7702384069817eff6d7e1596ef166 | diff --git a/data/pieceStore/blob.go b/data/pieceStore/blob.go
index <HASH>..<HASH> 100644
--- a/data/pieceStore/blob.go
+++ b/data/pieceStore/blob.go
@@ -78,10 +78,12 @@ func (me *data) WriteSectionTo(w io.Writer, off, n int64) (written int64, err er
off %= me.info.PieceLength
for n != 0 {
if i >= me.info.NumPieces() {
+ err = io.EOF
break
}
p := me.info.Piece(i)
if off >= p.Length() {
+ err = io.EOF
break
}
var pr io.ReadCloser | Some missing io.EOFs | anacrolix_torrent | train |
f3f6d8a1e478d15a9954bb7e39490bd74ded3f6f | diff --git a/hadoop-gremlin/src/main/java/org/apache/tinkerpop/gremlin/hadoop/structure/HadoopGraph.java b/hadoop-gremlin/src/main/java/org/apache/tinkerpop/gremlin/hadoop/structure/HadoopGraph.java
index <HASH>..<HASH> 100644
--- a/hadoop-gremlin/src/main/java/org/apache/tinkerpop/gremlin/hadoop/structure/HadoopGraph.java
+++ b/hadoop-gremlin/src/main/java/org/apache/tinkerpop/gremlin/hadoop/structure/HadoopGraph.java
@@ -64,6 +64,10 @@ import java.util.stream.Stream;
reason = "Hadoop-Gremlin is OLAP-oriented and for OLTP operations, linear-scan joins are required. This particular tests takes many minutes to execute.")
@Graph.OptOut(
test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.MatchTest$Traversals",
+ method = "g_V_matchXa_0sungBy_b__a_0writtenBy_c__b_writtenBy_dX_whereXc_sungBy_dX_whereXd_hasXname_GarciaXX",
+ reason = "Hadoop-Gremlin is OLAP-oriented and for OLTP operations, linear-scan joins are required. This particular tests takes many minutes to execute.")
[email protected](
+ test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.MatchTest$Traversals",
method = "g_V_matchXa_knows_b__c_knows_bX",
reason = "Giraph does a hard kill on failure and stops threads which stops test cases. Exception handling semantics are correct though.")
//computers = {GiraphGraphComputer.class})
@@ -105,6 +109,10 @@ import java.util.stream.Stream;
method = "g_V_matchXa_0sungBy_b__a_0writtenBy_c__b_writtenBy_d__c_sungBy_d__d_hasXname_GarciaXX",
reason = "Hadoop-Gremlin is OLAP-oriented and for OLTP operations, linear-scan joins are required. This particular tests takes many minutes to execute.")
@Graph.OptOut(
+ test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.GroovyMatchTest$Traversals",
+ method = "g_V_matchXa_0sungBy_b__a_0writtenBy_c__b_writtenBy_dX_whereXc_sungBy_dX_whereXd_hasXname_GarciaXX",
+ reason = "Hadoop-Gremlin is OLAP-oriented and for OLTP operations, linear-scan joins are required. This particular tests takes many minutes to execute.")
[email protected](
test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.CountTest$Traversals",
method = "g_V_both_both_count",
reason = "Hadoop-Gremlin is OLAP-oriented and for OLTP operations, linear-scan joins are required. This particular tests takes many minutes to execute.") | Added some extra OptOuts to HadoopGraph for "slow" tests.
This was necessary after refactoring that split single tests that tested multiple traversals. | apache_tinkerpop | train |
95aea5fcc81ceb709cc2d258125c59887c1e82cb | diff --git a/eZ/Publish/Core/FieldType/Page/PageStorage/Gateway/LegacyStorage.php b/eZ/Publish/Core/FieldType/Page/PageStorage/Gateway/LegacyStorage.php
index <HASH>..<HASH> 100644
--- a/eZ/Publish/Core/FieldType/Page/PageStorage/Gateway/LegacyStorage.php
+++ b/eZ/Publish/Core/FieldType/Page/PageStorage/Gateway/LegacyStorage.php
@@ -19,8 +19,9 @@ use ezcQuerySelect;
class LegacyStorage extends Gateway
{
- const POOL_TABLE = 'ezm_pool';
-
+ /**
+ * @var \eZ\Publish\Core\Persistence\Legacy\EzcDbHandler
+ */
protected $dbHandler;
/**
@@ -76,7 +77,7 @@ class LegacyStorage extends Gateway
$q = $dbHandler->createSelectQuery();
$q
->select( '*' )
- ->from( $dbHandler->quoteTable( self::POOL_TABLE ) )
+ ->from( $dbHandler->quoteTable( 'ezm_pool' ) )
->where(
$q->expr->eq( 'block_id', $q->bindValue( $block->id ) ),
$q->expr->gt( 'ts_visible', $q->bindValue( 0, null, \PDO::PARAM_INT ) ),
@@ -111,7 +112,7 @@ class LegacyStorage extends Gateway
$q = $dbHandler->createSelectQuery();
$q
->select( '*' )
- ->from( $dbHandler->quoteTable( self::POOL_TABLE ) )
+ ->from( $dbHandler->quoteTable( 'ezm_pool' ) )
->where(
$q->expr->eq( 'block_id', $q->bindValue( $block->id ) ),
$q->expr->gt( 'ts_visible', $q->bindValue( 0, null, \PDO::PARAM_INT ) ),
@@ -143,7 +144,7 @@ class LegacyStorage extends Gateway
$q = $dbHandler->createSelectQuery();
$q
->select( '*' )
- ->from( $dbHandler->quoteTable( self::POOL_TABLE ) )
+ ->from( $dbHandler->quoteTable( 'ezm_pool' ) )
->where(
$q->expr->eq( 'block_id', $q->bindValue( $block->id ) ),
$q->expr->eq( 'ts_visible', $q->bindValue( 0, null, \PDO::PARAM_INT ) ),
@@ -178,7 +179,7 @@ class LegacyStorage extends Gateway
$q = $dbHandler->createSelectQuery();
$q
->select( '*' )
- ->from( $dbHandler->quoteTable( self::POOL_TABLE ) )
+ ->from( $dbHandler->quoteTable( 'ezm_pool' ) )
->where(
$q->expr->eq( 'block_id', $q->bindValue( $block->id ) ),
$q->expr->gt( 'ts_hidden', $q->bindValue( 0, null, \PDO::PARAM_INT ) ) | EZP-<I> - Removed POOL_TABLE constant in Page storage gateway | ezsystems_ezpublish-kernel | train |
65b781560d46251c621ac2b2e55189ce70ff7ace | diff --git a/salt/minion.py b/salt/minion.py
index <HASH>..<HASH> 100644
--- a/salt/minion.py
+++ b/salt/minion.py
@@ -146,9 +146,15 @@ class Minion(object):
if not self._glob_match(data['tgt']):
return
if MULTI and self.opts['multiprocessing']:
- multiprocessing.Process(target=lambda: self._thread_return(data)).start()
+ if type(data['fun']) == type(list()):
+ multiprocessing.Process(target=lambda: self._thread_multi_return(data)).start()
+ else:
+ multiprocessing.Process(target=lambda: self._thread_return(data)).start()
else:
- threading.Thread(target=lambda: self._thread_return(data)).start()
+ if type(data['fun']) == type(list()):
+ threading.Thread(target=lambda: self._thread_multi_return(data)).start()
+ else:
+ threading.Thread(target=lambda: self._thread_return(data)).start()
def _handle_pub(self, load):
'''
@@ -224,6 +230,29 @@ class Minion(object):
ret['jid'] = data['jid']
self._return_pub(ret)
+ def _thread_multi_return(self, data):
+ '''
+ This methos should be used as a threading target, start the actual
+ minion side execution.
+ '''
+ ret = {'return': {}}
+ for ind in range(0, data['fun']):
+ for ind in range(0, len(data['arg'][ind])):
+ try:
+ data['arg'][ind] = eval(data['arg'][ind])
+ except:
+ pass
+
+ try:
+ ret['return'][data['fun']]\
+ = self.functions[data['fun'][ind]](*data['arg'][ind])
+ except Exception as exc:
+ self.opts['logger'].warning('The minion function caused an'\
+ + ' exception: ' + str(exc))
+ ret['return'][data['fun']] = exc
+ ret['jid'] = data['jid']
+ self._return_pub(ret)
+
def _return_pub(self, ret):
'''
Return the data from the executed command to the master server | Add support to the minion for compound execution | saltstack_salt | train |
a2b58c425bbb4a3ad934cbb8bd9e50a1d29583ea | diff --git a/src/jamesiarmes/PhpEws/Client.php b/src/jamesiarmes/PhpEws/Client.php
index <HASH>..<HASH> 100644
--- a/src/jamesiarmes/PhpEws/Client.php
+++ b/src/jamesiarmes/PhpEws/Client.php
@@ -575,6 +575,26 @@ class Client
}
/**
+ * Empties folders in a mailbox.
+ *
+ * Optionally, this operation enables you to delete the subfolders of the
+ * specified folder. When a subfolder is deleted, the subfolder and the
+ * messages within the subfolder are deleted.
+ *
+ * @since Exchange 2010
+ *
+ * @param \jamesiarmes\PhpEws\Request\EmptyFolderType $request
+ * @return \jamesiarmes\PhpEws\Response\EmptyFolderResponseType
+ */
+ public function EmptyFolder($request)
+ {
+ $this->initializeSoapClient();
+ $response = $this->soap->{__FUNCTION__}($request);
+
+ return $this->processResponse($response);
+ }
+
+ /**
* Function Description
*
* @param \jamesiarmes\PhpEws\Request\ExpandDLType $request | Added EmptyFolder operation. | jamesiarmes_php-ews | train |
411c44b0c508206a0d3a1f3f20a4008a6fdaf364 | diff --git a/drizzlepac/haputils/cell_utils.py b/drizzlepac/haputils/cell_utils.py
index <HASH>..<HASH> 100644
--- a/drizzlepac/haputils/cell_utils.py
+++ b/drizzlepac/haputils/cell_utils.py
@@ -253,6 +253,7 @@ class SkyFootprint(object):
self.total_mask = np.zeros(meta_wcs.array_shape, dtype=np.int16)
self.scaled_mask = None
self.footprint = None
+ self.footprint_member = None
self.edges = None
self.edges_ra = None | Initialize the SkyFootprint attribute, self.footprint_member, to avoid (#<I>)
errors being raised elsewhere in the code when checking for its value. | spacetelescope_drizzlepac | train |
e892a5329f6637134e12c30a87e3a50006434990 | diff --git a/src/main/java/net/figaro/GossipMonger.java b/src/main/java/net/figaro/GossipMonger.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/figaro/GossipMonger.java
+++ b/src/main/java/net/figaro/GossipMonger.java
@@ -31,7 +31,7 @@ public class GossipMonger implements Runnable {
private static final Logger log = Logger.getLogger(GossipMonger.class);
private static GossipMonger singleton = null;
private final ExecutorService threadPool = Executors.newCachedThreadPool();
- private final GossipType types = GossipType.getDefaultInstance();
+ private final GossipType types = new GossipType();
private final ConcurrentHashMap<Integer, Set<Talker>> map = new ConcurrentHashMap<Integer, Set<Talker>>();
private final Set<Talker> listenerQueuedTalkers = new CopyOnWriteArraySet<Talker>();
private final AtomicBoolean isShutdown = new AtomicBoolean();
@@ -68,6 +68,10 @@ public class GossipMonger implements Runnable {
return new TalkerContext(tname, type, this, chest, talker);
}
+ Integer getTypeIdByName(final String type) {
+ return types.getIdByName(type);
+ }
+
void registerListenerTalker(final Talker talker) {
registerListenerTalker(talker.getName(), talker);
registerListenerTalker(GossipType.BROADCAST, talker);
diff --git a/src/main/java/net/figaro/GossipType.java b/src/main/java/net/figaro/GossipType.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/figaro/GossipType.java
+++ b/src/main/java/net/figaro/GossipType.java
@@ -30,25 +30,15 @@ public class GossipType {
*/
public static final Integer BROADCAST = Integer.valueOf(Integer.MAX_VALUE); // BROADCAST
//
- private final static GossipType singleton = new GossipType();
private final ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
private final AtomicInteger counter = new AtomicInteger();
- private GossipType() {
+ GossipType() {
map.putIfAbsent("NULL", BROADCAST);
map.putIfAbsent("BROADCAST", BROADCAST);
}
/**
- * Return default instance
- *
- * @return default instance
- */
- public static GossipType getDefaultInstance() {
- return singleton;
- }
-
- /**
* Register new type
*
* @param name
diff --git a/src/main/java/net/figaro/Whisper.java b/src/main/java/net/figaro/Whisper.java
index <HASH>..<HASH> 100644
--- a/src/main/java/net/figaro/Whisper.java
+++ b/src/main/java/net/figaro/Whisper.java
@@ -82,7 +82,7 @@ public class Whisper<T> {
* @param msg
*/
public Whisper(final Talker from, final String type, final T msg) {
- this(from, GossipType.getDefaultInstance().getIdByName(type), msg);
+ this(from, GossipMonger.getDefaultInstance().getTypeIdByName(type), msg);
}
public String toString() { | change scope of GossipType | ggrandes_figaro | train |
3e5a08300d41e6265fd8b07f4ad44d3f1ecfcfd7 | diff --git a/generated/google/apis/pubsub_v1beta2.rb b/generated/google/apis/pubsub_v1beta2.rb
index <HASH>..<HASH> 100644
--- a/generated/google/apis/pubsub_v1beta2.rb
+++ b/generated/google/apis/pubsub_v1beta2.rb
@@ -25,7 +25,7 @@ module Google
# @see https://cloud.google.com/pubsub/docs
module PubsubV1beta2
VERSION = 'V1beta2'
- REVISION = '20180402'
+ REVISION = '20180416'
# View and manage your data across Google Cloud Platform services
AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
diff --git a/generated/google/apis/pubsub_v1beta2/classes.rb b/generated/google/apis/pubsub_v1beta2/classes.rb
index <HASH>..<HASH> 100644
--- a/generated/google/apis/pubsub_v1beta2/classes.rb
+++ b/generated/google/apis/pubsub_v1beta2/classes.rb
@@ -238,11 +238,11 @@ module Google
# Defines an Identity and Access Management (IAM) policy. It is used to
# specify access control policies for Cloud Platform resources.
- # A `Policy` consists of a list of `bindings`. A `Binding` binds a list of
+ # A `Policy` consists of a list of `bindings`. A `binding` binds a list of
# `members` to a `role`, where the members can be user accounts, Google groups,
# Google domains, and service accounts. A `role` is a named list of permissions
# defined by IAM.
- # **Example**
+ # **JSON Example**
# `
# "bindings": [
# `
@@ -251,7 +251,7 @@ module Google
# "user:[email protected]",
# "group:[email protected]",
# "domain:google.com",
- # "serviceAccount:[email protected]",
+ # "serviceAccount:[email protected]"
# ]
# `,
# `
@@ -260,6 +260,17 @@ module Google
# `
# ]
# `
+ # **YAML Example**
+ # bindings:
+ # - members:
+ # - user:[email protected]
+ # - group:[email protected]
+ # - domain:google.com
+ # - serviceAccount:[email protected]
+ # role: roles/owner
+ # - members:
+ # - user:[email protected]
+ # role: roles/viewer
# For a description of IAM and its features, see the
# [IAM developer's guide](https://cloud.google.com/iam/docs).
class Policy
@@ -514,11 +525,11 @@ module Google
# Defines an Identity and Access Management (IAM) policy. It is used to
# specify access control policies for Cloud Platform resources.
- # A `Policy` consists of a list of `bindings`. A `Binding` binds a list of
+ # A `Policy` consists of a list of `bindings`. A `binding` binds a list of
# `members` to a `role`, where the members can be user accounts, Google groups,
# Google domains, and service accounts. A `role` is a named list of permissions
# defined by IAM.
- # **Example**
+ # **JSON Example**
# `
# "bindings": [
# `
@@ -527,7 +538,7 @@ module Google
# "user:[email protected]",
# "group:[email protected]",
# "domain:google.com",
- # "serviceAccount:[email protected]",
+ # "serviceAccount:[email protected]"
# ]
# `,
# `
@@ -536,6 +547,17 @@ module Google
# `
# ]
# `
+ # **YAML Example**
+ # bindings:
+ # - members:
+ # - user:[email protected]
+ # - group:[email protected]
+ # - domain:google.com
+ # - serviceAccount:[email protected]
+ # role: roles/owner
+ # - members:
+ # - user:[email protected]
+ # role: roles/viewer
# For a description of IAM and its features, see the
# [IAM developer's guide](https://cloud.google.com/iam/docs).
# Corresponds to the JSON property `policy` | Autogenerated update (<I>-<I>-<I>)
Update:
- pubsub_v1beta2 | googleapis_google-api-ruby-client | train |
46e8185736ed315506e98f2603ff9e1a3de542a8 | diff --git a/lib/Vespolina/Order/Manager/OrderManager.php b/lib/Vespolina/Order/Manager/OrderManager.php
index <HASH>..<HASH> 100644
--- a/lib/Vespolina/Order/Manager/OrderManager.php
+++ b/lib/Vespolina/Order/Manager/OrderManager.php
@@ -184,6 +184,21 @@ class OrderManager implements OrderManagerInterface
return null;
}
+ public function isValidOpenOrder(OrderInterface $order = null, PartnerInterface $owner = null)
+ {
+ if (null == $order) {
+ return false;
+ }
+
+ if (null != $owner && $owner != $order->getOwner()) {
+ return false;
+ }
+
+ // todo: make sure order is still in a usable state
+
+ return true;
+ }
+
public function processOrder(OrderInterface $order, PricingContextInterface $context = null)
{
$orderEvents = $this->eventsClass;
@@ -461,6 +476,5 @@ class OrderManager implements OrderManagerInterface
public function clearOrder(OrderInterface $order)
{
$order->clearAttributes();
-
}
} | move isValidOpenOrder from OrderProvider to OrderManager | vespolina_commerce | train |
a77ae3c33b1f15a0cb45e56cf8c5166a66c58d6c | diff --git a/src/core/components/id.js b/src/core/components/id.js
index <HASH>..<HASH> 100644
--- a/src/core/components/id.js
+++ b/src/core/components/id.js
@@ -1,7 +1,6 @@
'use strict'
const promisify = require('promisify-es6')
-const mafmt = require('mafmt')
module.exports = function id (self) {
return promisify((opts, callback) => {
@@ -13,13 +12,9 @@ module.exports = function id (self) {
setImmediate(() => callback(null, {
id: self._peerInfo.id.toB58String(),
publicKey: self._peerInfo.id.pubKey.bytes.toString('base64'),
- addresses: self._peerInfo.multiaddrs.map((ma) => {
- if (mafmt.IPFS.matches(ma)) {
- return ma.toString()
- } else {
- return ma.toString() + '/ipfs/' + self._peerInfo.id.toB58String()
- }
- }).sort(),
+ addresses: self._peerInfo.multiaddrs
+ .map((ma) => ma.toString())
+ .sort(),
agentVersion: 'js-ipfs',
protocolVersion: '9000'
}))
diff --git a/src/core/components/pre-start.js b/src/core/components/pre-start.js
index <HASH>..<HASH> 100644
--- a/src/core/components/pre-start.js
+++ b/src/core/components/pre-start.js
@@ -4,6 +4,7 @@ const peerId = require('peer-id')
const PeerInfo = require('peer-info')
const multiaddr = require('multiaddr')
const waterfall = require('async/waterfall')
+const mafmt = require('mafmt')
const utils = require('../utils')
@@ -26,7 +27,14 @@ module.exports = function preStart (self) {
self._peerInfo = new PeerInfo(id)
config.Addresses.Swarm.forEach((addr) => {
- self._peerInfo.multiaddr.add(multiaddr(addr))
+ let ma = multiaddr(addr)
+
+ if (!mafmt.IPFS.matches(ma)) {
+ ma = ma.encapsulate('/ipfs/' +
+ self._peerInfo.id.toB58String())
+ }
+
+ self._peerInfo.multiaddr.add(ma)
})
cb() | feat: no need anymore to append ipfs/Qmhash to webrtc-star multiaddrs | ipfs_js-ipfs | train |
d6f80fdfd3b947c95a9ce4beb7dc56452ce9fdba | diff --git a/textblob/en/inflect.py b/textblob/en/inflect.py
index <HASH>..<HASH> 100644
--- a/textblob/en/inflect.py
+++ b/textblob/en/inflect.py
@@ -189,7 +189,7 @@ plural_categories = {
"sand", "software", "understanding", "water"],
"s-singular": [
"acropolis", "aegis", "alias", "asbestos", "bathos", "bias", "bus", "caddis", "canvas",
- "chaos", "Christmas", "cosmos", "dais", "digitalis", "epidermis", "ethos", "gas", "glottis",
+ "chaos", "christmas", "cosmos", "dais", "digitalis", "epidermis", "ethos", "gas", "glottis",
"ibis", "lens", "mantis", "marquis", "metropolis", "pathos", "pelvis", "polis", "rhinoceros",
"sassafras", "trellis"],
"ex-ices": ["codex", "murex", "silex"],
@@ -361,7 +361,7 @@ for rule in singular_rules:
singular_uninflected = [
"aircraft", "antelope", "bison", "bream", "breeches", "britches", "carp", "cattle", "chassis",
- "christmas", "clippers", "cod", "contretemps", "corps", "debris", "diabetes", "djinn", "eland",
+ "clippers", "cod", "contretemps", "corps", "debris", "diabetes", "djinn", "eland",
"elk", "flounder", "gallows", "georgia", "graffiti", "headquarters", "herpes", "high-jinks",
"homework", "innings", "jackanapes", "mackerel", "measles", "mews", "moose", "mumps", "news",
"offspring", "pincers", "pliers", "proceedings", "rabies", "salmon", "scissors", "series", | remove Christmas from uninflected list | sloria_TextBlob | train |
c41535db842dd8e0e2979b43819500ba90c8d056 | diff --git a/src/PHPSQLParser/processors/SelectExpressionProcessor.php b/src/PHPSQLParser/processors/SelectExpressionProcessor.php
index <HASH>..<HASH> 100644
--- a/src/PHPSQLParser/processors/SelectExpressionProcessor.php
+++ b/src/PHPSQLParser/processors/SelectExpressionProcessor.php
@@ -104,6 +104,13 @@ class SelectExpressionProcessor extends AbstractProcessor {
$base_expr .= $token;
}
+ if ($alias) {
+ // remove quotation from the alias
+ $alias['no_quotes'] = $this->revokeQuotation($alias['name']);
+ $alias['name'] = trim($alias['name']);
+ $alias['base_expr'] = trim($alias['base_expr']);
+ }
+
$stripped = $this->processExpressionList($stripped);
// TODO: the last part can also be a comment, don't use array_pop
@@ -127,26 +134,17 @@ class SelectExpressionProcessor extends AbstractProcessor {
'base_expr' => trim($last['base_expr']));
// remove the last token
array_pop($tokens);
- $base_expr = join("", $tokens);
}
}
- if (!$alias) {
- $base_expr = join("", $tokens);
- } else {
- /* remove escape from the alias */
- $alias['no_quotes'] = $this->revokeQuotation($alias['name']);
- $alias['name'] = trim($alias['name']);
- $alias['base_expr'] = trim($alias['base_expr']);
- }
-
+ $base_expr = $expression;
+
// TODO: this is always done with $stripped, how we do it twice?
$processed = $this->processExpressionList($tokens);
// if there is only one part, we copy the expr_type
- // in all other cases we use "expression" as global type
+ // in all other cases we use "EXPRESSION" as global type
$type = ExpressionType::EXPRESSION;
-
if (count($processed) === 1) {
if (!$this->isSubQuery($processed[0])) {
$type = $processed[0]['expr_type']; | CHG: the base_expr of a select-expression contains now an explicit alias (with "as"). Check your client code!
git-svn-id: <URL> | greenlion_PHP-SQL-Parser | train |
acb489ad79e0e100a69c77b97579bee469526299 | diff --git a/lib/OpenLayers.js b/lib/OpenLayers.js
index <HASH>..<HASH> 100644
--- a/lib/OpenLayers.js
+++ b/lib/OpenLayers.js
@@ -414,4 +414,4 @@
/**
* Constant: VERSION_NUMBER
*/
-OpenLayers.VERSION_NUMBER="Release 2.12-rc5";
+OpenLayers.VERSION_NUMBER="Release 2.12-rc6";
diff --git a/lib/OpenLayers/SingleFile.js b/lib/OpenLayers/SingleFile.js
index <HASH>..<HASH> 100644
--- a/lib/OpenLayers/SingleFile.js
+++ b/lib/OpenLayers/SingleFile.js
@@ -7,7 +7,7 @@ var OpenLayers = {
/**
* Constant: VERSION_NUMBER
*/
- VERSION_NUMBER: "Release 2.12-rc5",
+ VERSION_NUMBER: "Release 2.12-rc6",
/**
* Constant: singleFile | set VERSION_NUMBER to <I>-rc6 | openlayers_openlayers | train |
851bfec6f7a3d96a6af3ce556818f8d126f31e75 | diff --git a/BlockOptionsManipulator.php b/BlockOptionsManipulator.php
index <HASH>..<HASH> 100644
--- a/BlockOptionsManipulator.php
+++ b/BlockOptionsManipulator.php
@@ -15,9 +15,6 @@ class BlockOptionsManipulator implements BlockOptionsManipulatorInterface
/** @var PropertyAccessor */
protected $propertyAccessor;
- /** @var PropertyPath[] */
- private $cache = [];
-
public function __construct()
{
$this->propertyAccessor = new PropertyAccessor();
@@ -118,14 +115,7 @@ class BlockOptionsManipulator implements BlockOptionsManipulatorInterface
*/
protected function getPropertyPath($optionName)
{
- if (isset($this->cache[$optionName])) {
- $propertyPath = $this->cache[$optionName];
- } else {
- $propertyPath = new PropertyPath($optionName);
- $this->cache[$optionName] = $propertyPath;
- }
-
- return $propertyPath;
+ return new PropertyPath($optionName);
}
/** | CRM-<I>: fix Load page performance degradation. Add PropertyPath cache in PropertyAccessor | oroinc_OroLayoutComponent | train |
91558cb40cbee307f16909baf7fc449b5caa2e7e | diff --git a/lib/amqp-spec/rspec.rb b/lib/amqp-spec/rspec.rb
index <HASH>..<HASH> 100644
--- a/lib/amqp-spec/rspec.rb
+++ b/lib/amqp-spec/rspec.rb
@@ -68,6 +68,34 @@ module AMQP
metadata[:em_default_options] = opts if opts
metadata[:em_default_options]
end
+
+ # before hook that will run inside EM event loop
+ def em_before *args, &block
+ scope, options = scope_and_options_from(*args)
+ em_hooks[:before][scope] << block
+ end
+
+ # after hook that will run inside EM event loop
+ def em_after *args, &block
+ scope, options = scope_and_options_from(*args)
+ em_hooks[:after][scope] << block
+ end
+
+ def em_hooks
+ metadata[:em_hooks] ||= {
+ :around => { :each => [] },
+ :before => { :each => [], :all => [], :suite => [] },
+ :after => { :each => [], :all => [], :suite => [] }
+ }
+ end
+
+ def scope_and_options_from(scope=:each, options={})
+ if Hash === scope
+ options = scope
+ scope = :each
+ end
+ return scope, options
+ end
end
def self.included(example_group)
diff --git a/spec/problematic_rspec_spec.rb b/spec/problematic_rspec_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/problematic_rspec_spec.rb
+++ b/spec/problematic_rspec_spec.rb
@@ -28,7 +28,7 @@ describe '!!!!!!!!! LEAKING OR PROBLEMATIC EXAMPLES !!!!!!!!!' do
end
end
- context 'for evented specs' do
+ context 'for evented specs', pending: true do
after { @last.should == :em_after }
it 'should execute em_before or em_after if em block is used' do | Copy-pasted before/after code from rspec/core/hooks.rb | arvicco_amqp-spec | train |
ebd698020ad12a8c284bcddcd1ea3f433a645c81 | diff --git a/languagetool-standalone/src/test/java/org/languagetool/language/LanguageIdentifierTest.java b/languagetool-standalone/src/test/java/org/languagetool/language/LanguageIdentifierTest.java
index <HASH>..<HASH> 100644
--- a/languagetool-standalone/src/test/java/org/languagetool/language/LanguageIdentifierTest.java
+++ b/languagetool-standalone/src/test/java/org/languagetool/language/LanguageIdentifierTest.java
@@ -80,7 +80,10 @@ public class LanguageIdentifierTest {
private void langAssert(String expectedLangCode, String text) {
Language expectedLang = expectedLangCode != null ? Languages.getLanguageForShortCode(expectedLangCode) : null;
+ //long start = System.currentTimeMillis();
Language detectedLang = identifier.detectLanguage(text);
+ //long end = System.currentTimeMillis();
+ //System.out.println("-> " + (end-start) + "ms");
if (!Objects.equals(expectedLang, detectedLang)) {
fail("Got '" + detectedLang + "', expected '" + expectedLangCode + "' for '" + text + "'");
} | code to measure performance (commented out) | languagetool-org_languagetool | train |
77085cbcf9ca7cf1cf8385b4d5630954f951172d | diff --git a/src/Netzmacht/Bootstrap/Templates/Modifier.php b/src/Netzmacht/Bootstrap/Templates/Modifier.php
index <HASH>..<HASH> 100644
--- a/src/Netzmacht/Bootstrap/Templates/Modifier.php
+++ b/src/Netzmacht/Bootstrap/Templates/Modifier.php
@@ -47,7 +47,7 @@ class Modifier
$template->class = implode(' ', $cssClasses);
$template->imgSize .= sprintf(' class="%s"', $imageClasses);
- if ($template->picture) {
+ if (!empty($template->picture['img']) && is_array($template->picture['img'])) {
$picture = $template->picture;
$picture['img']['class'] = $imageClasses; | Improve picture variable checking to prevent accidently overriding wrong value. | contao-bootstrap_templates | train |
f3536b583fc40dc07de400bb455f7f408f817350 | diff --git a/gwpy/tests/test_timeseries.py b/gwpy/tests/test_timeseries.py
index <HASH>..<HASH> 100644
--- a/gwpy/tests/test_timeseries.py
+++ b/gwpy/tests/test_timeseries.py
@@ -946,11 +946,16 @@ class TestTimeSeries(TestTimeSeriesBase):
utils.assert_quantity_sub_equal(sg, sg2)
# test a couple of methods
- with pytest.warns(UserWarning):
- sg = losc.spectrogram(0.5, fftlength=0.25, method='welch')
- assert sg.shape == (8, 0.25 * losc.sample_rate.value // 2 + 1)
- assert sg.df == 4 * units.Hertz
- assert sg.dt == 0.5 * units.second
+ try:
+ with pytest.warns(UserWarning):
+ sg = losc.spectrogram(0.5, fftlength=0.25, method='welch')
+ except TypeError: # old pycbc doesn't accept window as array
+ pass
+ else:
+ assert sg.shape == (8, 0.25 * losc.sample_rate.value // 2 + 1)
+ assert sg.df == 4 * units.Hertz
+ assert sg.dt == 0.5 * units.second
+
sg = losc.spectrogram(0.5, fftlength=0.25, method='scipy-bartlett')
assert sg.shape == (8, 0.25 * losc.sample_rate.value // 2 + 1)
assert sg.df == 4 * units.Hertz | tests: catch errors from pycbc
hopefully resolved in an upcoming pycbc release (new feature) | gwpy_gwpy | train |
38cb5522a46eb74d94093e3306321dda823dd0c2 | diff --git a/mailer/__init__.py b/mailer/__init__.py
index <HASH>..<HASH> 100644
--- a/mailer/__init__.py
+++ b/mailer/__init__.py
@@ -1,4 +1,4 @@
-VERSION = (0, 2, 0, "a", 1) # following PEP 386
+VERSION = (0, 2, 0, "a", 2) # following PEP 386
DEV_N = None
diff --git a/mailer/management/commands/send_mail.py b/mailer/management/commands/send_mail.py
index <HASH>..<HASH> 100644
--- a/mailer/management/commands/send_mail.py
+++ b/mailer/management/commands/send_mail.py
@@ -2,6 +2,7 @@ import logging
from django.conf import settings
from django.core.management.base import NoArgsCommand
+from django.db import connection
from mailer.engine import send_all
@@ -21,3 +22,4 @@ class Command(NoArgsCommand):
send_all()
else:
logging.info("sending is paused, quitting.")
+ connection.close() | Close connection to db after send_mail command to prevent psql 'unexpected EOF on client connection with an open transaction' error | pinax_django-mailer | train |
0b1acc2a5032684b2410290c6f682da2268829e7 | diff --git a/src/extend.js b/src/extend.js
index <HASH>..<HASH> 100644
--- a/src/extend.js
+++ b/src/extend.js
@@ -8,9 +8,8 @@ import crop from './transform/crop';
import grey from './transform/grey';
export default function extend(IJ) {
- IJ.extend('invert', invert, true);
+ IJ.extendMethod('invert', invert, true);
- IJ.extend('crop', crop);
- IJ.extend('grey', grey);
- IJ.extend('gray', grey);
+ IJ.extendMethod('crop', crop);
+ IJ.extendMethod('grey', grey).extendMethod('gray', grey);
}
diff --git a/src/ij.js b/src/ij.js
index <HASH>..<HASH> 100644
--- a/src/ij.js
+++ b/src/ij.js
@@ -6,6 +6,12 @@ import {Image, getImageData, Canvas} from './canvas';
import extend from './extend';
import {createWriteStream} from 'fs';
+let computedPropertyDescriptor = {
+ configurable: true,
+ enumerable: true,
+ get: undefined
+};
+
export default class IJ {
constructor(width, height, data, options) {
if (width === undefined) width = 1;
@@ -33,6 +39,7 @@ export default class IJ {
this.kind = kind;
this.info = map;
+ this.computed = {};
this.width = width;
this.height = height;
@@ -68,10 +75,15 @@ export default class IJ {
});
}
- static extend(name, method, inplace = false) {
+ static extendMethod(name, method, inplace = false) {
+ if (IJ.prototype.hasOwnProperty(name)) {
+ console.warn(`Method '${name}' already exists and will be overwritten`);
+ }
if (inplace) {
IJ.prototype[name] = function (...args) {
method.apply(this, args);
+ // reset computed properties
+ this.computed = {};
return this;
};
} else {
@@ -79,6 +91,24 @@ export default class IJ {
return method.apply(this, args);
};
}
+ return IJ;
+ }
+
+ static extendProperty(name, method) {
+ if (IJ.prototype.hasOwnProperty(name)) {
+ console.warn(`Property getter '${name}' already exists and will be overwritten`);
+ }
+ computedPropertyDescriptor.get = function () {
+ if (this.computed.hasOwnProperty(name)) {
+ return this.computed[name];
+ } else {
+ let result = method.call(this);
+ this.computed[name] = result;
+ return result;
+ }
+ };
+ Object.defineProperty(IJ.prototype, name, computedPropertyDescriptor);
+ return IJ;
}
static createFrom(other, {
diff --git a/src/transform/crop.js b/src/transform/crop.js
index <HASH>..<HASH> 100644
--- a/src/transform/crop.js
+++ b/src/transform/crop.js
@@ -7,7 +7,7 @@ export default function crop({
y = 0,
width = this.width - x,
height = this.height - y
- }) {
+ } = {}) {
if (x > (this.width - 1) || y > (this.height - 1))
throw new RangeError(`origin (${x}; ${y}) out of range (${this.width - 1}; ${this.height - 1})`);
diff --git a/src/transform/grey.js b/src/transform/grey.js
index <HASH>..<HASH> 100644
--- a/src/transform/grey.js
+++ b/src/transform/grey.js
@@ -2,7 +2,7 @@
import IJ from '../ij';
-export default function grey({algorithm = 'luminance'}) {
+export default function grey({algorithm = 'luminance'} = {}) {
if (this.kind.startsWith('GREY')) {
return this.clone(); | rename extend to extendMethod and add extendProperty (#9) | image-js_image-js | train |
80fc505557d907a3c016627b4c6f61edd1e84090 | diff --git a/test/common.js b/test/common.js
index <HASH>..<HASH> 100644
--- a/test/common.js
+++ b/test/common.js
@@ -1,7 +1,5 @@
/*global sinon:true, unexpected:true, unexpectedSinon:true*/
sinon = require('sinon');
unexpected = require('unexpected').clone();
-unexpectedSinon = process.env.COVERAGE ?
- require('../lib-cov/unexpected-sinon') :
- require('../lib/unexpected-sinon');
+unexpectedSinon = require('../lib/unexpected-sinon');
unexpected.installPlugin(unexpectedSinon); | test/common: Remove no longer used lib-cov support. | unexpectedjs_unexpected-sinon | train |
5066e68b398039beb5e1966ba1ed7684d97a8f74 | diff --git a/gitlab/v4/objects.py b/gitlab/v4/objects.py
index <HASH>..<HASH> 100644
--- a/gitlab/v4/objects.py
+++ b/gitlab/v4/objects.py
@@ -4644,10 +4644,6 @@ class TodoManager(ListMixin, DeleteMixin, RESTManager):
int: The number of todos maked done
"""
result = self.gitlab.http_post("/todos/mark_as_done", **kwargs)
- try:
- return int(result)
- except ValueError:
- return 0
class GeoNode(SaveMixin, ObjectDeleteMixin, RESTObject): | fix(todo): mark_all_as_done doesn't return anything | python-gitlab_python-gitlab | train |
ce13c445c7da93647aaf54628b9018583654f79a | diff --git a/lib/haml/engine.rb b/lib/haml/engine.rb
index <HASH>..<HASH> 100644
--- a/lib/haml/engine.rb
+++ b/lib/haml/engine.rb
@@ -16,9 +16,41 @@ module Haml
# Allow access to the precompiled template
attr_reader :precompiled
+ # Designates an XHTML/XML element.
+ ELEMENT = '%'[0]
+
+ # Designates a <tt><div></tt> element with the given class.
+ DIV_CLASS = '.'[0]
+
+ # Designates a <tt><div></tt> element with the given id.
+ DIV_ID = '#'[0]
+
+ # Designates an XHTML/XML comment.
+ COMMENT = '/'[0]
+
+ # Designates script, the result of which is output.
+ SCRIPT = '='[0]
+
+ # Designates script, the result of which is flattened and output.
+ FLAT_SCRIPT = '~'[0]
+
+ # Designates script which is run but not output.
+ SILENT_SCRIPT = '-'[0]
+
+ # When following SILENT_SCRIPT, designates a comment that is not output.
+ SILENT_COMMENT = '#'[0]
+
# Keeps track of the ASCII values of the characters that begin a
# specially-interpreted line.
- SPECIAL_CHARACTERS = %w(# . = ~ % /).collect { |c| c[0] }
+ SPECIAL_CHARACTERS = [
+ ELEMENT,
+ DIV_CLASS,
+ DIV_ID,
+ COMMENT,
+ SCRIPT,
+ FLAT_SCRIPT,
+ SILENT_SCRIPT
+ ]
# The value of the character that designates that a line is part
# of a multiline string.
@@ -117,7 +149,7 @@ module Haml
if count > @to_close_stack.size
# Indentation has been increased without a new tag
- if @latest_command == 45 # '-'
+ if @latest_command == SILENT_SCRIPT
# The indentation was increased after silent script,
# it must be a block
@@ -125,7 +157,7 @@ module Haml
end
elsif count <= @to_close_stack.size && @to_close_stack.size > 0 &&
- (line.length == 0 || line[0] != 45 || !MID_BLOCK_KEYWORDS.include?(line[1..-1].split[0]))
+ (line.length == 0 || line[0] != SILENT_SCRIPT || !MID_BLOCK_KEYWORDS.include?(line[1..-1].split[0]))
# The tabulation has gone down, and it's not because of one of
# Ruby's mid-block keywords
@@ -135,22 +167,22 @@ module Haml
if line.length > 0
@latest_command = line[0]
case @latest_command
- when 46, 35 # '.', '#'
+ when DIV_CLASS, DIV_ID
render_div(line, index)
- when 37 # '%'
+ when ELEMENT
render_tag(line, index)
- when 47 # '/'
+ when COMMENT
render_comment(line)
- when 61 # '='
+ when SCRIPT
push_script(line[1..-1], false, index)
- when 126 # '~'
+ when FLAT_SCRIPT
push_script(line[1..-1], true, index)
- when 45 # '-'
+ when SILENT_SCRIPT
sub_line = line[1..-1]
- unless sub_line[0] == 35 # '#'
+ unless sub_line[0] == SILENT_COMMENT
push_silent(sub_line, index)
else
- @latest_command = 35
+ @latest_command = SILENT_COMMENT
end
else
push_text line.strip
@@ -169,11 +201,11 @@ module Haml
# rendered normally.
def handle_multiline(count, line, index)
# Multilines are denoting by ending with a `|` (124)
- if line && (line[-1] == MULTILINE_CHAR_VALUE) && @multiline_buffer
+ if is_multiline?(line) && @multiline_buffer
# A multiline string is active, and is being continued
@multiline_buffer += line[0...-1]
suppress_render = true
- elsif line && (line[-1] == MULTILINE_CHAR_VALUE) && (MULTILINE_STARTERS.include? line[0])
+ elsif is_multiline?(line) && (MULTILINE_STARTERS.include? line[0])
# A multiline string has just been activated, start adding the lines
@multiline_buffer = line[0...-1]
@multiline_count = count
@@ -188,6 +220,11 @@ module Haml
return suppress_render
end
+
+ # Checks whether or not +line+ is in a multiline sequence.
+ def is_multiline?(line) # ' '[0] == 32
+ line && line.length > 1 && line[-1] == MULTILINE_CHAR_VALUE && line[-2] == 32
+ end
# Takes <tt>@precompiled</tt>, a string buffer of Ruby code, and
# evaluates it in the context of <tt>@scope_object</tt>, after preparing | Replacing magic tag-character numbers with constants.
This brought out a bug in the multiline handling, so I fixed that, too.
git-svn-id: svn://hamptoncatlin.com/haml/branches/edge@<I> <I>b-<I>-<I>-af8c-cdc<I>e<I>b9 | sass_ruby-sass | train |
6b51228ac7ae74efda36563d53cd8b0253e1c12d | diff --git a/lib/colgrep.js b/lib/colgrep.js
index <HASH>..<HASH> 100644
--- a/lib/colgrep.js
+++ b/lib/colgrep.js
@@ -1,4 +1,4 @@
-// Generated by IcedCoffeeScript 1.7.1-a
+// Generated by IcedCoffeeScript 1.7.1-c
(function() {
var colgrep;
diff --git a/lib/err.js b/lib/err.js
index <HASH>..<HASH> 100644
--- a/lib/err.js
+++ b/lib/err.js
@@ -1,4 +1,4 @@
-// Generated by IcedCoffeeScript 1.7.1-a
+// Generated by IcedCoffeeScript 1.7.1-c
(function() {
var ie;
diff --git a/lib/gpg.js b/lib/gpg.js
index <HASH>..<HASH> 100644
--- a/lib/gpg.js
+++ b/lib/gpg.js
@@ -1,8 +1,8 @@
-// Generated by IcedCoffeeScript 1.7.1-a
+// Generated by IcedCoffeeScript 1.7.1-c
(function() {
var E, GPG, colgrep, iced, ispawn, parse, __iced_k, __iced_k_noop, _gpg_cmd, _log;
- iced = require('iced-coffee-script/lib/coffee-script/iced').runtime;
+ iced = require('iced-runtime').iced;
__iced_k = __iced_k_noop = function() {};
colgrep = require('./colgrep').colgrep;
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -1,4 +1,4 @@
-// Generated by IcedCoffeeScript 1.7.1-a
+// Generated by IcedCoffeeScript 1.7.1-c
(function() {
var BaseKey, BucketDict, Element, Ignored, Index, Key, Line, Parser, Subkey, Warnings, list_fingerprints, parse, parse_int, pgpu, uniquify, util,
__hasProp = {}.hasOwnProperty,
diff --git a/lib/keyring.js b/lib/keyring.js
index <HASH>..<HASH> 100644
--- a/lib/keyring.js
+++ b/lib/keyring.js
@@ -1,10 +1,10 @@
-// Generated by IcedCoffeeScript 1.7.1-a
+// Generated by IcedCoffeeScript 1.7.1-c
(function() {
var AltKeyRing, AltKeyRingBase, BaseKeyRing, E, GPG, Globals, GpgKey, Log, MasterKeyRing, Parser, QuarantinedKeyRing, RingFileBundle, TmpKeyRing, TmpKeyRingBase, TmpOneShotKeyRing, TmpPrimaryKeyRing, a_json_parse, athrow, base64u, chain, colgrep, fingerprint_to_key_id_64, fpeq, fs, globals, gpg, iced, list_fingerprints, log, make_esc, master_ring, mkdir_p, os, path, pgp_utils, prng, reset_master_ring, states, strip, userid, util, __iced_k, __iced_k_noop, _globals, _ref, _ref1, _ref2, _ref3,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
- iced = require('iced-coffee-script/lib/coffee-script/iced').runtime;
+ iced = require('iced-runtime').iced;
__iced_k = __iced_k_noop = function() {};
_ref = require('./gpg'), GPG = _ref.GPG, gpg = _ref.gpg;
diff --git a/lib/main.js b/lib/main.js
index <HASH>..<HASH> 100644
--- a/lib/main.js
+++ b/lib/main.js
@@ -1,4 +1,4 @@
-// Generated by IcedCoffeeScript 1.7.1-a
+// Generated by IcedCoffeeScript 1.7.1-c
(function() {
var k, m, modules, v, _i, _len;
diff --git a/lib/parse.js b/lib/parse.js
index <HASH>..<HASH> 100644
--- a/lib/parse.js
+++ b/lib/parse.js
@@ -1,8 +1,8 @@
-// Generated by IcedCoffeeScript 1.7.1-a
+// Generated by IcedCoffeeScript 1.7.1-c
(function() {
var E, GPG, Message, Packet, Parser, iced, parse, strip, util, __iced_k, __iced_k_noop;
- iced = require('iced-coffee-script/lib/coffee-script/iced').runtime;
+ iced = require('iced-runtime').iced;
__iced_k = __iced_k_noop = function() {};
E = require('./err').E; | recompile with new ICS | keybase_gpg-wrapper | train |
54e96edb2ff277c1db25885840b91ae051962bf4 | diff --git a/$dom.dev.js b/$dom.dev.js
index <HASH>..<HASH> 100644
--- a/$dom.dev.js
+++ b/$dom.dev.js
@@ -7,11 +7,12 @@
* Licensed under the MIT License
* http://github.com/julienw/dollardom
*/
-; // empty statement to make uglify remove the following comments
-/*jshint boss: true, bitwise: true, curly: true, newcap: true, noarg: true, nonew: true */
-/* future jshint options : nomen: true */
-/* undef options seems buggy */
(function (window)
+/* options for jshint are here because uglifyjs needs a real piece of code between the comments
+ * it keeps and the comments it removes */
+/*jshint boss: true, bitwise: true, curly: true, newcap: true, noarg: true, nonew: true, latedef : true */
+/* future jshint options : nomen: true */
+/* undef options seems buggy, we use latedef */
{
var
/* these references exist to reduce size in minifiers */ | changes in jshint options and in the comment placement to pelase uglifyjs | julienw_dollardom | train |
ce0f16319271ea0ba9b96f9ff7c98383a3c3418d | diff --git a/web/src/main/java/uk/ac/ebi/atlas/commands/BaselineBioentityCountsService.java b/web/src/main/java/uk/ac/ebi/atlas/commands/BaselineBioentityCountsService.java
index <HASH>..<HASH> 100644
--- a/web/src/main/java/uk/ac/ebi/atlas/commands/BaselineBioentityCountsService.java
+++ b/web/src/main/java/uk/ac/ebi/atlas/commands/BaselineBioentityCountsService.java
@@ -57,6 +57,8 @@ public class BaselineBioentityCountsService {
static {
LIMITED_BY_EXPERIMENTS.put("E-MTAB-513", new BaselineExperimentResult("E-MTAB-513", "Illumina Body Map", "Homo sapiens"));
LIMITED_BY_EXPERIMENTS.put("E-MTAB-599", new BaselineExperimentResult("E-MTAB-599", "Six tissues", "Mus musculus"));
+ LIMITED_BY_EXPERIMENTS.put("E-MTAB-599", new BaselineExperimentResult("E-MTAB-2037", "Seven tissues", "Oryza sativa Japonica Group"));
+ LIMITED_BY_EXPERIMENTS.put("E-MTAB-599", new BaselineExperimentResult("E-MTAB-2039", "Nine tissues", "Oryza sativa Japonica Group"));
} | Allowed the two new rice experiments to be searchable | ebi-gene-expression-group_atlas | train |
5b89ff626d3b4c3ff5d0bd021dd9c35ee1d74bfb | diff --git a/mod/forum/locallib.php b/mod/forum/locallib.php
index <HASH>..<HASH> 100644
--- a/mod/forum/locallib.php
+++ b/mod/forum/locallib.php
@@ -95,6 +95,12 @@ class forum_portfolio_caller extends portfolio_module_caller_base {
$fs = get_file_storage();
if ($this->post) {
if ($this->attachment) {
+ // Make sure the requested file belongs to this post.
+ $file = $fs->get_file_by_id($this->attachment);
+ if ($file->get_contextid() != $this->modcontext->id
+ || $file->get_itemid() != $this->post->id) {
+ throw new portfolio_caller_exception('filenotfound');
+ }
$this->set_file_and_format_data($this->attachment);
} else {
$attach = $fs->get_area_files($this->modcontext->id, 'mod_forum', 'attachment', $this->post->id, 'timemodified', false); | MDL-<I> mod_forum: Limit portfolio to files belonging to the post | moodle_moodle | train |
75ebca24678563b2d018ce0423b2edc5968cb180 | diff --git a/odl/operator/operator.py b/odl/operator/operator.py
index <HASH>..<HASH> 100644
--- a/odl/operator/operator.py
+++ b/odl/operator/operator.py
@@ -1351,7 +1351,11 @@ class OperatorComp(Operator):
if self.is_linear:
return self
else:
- left_deriv = self.left.derivative(self.right(x))
+ if self.left.is_linear:
+ left_deriv = self.left
+ else:
+ left_deriv = self.left.derivative(self.right(x))
+
right_deriv = self.right.derivative(x)
return OperatorComp(left_deriv, right_deriv, | ENH: Minor optimization of OperatorComp.derivative | odlgroup_odl | train |
b82a14e0175150ac9ea392de5298e5355340925e | diff --git a/cli/main.go b/cli/main.go
index <HASH>..<HASH> 100644
--- a/cli/main.go
+++ b/cli/main.go
@@ -61,6 +61,10 @@ func main() {
Name: `local-first`,
Usage: `Attempt to lookup files locally before evaluating mounts.`,
},
+ cli.StringFlag{
+ Name: `verify-file`,
+ Usage: `Specifies a filename to verify the existence of (relative to the server root).`,
+ },
}
app.Before = func(c *cli.Context) error {
@@ -85,6 +89,7 @@ func main() {
server.Port = c.Int(`port`)
server.RoutePrefix = c.String(`route-prefix`)
server.TryLocalFirst = c.Bool(`local-first`)
+ server.VerifyFile = c.String(`verify-file`)
if v := c.StringSlice(`template-pattern`); len(v) > 0 {
server.TemplatePatterns = v
diff --git a/util/util.go b/util/util.go
index <HASH>..<HASH> 100644
--- a/util/util.go
+++ b/util/util.go
@@ -9,7 +9,7 @@ import (
const ApplicationName = `diecast`
const ApplicationSummary = `a dynamic site generator that consumes REST services and renders static HTML output in realtime`
-const ApplicationVersion = `1.2.1`
+const ApplicationVersion = `1.2.2`
var StartedAt = time.Now()
var SiSuffixes = []string{`bytes`, `KB`, `MB`, `GB`, `TB`, `PB`, `EB`, `YB`} | Made verify file default off with CLI usage | ghetzel_diecast | train |
62dd60a9f45a10c8b242274c2bf66de60fb941b9 | diff --git a/prov-n/src/main/java/org/openprovenance/prov/notation/BeanTreeConstructor.java b/prov-n/src/main/java/org/openprovenance/prov/notation/BeanTreeConstructor.java
index <HASH>..<HASH> 100644
--- a/prov-n/src/main/java/org/openprovenance/prov/notation/BeanTreeConstructor.java
+++ b/prov-n/src/main/java/org/openprovenance/prov/notation/BeanTreeConstructor.java
@@ -62,15 +62,24 @@ public class BeanTreeConstructor implements BeanConstructor{
}
return attrs;
}
+ public List<Object> convertLocationAttributes(List<Object> lAttrs) {
+ List<Object> attrs=new LinkedList<Object>();
+ for (Object a: lAttrs) {
+ attrs.add(c.convertAttribute("prov:location",a));
+ }
+ return attrs;
+ }
- public Object convertEntity(Object id, List<Object> tAttrs, List<Object> lAttrs, List<Object> otherAttrs) {
+ public Object convertEntity(Object id, List<Object> tAttrs, List<Object> lAttrs, List<Object> locAttrs, List<Object> otherAttrs) {
List<?> tAttrs2=convertTypeAttributes(tAttrs);
List<?> lAttrs2=convertLabelAttributes(lAttrs);
+ List<?> locAttrs2=convertLocationAttributes(locAttrs);
List<Object> attrs=new LinkedList<Object>();
- attrs.addAll(lAttrs2);
attrs.addAll(tAttrs2);
+ attrs.addAll(lAttrs2);
+ attrs.addAll(locAttrs2);
attrs.addAll(otherAttrs);
return c.convertEntity(id,
diff --git a/prov-xml/src/main/java/org/openprovenance/prov/xml/BeanConstructor.java b/prov-xml/src/main/java/org/openprovenance/prov/xml/BeanConstructor.java
index <HASH>..<HASH> 100644
--- a/prov-xml/src/main/java/org/openprovenance/prov/xml/BeanConstructor.java
+++ b/prov-xml/src/main/java/org/openprovenance/prov/xml/BeanConstructor.java
@@ -8,7 +8,7 @@ import javax.xml.namespace.QName;
public interface BeanConstructor {
public Object convert(QName q);
- public Object convertEntity(Object id, List<Object> tAttrs, List<Object> lAttr, List<Object> otherAttrs);
+ public Object convertEntity(Object id, List<Object> tAttrs, List<Object> lAttr, List<Object> locAttr, List<Object> otherAttrs);
public Object convertAgent(Object id, List<Object> tAttrs, List<Object> lAttr, List<Object> otherAttrs);
public Object convertActivity(Object id, List<Object> tAttrs, List<Object> lAttr, List<Object> otherAttrs, Object startTime, Object endTime);
diff --git a/prov-xml/src/main/java/org/openprovenance/prov/xml/BeanTraversal.java b/prov-xml/src/main/java/org/openprovenance/prov/xml/BeanTraversal.java
index <HASH>..<HASH> 100644
--- a/prov-xml/src/main/java/org/openprovenance/prov/xml/BeanTraversal.java
+++ b/prov-xml/src/main/java/org/openprovenance/prov/xml/BeanTraversal.java
@@ -109,6 +109,14 @@ public class BeanTraversal {
}
return res;
}
+ public List<Object> convertLocationAttribute(HasLocation e) {
+ List<Object> locations = e.getLocation();
+ List<Object> res = new LinkedList<Object>();
+ for (Object location : locations) {
+ res.add(convertTypedLiteral(location));
+ }
+ return res;
+ }
public List<Object> convertAttributes(HasExtensibility e) {
List<Object> attrs = new LinkedList<Object>();
@@ -166,8 +174,9 @@ public class BeanTraversal {
List<Object> tAttrs = convertTypeAttributes(e);
List<Object> otherAttrs = convertAttributes(e);
List<Object> lAttrs = convertLabelAttribute(e);
+ List<Object> locAttrs = convertLocationAttribute(e);
- return c.convertEntity(c.convert(e.getId()), tAttrs, lAttrs, otherAttrs);
+ return c.convertEntity(c.convert(e.getId()), tAttrs, lAttrs, locAttrs, otherAttrs);
}
public Object convert(Activity e) { | Support for Attribute in prov-n and round trip testing | lucmoreau_ProvToolbox | train |
b6b6a8a583d9a40fa46ddb552b501f287b2d33ae | diff --git a/lib/aws/api/pagination_translator.rb b/lib/aws/api/pagination_translator.rb
index <HASH>..<HASH> 100644
--- a/lib/aws/api/pagination_translator.rb
+++ b/lib/aws/api/pagination_translator.rb
@@ -55,7 +55,7 @@ module Aws
class << self
def translate(api)
- filename = api.metadata['service_class_name'].downcase
+ filename = api.metadata['endpoint_prefix']
filename += "-#{api.version}.paginators.json"
path = File.join(Aws::GEM_ROOT, 'apis', 'source',filename)
if File.exists?(path) | Fixed a bug in the Api translation of pagination configuration.
Now using the correct filename prefix (the endpoint prefix)
to locate the paging config. | aws_aws-sdk-ruby | train |
967af6f048b66a0b478f69cee86fd031acd833b6 | diff --git a/peru/resources/plugins/curl/curl_plugin.py b/peru/resources/plugins/curl/curl_plugin.py
index <HASH>..<HASH> 100755
--- a/peru/resources/plugins/curl/curl_plugin.py
+++ b/peru/resources/plugins/curl/curl_plugin.py
@@ -7,6 +7,7 @@ import re
import stat
import sys
import tarfile
+from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit
import urllib.request
import zipfile
@@ -157,13 +158,18 @@ def main():
url = os.environ['PERU_MODULE_URL']
sha1 = os.environ['PERU_MODULE_SHA1']
command = os.environ['PERU_PLUGIN_COMMAND']
- if command == 'sync':
- plugin_sync(url, sha1)
- elif command == 'reup':
- plugin_reup(url, sha1)
- else:
- raise RuntimeError('unknown command: ' + repr(command))
+ try:
+ if command == 'sync':
+ plugin_sync(url, sha1)
+ elif command == 'reup':
+ plugin_reup(url, sha1)
+ else:
+ raise RuntimeError('unknown command: ' + repr(command))
+ except (HTTPError, URLError) as e:
+ print("Error fetching", url)
+ print(e)
+ return 1
if __name__ == '__main__':
- main()
+ sys.exit(main()) | catch HTTPError and URLError in the curl plugin | buildinspace_peru | train |
e086375ec8c20881af50b13e7ba72effaed0280f | diff --git a/salt/modules/vagrant.py b/salt/modules/vagrant.py
index <HASH>..<HASH> 100644
--- a/salt/modules/vagrant.py
+++ b/salt/modules/vagrant.py
@@ -361,10 +361,12 @@ def destroy(name):
machine = vm_['machine']
cmd = 'vagrant destroy -f {}'.format(machine)
- ret = __salt__['cmd.retcode'](cmd,
+ try:
+ ret = __salt__['cmd.retcode'](cmd,
runas=vm_.get('runas'),
cwd=vm_.get('cwd'))
- _erase_cache(name)
+ finally:
+ _erase_cache(name)
return ret == 0 | clean up cache even if other steps fail | saltstack_salt | train |
7feea31d4e479ffe785f4ca06402c29f558302c0 | diff --git a/src/dhis2.angular.services.js b/src/dhis2.angular.services.js
index <HASH>..<HASH> 100644
--- a/src/dhis2.angular.services.js
+++ b/src/dhis2.angular.services.js
@@ -1825,7 +1825,7 @@ var d2Services = angular.module('d2Services', ['ngResource'])
var orgUnitUid = selectedEnrollment ? selectedEnrollment.orgUnit : executingEvent.orgUnit;
var orgUnitCode = '';
- return OrgUnitFactory.getFromStoreOrServer( orgUnitUid ).then(function (response) {
+ return OrgUnitFactory.getOrgUnit( orgUnitUid ).then(function (response) {
orgUnitCode = response.code;
variables = pushVariable(variables, 'orgunit_code', orgUnitCode, null, 'TEXT', orgUnitCode ? true : false, 'V', '', false);
return variables;
@@ -3290,6 +3290,9 @@ var d2Services = angular.module('d2Services', ['ngResource'])
def.resolve( response ? response : null );
});
}
+ else {
+ def.resolve(null);
+ }
return def.promise;
},
getOrgUnitReportDateRange: function(orgUnit) { | Changed method to get orgunit details from PR execution | dhis2_d2-tracker | train |
fa4977003ab27fb29edb1ee85be0b1d225fe0f22 | diff --git a/theanets/feedforward.py b/theanets/feedforward.py
index <HASH>..<HASH> 100644
--- a/theanets/feedforward.py
+++ b/theanets/feedforward.py
@@ -147,12 +147,8 @@ class Network:
self.weights = []
self.biases = []
self.updates = {}
-
- self.rng = kwargs.get('rng') or RandomStreams()
-
- if 'decode_from' not in kwargs:
- kwargs['decode_from'] = 1
self.kwargs = kwargs
+ self.rng = kwargs.get('rng') or RandomStreams()
self.hidden_activation = kwargs.get(
'hidden_activation', kwargs.get('activation', 'sigmoid')) | Simplify constructor a bit. | lmjohns3_theanets | train |
12be1d3aed26bca1b74bff07086fe4e0e932e843 | diff --git a/seqtools/format/sam/bam/__init__.py b/seqtools/format/sam/bam/__init__.py
index <HASH>..<HASH> 100644
--- a/seqtools/format/sam/bam/__init__.py
+++ b/seqtools/format/sam/bam/__init__.py
@@ -106,6 +106,23 @@ class BAM(samtools.format.sam.SAM):
"""
return [self._options.blockStart,self._options.innerStart]
+ def __str__(self):
+ return self.get_sam_line
+
+ def get_sam_line(self):
+ return "\t".join([str(x) for x in
+ [qname,
+ flag,
+ rname,
+ pos,
+ mapq,
+ cigar_string,
+ rnext,
+ pnext,
+ tlen,
+ seq,
+ qual,
+ auxillary_string]])
### The getters for all the fields
@property
def qname(self): return self.bentries.qname | facilitate outputting the sam line from the bam directly | jason-weirather_py-seq-tools | train |
b368651acc5d50484e9c2ece8caaa466c179305c | diff --git a/classes/ezperfloggerstatsdlogger.php b/classes/ezperfloggerstatsdlogger.php
index <HASH>..<HASH> 100644
--- a/classes/ezperfloggerstatsdlogger.php
+++ b/classes/ezperfloggerstatsdlogger.php
@@ -64,7 +64,7 @@ class eZPerfLoggerStatsdLogger implements eZPerfLoggerLogger
{
if ( strlen( $token) && $token[0] == '$' )
{
- $token = eZPerfLogger::getModuleResultData( substr( $token, 1 ) );
+ $token = str_replace( '.', '_', eZPerfLogger::getModuleResultData( substr( $token, 1 ) ) );
}
}
$string = implode( '.', $tokens ); | A bit of escaping stasd key names | gggeek_ezperformancelogger | train |
2add0af2b5273f0978580386f1b66ff2a6fb53e1 | diff --git a/crud/Action.php b/crud/Action.php
index <HASH>..<HASH> 100644
--- a/crud/Action.php
+++ b/crud/Action.php
@@ -518,7 +518,6 @@ class Action extends \yii\rest\Action
'query' => $relation,
'pagination' => [
'pageParam' => "$field-page",
- 'pageSize' => 10,
],
'sort' => ['sortParam' => "$field-sort"],
]),
diff --git a/db/ActiveSearchTrait.php b/db/ActiveSearchTrait.php
index <HASH>..<HASH> 100644
--- a/db/ActiveSearchTrait.php
+++ b/db/ActiveSearchTrait.php
@@ -17,11 +17,23 @@ trait ActiveSearchTrait
use QuickSearchTrait;
/**
- * Creates data provider instance with search query applied
+ * Creates data provider instance with search query applied. You can pass {@link Pagination} configuration in
+ * $pagination param. If you want set it up globally then you should use DI like this:
+ * ```
+ * 'bootstrap' => [
+ * function () {
+ * \Yii::$container->set(\yii\data\Pagination::className(), [
+ * 'pageSizeLimit' => [-1, 0x7FFFFFFF],
+ * 'defaultPageSize' => 50,
+ * ]);
+ * },
+ * ],
+ * ```
*
* @param \yii\db\ActiveQuery $query
* @param Sort|array $sort
* @param Pagination|array $pagination
+ *
* @return ActiveDataProvider
*/
public function search(\yii\db\ActiveQuery $query = null, $sort = [], $pagination = [])
@@ -34,12 +46,6 @@ trait ActiveSearchTrait
if (is_array($sort)) {
$sort = \yii\helpers\ArrayHelper::merge($this->getSortConfig($query, $this->attributes()), $sort);
}
- if (is_array($pagination)) {
- $pagination = array_merge([
- 'pageSizeLimit' => [-1, 0x7FFFFFFF],
- 'defaultPageSize' => 25,
- ], $pagination);
- }
$dataProvider = new ActiveDataProvider([
'query' => $query,
diff --git a/defaultViews/index.php b/defaultViews/index.php
index <HASH>..<HASH> 100644
--- a/defaultViews/index.php
+++ b/defaultViews/index.php
@@ -109,6 +109,8 @@ echo GridView::widget(array_merge([
Pjax::end();
if ($searchModes & IndexAction::SEARCH_COLUMN_HEADERS) {
+ //@todo implement filtering on keyup after timeout.
+ //@todo move this to separate js file and make library from it.
$script = <<<JavaScript
var enterPressed = false;
$(document)
@@ -135,6 +137,11 @@ $(document)
.on('change', '#{$gridId}-filters input.select2, #{$gridId}-filters select.select2', function (event) {
$('#{$gridId}').yiiGridView('applyFilter');
return false;
+ })
+ .on( "autocompleteselect", '#{$gridId}-filters input.ui-autocomplete-input', function( event, ui ) {
+ $(this).val(ui.item.value);
+ $('#{$gridId}').yiiGridView('applyFilter');
+ return false;
});
JavaScript;
$this->registerJs($script); | remove pagination configuration - this should be in app config, added exapmple how to set it up in app; improved filtering grid javascript | netis-pl_yii2-crud | train |
54cad3c4e795d159711c003f3837d0f00a867a3e | diff --git a/lib/basepanel.py b/lib/basepanel.py
index <HASH>..<HASH> 100644
--- a/lib/basepanel.py
+++ b/lib/basepanel.py
@@ -362,10 +362,9 @@ class BasePanel(wx.Panel):
dtick = abs(ticks[1] - ticks[0])
except:
pass
- # print ' tick ' , type, dtick, ' -> ',
- if dtick > 99999:
- fmt, v = ('%1.6e', '%1.7g')
- elif dtick > 0.99:
+ if dtick > 29999:
+ fmt, v = ('%1.5g', '%1.6g')
+ elif dtick > 1.99:
fmt, v = ('%1.0f', '%1.2f')
elif dtick > 0.099:
fmt, v = ('%1.1f', '%1.3f') | changed default text formatting for large numbers to '.g' formatting | newville_wxmplot | train |
2bd5f11531db2a02677295c59140e900a0fdd4a4 | diff --git a/persister/throttle_test.go b/persister/throttle_test.go
index <HASH>..<HASH> 100644
--- a/persister/throttle_test.go
+++ b/persister/throttle_test.go
@@ -1,6 +1,7 @@
package persister
import (
+ "fmt"
"testing"
"time"
@@ -8,8 +9,7 @@ import (
"github.com/stretchr/testify/assert"
)
-func TestThrottleChan(t *testing.T) {
- perSecond := 100
+func doTestThrottleChan(t *testing.T, perSecond int) {
timestamp := time.Now().Unix()
chIn := make(chan *points.Points)
@@ -34,6 +34,14 @@ LOOP:
max := float64(perSecond) * 1.05
min := float64(perSecond) * 0.95
- assert.True(t, float64(bw) >= min)
- assert.True(t, float64(bw) <= max)
+ assert.True(t, float64(bw) >= min, fmt.Sprintf("perSecond: %d, bw: %d", perSecond, bw))
+ assert.True(t, float64(bw) <= max, fmt.Sprintf("perSecond: %d, bw: %d", perSecond, bw))
+}
+
+func TestThrottleChan(t *testing.T) {
+ perSecondTable := []int{1, 10, 100, 1000, 10000, 100000, 200000, 531234}
+
+ for _, perSecond := range perSecondTable {
+ doTestThrottleChan(t, perSecond)
+ }
}
diff --git a/persister/whisper.go b/persister/whisper.go
index <HASH>..<HASH> 100644
--- a/persister/whisper.go
+++ b/persister/whisper.go
@@ -6,6 +6,7 @@ import (
"os"
"path/filepath"
"strings"
+ "sync"
"sync/atomic"
"time"
@@ -226,13 +227,31 @@ LOOP:
func throttleChan(in chan *points.Points, ratePerSec int, exit chan bool) chan *points.Points {
out := make(chan *points.Points, cap(in))
- step := time.Duration(1e9/ratePerSec) * time.Nanosecond
+ delimeter := ratePerSec
+ chunk := 1
- go func() {
+ if ratePerSec > 1000 {
+ minRemainder := ratePerSec
+
+ for i := 100; i < 1000; i++ {
+ if ratePerSec%i < minRemainder {
+ delimeter = i
+ minRemainder = ratePerSec % delimeter
+ }
+ }
+
+ chunk = ratePerSec / delimeter
+ }
+
+ step := time.Duration(1e9/delimeter) * time.Nanosecond
+
+ var onceClose sync.Once
+
+ throttleWorker := func() {
var p *points.Points
var ok bool
- defer close(out)
+ defer onceClose.Do(func() { close(out) })
// start flight
throttleTicker := time.NewTicker(step)
@@ -242,20 +261,24 @@ func throttleChan(in chan *points.Points, ratePerSec int, exit chan bool) chan *
for {
select {
case <-throttleTicker.C:
- select {
- case p, ok = <-in:
- if !ok {
+ for i := 0; i < chunk; i++ {
+ select {
+ case p, ok = <-in:
+ if !ok {
+ break LOOP
+ }
+ case <-exit:
break LOOP
}
- case <-exit:
- break LOOP
+ out <- p
}
- out <- p
case <-exit:
break LOOP
}
}
- }()
+ }
+
+ go throttleWorker()
return out
} | #<I> Throttling performance | lomik_go-carbon | train |
38f49c3768e0c92a96d60391bafc29f2728298ef | diff --git a/internal/uidriver/js/ui.go b/internal/uidriver/js/ui.go
index <HASH>..<HASH> 100644
--- a/internal/uidriver/js/ui.go
+++ b/internal/uidriver/js/ui.go
@@ -77,8 +77,7 @@ func (u *UserInterface) IsFullscreen() bool {
}
func (u *UserInterface) IsForeground() bool {
- // TODO: implement this
- return true
+ return u.isForeground()
}
func (u *UserInterface) SetRunnableInBackground(runnableInBackground bool) {
@@ -146,14 +145,17 @@ func (u *UserInterface) suspended() bool {
if u.runnableInBackground {
return false
}
+ return !u.isForeground()
+}
+func (u *UserInterface) isForeground() bool {
if !document.Call("hasFocus").Bool() {
- return true
+ return false
}
if document.Get("hidden").Bool() {
- return true
+ return false
}
- return false
+ return true
}
func (u *UserInterface) update() error { | uidriver/js: Implement IsForeground
Updates #<I> | hajimehoshi_ebiten | train |
50955793b0183f9de69bd78e2ec251cf20aab121 | diff --git a/credentials/credentials_test.go b/credentials/credentials_test.go
index <HASH>..<HASH> 100644
--- a/credentials/credentials_test.go
+++ b/credentials/credentials_test.go
@@ -155,6 +155,7 @@ func serverHandle(t *testing.T, hs serverHandshake, done chan AuthInfo, lis net.
serverAuthInfo, err := hs(serverRawConn)
if err != nil {
t.Errorf("Server failed while handshake. Error: %v", err)
+ serverRawConn.Close()
close(done)
return
} | Debugging tests for AuthInfo (#<I>)
* debug
* fix | grpc_grpc-go | train |
17e3b43879d516437ada71cf9c0deac6a382ed9a | diff --git a/commands.go b/commands.go
index <HASH>..<HASH> 100644
--- a/commands.go
+++ b/commands.go
@@ -96,6 +96,10 @@ type Cmdable interface {
Exists(ctx context.Context, keys ...string) *IntCmd
Expire(ctx context.Context, key string, expiration time.Duration) *BoolCmd
ExpireAt(ctx context.Context, key string, tm time.Time) *BoolCmd
+ ExpireNX(ctx context.Context, key string, expiration time.Duration) *BoolCmd
+ ExpireXX(ctx context.Context, key string, expiration time.Duration) *BoolCmd
+ ExpireGT(ctx context.Context, key string, expiration time.Duration) *BoolCmd
+ ExpireLT(ctx context.Context, key string, expiration time.Duration) *BoolCmd
Keys(ctx context.Context, pattern string) *StringSliceCmd
Migrate(ctx context.Context, host, port, key string, db int, timeout time.Duration) *StatusCmd
Move(ctx context.Context, key string, db int) *BoolCmd | fix: add missing Expire methods to Cmdable
This is a followup to <URL> | go-redis_redis | train |
8c4910d219cad49637fbb3d9253a890d29068e91 | diff --git a/imgaug/augmenters/meta.py b/imgaug/augmenters/meta.py
index <HASH>..<HASH> 100644
--- a/imgaug/augmenters/meta.py
+++ b/imgaug/augmenters/meta.py
@@ -1363,6 +1363,9 @@ class Augmenter(object): # pylint: disable=locally-disabled, unused-variable, l
return result[0]
return tuple(result)
+ def __call__(self, *args, **kwargs):
+ return self.augment(*args, **kwargs)
+
def pool(self, processes=None, maxtasksperchild=None, seed=None):
"""
Create a pool used for multicore augmentation from this augmenter.
diff --git a/test/augmenters/test_meta.py b/test/augmenters/test_meta.py
index <HASH>..<HASH> 100644
--- a/test/augmenters/test_meta.py
+++ b/test/augmenters/test_meta.py
@@ -47,6 +47,7 @@ def main():
test_Augmenter_augment()
test_Augmenter_augment_py36_or_higher()
test_Augmenter_augment_py35_or_lower()
+ test_Augmenter___call__()
test_Augmenter_pool()
test_Augmenter_find()
test_Augmenter_remove()
@@ -2651,6 +2652,14 @@ def test_Augmenter_augment_py35_or_lower():
assert got_exception
+def test_Augmenter___call__():
+ image = ia.quokka(size=(128, 128), extract="square")
+ heatmaps = ia.quokka_heatmap(size=(128, 128), extract="square")
+ images_aug, heatmaps_aug = iaa.Noop()(images=[image], heatmaps=[heatmaps])
+ assert np.array_equal(images_aug[0], image)
+ assert np.allclose(heatmaps_aug[0].arr_0to1, heatmaps.arr_0to1)
+
+
def test_Augmenter_pool():
augseq = iaa.Noop() | Add __call__ method to Augmenter | aleju_imgaug | train |
464b4de715e0d7af2e8dd5eec8a74a3e569c95f5 | diff --git a/lib/ignorance/git_ignore_file.rb b/lib/ignorance/git_ignore_file.rb
index <HASH>..<HASH> 100644
--- a/lib/ignorance/git_ignore_file.rb
+++ b/lib/ignorance/git_ignore_file.rb
@@ -9,6 +9,20 @@ module Ignorance
@repo_dir = '.git'
end
+ private
+
+ def ignored
+ (file_contents + user_ignore_file_contents).reject{ |t| t.match /^\#/ }.map(&:chomp)
+ end
+
+ def user_ignore_file_contents
+ File.exists?(user_ignore_file) ? File.readlines(user_ignore_file) : []
+ end
+
+ def user_ignore_file
+ @user_ignore_file ||= `git config --global --get core.excludesfile`.chomp
+ end
+
end
end
diff --git a/spec/lib/ignorance/git_ignore_file_spec.rb b/spec/lib/ignorance/git_ignore_file_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/ignorance/git_ignore_file_spec.rb
+++ b/spec/lib/ignorance/git_ignore_file_spec.rb
@@ -9,5 +9,21 @@ module Ignorance
it_should_behave_like "an ignore file"
+ context "when the user's gitignore file includes the token" do
+ let(:token) { "foofile.md" }
+ let(:user_ignore_file) { '~/.gitignore' }
+ before do
+ ignorefile_write %w[other stuff here].join("\n")
+ File.open(user_ignore_file, 'w') do |fh|
+ fh.write "#{token}\n"
+ end
+ subject.stub(:user_ignore_file).and_return(user_ignore_file)
+ end
+
+ specify "then the file is ignored" do
+ File.read('~/.gitignore').should match /#{token}/
+ subject.ignored?(token).should be_true
+ end
+ end
end
end | Git should also not act if token to ignore is in user's core.excludesfile | joelhelbling_ignorance | train |
9d8f0f2cd2756fa643e92406e3744c944e9acdbe | diff --git a/lib/sunspot/field.rb b/lib/sunspot/field.rb
index <HASH>..<HASH> 100644
--- a/lib/sunspot/field.rb
+++ b/lib/sunspot/field.rb
@@ -58,6 +58,10 @@ module Sunspot
fields_hash[clazz.object_id] ||= []
end
+ def unregister_all!
+ fields_hash.clear
+ end
+
private
def fields_hash
diff --git a/spec/indexer_spec.rb b/spec/indexer_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/indexer_spec.rb
+++ b/spec/indexer_spec.rb
@@ -4,6 +4,7 @@ describe Sunspot::Indexer do
before :each do
Solr::Connection.stub!(:new).and_return connection
+ Sunspot::Field.unregister_all!
Post.is_searchable do
keywords :title, :body
string :title | Added unregister_all! to Field
Added convenience method to Field to unregister all configured fields.
Probably only useful in testing. | sunspot_sunspot | train |
def8ec5ee9c02a035d082b6162de709c807ba6c3 | diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/slot/TaskSlotUtils.java b/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/slot/TaskSlotUtils.java
index <HASH>..<HASH> 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/slot/TaskSlotUtils.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/slot/TaskSlotUtils.java
@@ -18,6 +18,7 @@
package org.apache.flink.runtime.taskexecutor.slot;
+import org.apache.flink.api.common.resources.CPUResource;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.MemorySize;
import org.apache.flink.runtime.clusterframework.types.AllocationID;
@@ -38,7 +39,7 @@ public enum TaskSlotUtils {
private static final ResourceProfile DEFAULT_RESOURCE_PROFILE =
new ResourceProfile(
- Double.MAX_VALUE,
+ new CPUResource(Double.MAX_VALUE),
MemorySize.MAX_VALUE,
MemorySize.MAX_VALUE,
new MemorySize(10 * MemoryManager.MIN_PAGE_SIZE), | [hotfix][tests] Fix ResourceProfile instantiation | apache_flink | train |
3af99b860793c46aaa563df74f4c33d5602f5ec4 | diff --git a/bundles/org.eclipse.orion.client.editor/web/orion/editor/contentAssist.js b/bundles/org.eclipse.orion.client.editor/web/orion/editor/contentAssist.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.editor/web/orion/editor/contentAssist.js
+++ b/bundles/org.eclipse.orion.client.editor/web/orion/editor/contentAssist.js
@@ -1,6 +1,6 @@
/*******************************************************************************
* @license
- * Copyright (c) 2011, 2014 IBM Corporation and others.
+ * Copyright (c) 2011, 2016 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution
@@ -279,7 +279,7 @@ define("orion/editor/contentAssist", [ //$NON-NLS-0$
var selectionStart = Math.min(sel.start, sel.end);
this._initialCaretOffset = Math.min(offset, selectionStart);
this._computedProposals = null;
-
+ delete this._autoApply;
this._computeProposals(this._initialCaretOffset).then(function(proposals) {
if (this.isActive()) {
var flatProposalArray = this._flatten(proposals);
@@ -287,7 +287,8 @@ define("orion/editor/contentAssist", [ //$NON-NLS-0$
if (flatProposalArray && Array.isArray(flatProposalArray) && (0 < flatProposalArray.length)) {
this._computedProposals = proposals;
}
- this.dispatchEvent({type: "ProposalsComputed", data: {proposals: flatProposalArray}, autoApply: !this._autoTriggered}); //$NON-NLS-0$
+ var autoApply = typeof this._autoApply === 'boolean' ? this._autoApply : !this._autoTriggerEnabled;
+ this.dispatchEvent({type: "ProposalsComputed", data: {proposals: flatProposalArray}, autoApply: autoApply}); //$NON-NLS-0$
if (this._computedProposals && this._filterText) {
// force filtering here because user entered text after
// computeProposals() was called but before the plugins
@@ -359,6 +360,9 @@ define("orion/editor/contentAssist", [ //$NON-NLS-0$
var func;
var promise;
var params;
+ if(typeof providerInfo.autoApply === 'boolean') {
+ _self._autoApply = providerInfo.autoApply;
+ }
if (computePrefixFunc) {
ecProvider = _self.editorContextProvider;
editorContext = ecProvider.getEditorContext();
diff --git a/bundles/org.eclipse.orion.client.javascript/web/javascript/plugins/javascriptPlugin.js b/bundles/org.eclipse.orion.client.javascript/web/javascript/plugins/javascriptPlugin.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.javascript/web/javascript/plugins/javascriptPlugin.js
+++ b/bundles/org.eclipse.orion.client.javascript/web/javascript/plugins/javascriptPlugin.js
@@ -473,7 +473,8 @@ define([
name: 'ternContentAssist', //$NON-NLS-1$
id: "orion.edit.contentassist.javascript.tern", //$NON-NLS-1$
charTriggers: "[.]", //$NON-NLS-1$
- excludedStyles: "(string.*)" //$NON-NLS-1$
+ excludedStyles: "(string.*)", //$NON-NLS-1$
+ autoApply: false
});
provider.registerService("orion.edit.contentassist", //$NON-NLS-1$
diff --git a/bundles/org.eclipse.orion.client.ui/web/orion/editorView.js b/bundles/org.eclipse.orion.client.ui/web/orion/editorView.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.ui/web/orion/editorView.js
+++ b/bundles/org.eclipse.orion.client.ui/web/orion/editorView.js
@@ -392,7 +392,7 @@ define([
var id = serviceRef.getProperty("service.id").toString(); //$NON-NLS-0$
var charTriggers = serviceRef.getProperty("charTriggers"); //$NON-NLS-0$
var excludedStyles = serviceRef.getProperty("excludedStyles"); //$NON-NLS-0$
-
+ var autoApply = serviceRef.getProperty("autoApply");
if (charTriggers) {
charTriggers = new RegExp(charTriggers);
}
@@ -401,7 +401,7 @@ define([
excludedStyles = new RegExp(excludedStyles);
}
- return {provider: service, id: id, charTriggers: charTriggers, excludedStyles: excludedStyles};
+ return {provider: service, id: id, charTriggers: charTriggers, excludedStyles: excludedStyles, autoApply: autoApply};
}
return null;
}).filter(function(providerInfo) { | Bug <I> - Content assist automatically fills in the "wrong thing" (assumes a single method and pastes it in) | eclipse_orion.client | train |
f577dc0ec150587d5b090ebe5d718d7549a826a1 | diff --git a/js/oadoi-link-results.module.js b/js/oadoi-link-results.module.js
index <HASH>..<HASH> 100644
--- a/js/oadoi-link-results.module.js
+++ b/js/oadoi-link-results.module.js
@@ -3,15 +3,15 @@ angular
.component('prmSearchResultAvailabilityLineAfter', {
bindings: { parentCtrl: '<'},
template: `
- <oadoi-results ng-if="{{$ctrl.showOnResultsPage}} && !{{$ctrl.isFullView}}">
+ <oadoi-results ng-if="$ctrl.show">
<div layout="flex" ng-if="$ctrl.best_oa_link" class="layout-row" style="margin-top: 5px;">
<prm-icon icon-type="svg" svg-icon-set="action" icon-definition="ic_lock_open_24px"></prm-icon>
<a class="arrow-link-button md-primoExplore-theme md-ink-ripple" style="margin-left: 3px; margin-top: 3px;"
target="_blank" href="{{$ctrl.best_oa_link}}"><strong>Open Access</strong> available via unpaywall</a>
<prm-icon link-arrow icon-type="svg" svg-icon-set="primo-ui" icon-definition="chevron-right"></prm-icon>
</div>
- <div class="layout-row">
- <table ng-if="$ctrl.debug">
+ <div ng-if="$ctrl.debug" class="layout-row">
+ <table>
<tr><td><strong>doi</strong></td><td>{{$ctrl.doi}}</td></tr>
<tr><td><strong>is_OA</strong></td><td>{{$ctrl.is_oa}}</td>
<tr><td><strong>best_oa_link</strong></td><td>{{$ctrl.best_oa_link}}</td></tr>
@@ -20,11 +20,15 @@ angular
</oadoi-results>`,
controller:
function oadoiResultsCtrl(oadoiOptions, $scope, $element, $http) {
- // ensure that preference is set to display
+ // get data from oadoiOptions
var self = this;
- self.showOnResultsPage = oadoiOptions.showOnResultsPage;
- if(!self.showOnResultsPage){ return; }
self.debug = oadoiOptions.debug;
+ var showOnResultsPage = oadoiOptions.showOnResultsPage;
+
+ // ensure that preference is set to display
+ var onFullView = this.parentCtrl.isFullView || this.parentCtrl.isOverlayFullView;
+ self.show = showOnResultsPage && !onFullView;
+ if(!showOnResultsPage){ return; }
// get the item from the component's parent controller
var item = this.parentCtrl.result; | bulib: further protect '-results' visibility | alliance-pcsg_primo-explore-oadoi-link | train |
778163d4be346c82fea9c5b51eb162885d77e4fa | diff --git a/lib/kamerling/franchus.rb b/lib/kamerling/franchus.rb
index <HASH>..<HASH> 100644
--- a/lib/kamerling/franchus.rb
+++ b/lib/kamerling/franchus.rb
@@ -1,9 +1,10 @@
module Kamerling class Franchus
UnknownMessage = Class.new RuntimeError
- def handle string
- send "handle_#{string[0..3]}", string
+ def handle input, scribe: nil
+ message = scribe.decipher input
+ send "handle_#{message.type}", message
rescue NoMethodError
- raise UnknownMessage, string
+ raise UnknownMessage, input
end
end end
diff --git a/spec/kamerling/franchus_spec.rb b/spec/kamerling/franchus_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/kamerling/franchus_spec.rb
+++ b/spec/kamerling/franchus_spec.rb
@@ -7,9 +7,12 @@ module Kamerling describe Franchus do
end
it 'handles known messages' do
+ scribe = double decipher: -> _ { double type: 'MESS' }
franchus = Franchus.new
- def franchus.handle_MESS(msg); msg[5..-1]; end
- franchus.handle('MESS age').must_equal 'age'
+ def franchus.handle_MESS message
+ message.type
+ end
+ franchus.handle('MESSage', scribe: scribe).must_equal 'MESS'
end
end
end end | Franchus#handle: pass messages to a scribe for deciphering | chastell_kamerling | train |
ad5259a1ffa748704277743cded5d55817430b87 | diff --git a/src/runnables/runnable-model.js b/src/runnables/runnable-model.js
index <HASH>..<HASH> 100644
--- a/src/runnables/runnable-model.js
+++ b/src/runnables/runnable-model.js
@@ -53,7 +53,7 @@ export default class Runnable {
return 'failed'
} else if (this._anyChildrenProcessing) {
return 'processing'
- } else if (this._allChildrenPassed) {
+ } else if (this._allChildrenPassedOrPending) {
return 'passed'
} else {
return 'processing'
@@ -81,12 +81,16 @@ export default class Runnable {
return _.some(this._childStates, (state) => state === 'failed')
}
- @computed get _allChildrenPassed () {
- return !this._childStates.length || _.every(this._childStates, (state) => state === 'passed')
+ @computed get _allChildrenPassedOrPending () {
+ return !this._childStates.length || _.every(this._childStates, (state) => (
+ state === 'passed' || state === 'pending'
+ ))
}
@computed get _allChildrenPending () {
- return !!this._childStates.length && _.every(this._childStates, (state) => state === 'pending')
+ return !!this._childStates.length && _.every(this._childStates, (state) => (
+ state === 'pending'
+ ))
}
addAgent (agent) { | update suite state logic - show passed if all children are passed or pending | cypress-io_cypress | train |
3f24535c08a81f61924870f058b7755f341546f3 | diff --git a/test/checks/lists/only-dlitems.js b/test/checks/lists/only-dlitems.js
index <HASH>..<HASH> 100644
--- a/test/checks/lists/only-dlitems.js
+++ b/test/checks/lists/only-dlitems.js
@@ -194,6 +194,22 @@ describe('only-dlitems', function() {
);
});
+ it('should return true if the list mixed items inside a div group with a role', function() {
+ var checkArgs = checkSetup(
+ '<dl id="target"><div><dt>An item</dt><dd>A list</dd><p>Not a list</p></div></dl>'
+ );
+ assert.isTrue(
+ checks['only-dlitems'].evaluate.apply(checkContext, checkArgs)
+ );
+ });
+
+ it('should return false if there is an empty div', function() {
+ var checkArgs = checkSetup('<dl id="target"><div></div></dl>');
+ assert.isFalse(
+ checks['only-dlitems'].evaluate.apply(checkContext, checkArgs)
+ );
+ });
+
it('returns false if there are display:none elements that normally would not be allowed', function() {
var checkArgs = checkSetup(
'<dl id="target"> <dt>An item</dt> <dd>A list</dd> <h1 style="display:none">heading</h1> </dl>'
@@ -203,6 +219,13 @@ describe('only-dlitems', function() {
);
});
+ it('should return true if there is a div with text', function() {
+ var checkArgs = checkSetup('<dl id="target"><div>text</div></dl>');
+ assert.isTrue(
+ checks['only-dlitems'].evaluate.apply(checkContext, checkArgs)
+ );
+ });
+
it('returns false if there are visibility:hidden elements that normally would not be allowed', function() {
var checkArgs = checkSetup(
'<dl id="target"> <dt>An item</dt> <dd>A list</dd> <h1 style="visibility:hidden">heading</h1> </dl>'
@@ -212,6 +235,13 @@ describe('only-dlitems', function() {
);
});
+ it('should return true if there is a div with non-dd / dt elements', function() {
+ var checkArgs = checkSetup('<dl id="target"><div> <p>text</p> </div></dl>');
+ assert.isTrue(
+ checks['only-dlitems'].evaluate.apply(checkContext, checkArgs)
+ );
+ });
+
it('returns false if there are aria-hidden=true elements that normally would not be allowed', function() {
var checkArgs = checkSetup(
'<dl id="target"> <dt>An item</dt> <dd>A list</dd> <h1 aria-hidden="true">heading</h1> </dl>' | test: More div tests for only-dlitems (#<I>) | dequelabs_axe-core | train |
3c6b3aa5033cf64f966498f8f3c2937be9f8b347 | diff --git a/lib/rom/repository/struct_builder.rb b/lib/rom/repository/struct_builder.rb
index <HASH>..<HASH> 100644
--- a/lib/rom/repository/struct_builder.rb
+++ b/lib/rom/repository/struct_builder.rb
@@ -50,7 +50,7 @@ module ROM
end
def visit_attribute(attr)
- [attr.aliased? && !attr.wrapped? ? attr.alias : attr.name, attr.type]
+ [attr.aliased? && !attr.wrapped? ? attr.alias : attr.name, attr.to_read_type]
end
def build_class(name, parent, &block)
diff --git a/spec/integration/typed_structs_spec.rb b/spec/integration/typed_structs_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/integration/typed_structs_spec.rb
+++ b/spec/integration/typed_structs_spec.rb
@@ -1,31 +1,64 @@
RSpec.describe 'ROM repository with typed structs' do
subject(:repo) do
- Class.new(ROM::Repository[:books]).new(rom)
+ Class.new(ROM::Repository[:books]) { commands :create }.new(rom)
end
include_context 'database'
include_context 'seeds'
- before do
- configuration.relation(:books) do
- schema(infer: true)
+ context 'typed projections' do
+ before do
+ configuration.relation(:books) do
+ schema(infer: true)
- view(:index) do
- schema { project(:id, :title, :created_at) }
- relation { order(:title) }
+ view(:index) do
+ schema { project(:id, :title, :created_at) }
+ relation { order(:title) }
+ end
end
+
+ rom.relations[:books].insert(title: 'Hello World', created_at: Time.now)
end
- rom.relations[:books].insert(title: 'Hello World', created_at: Time.now)
+ it 'loads typed structs' do
+ book = repo.books.index.first
+
+ expect(book).to be_kind_of(Dry::Struct)
+
+ expect(book.id).to be_kind_of(Integer)
+ expect(book.title).to eql('Hello World')
+ expect(book.created_at).to be_kind_of(Time)
+ end
end
- it 'loads typed structs' do
- book = repo.books.index.first
+ context 'read-write type coercions' do
+ before do
+ configuration.relation(:books) do
+ schema(infer: true) do
+ attribute :title,
+ ROM::Types::Coercible::String.meta(
+ read: ROM::Types::Symbol.constructor(&:to_sym)
+ )
+ end
+ end
+
+ configuration.commands(:books) do
+ define(:create) { result(:one) }
+ end
+ end
+
+ it 'loads typed structs' do
+ created_book = repo.create(title: :'Hello World', created_at: Time.now)
- expect(book).to be_kind_of(Dry::Struct)
+ expect(created_book).to be_kind_of(Dry::Struct)
- expect(book.id).to be_kind_of(Integer)
- expect(book.title).to eql('Hello World')
- expect(book.created_at).to be_kind_of(Time)
+ expect(created_book.id).to be_kind_of(Integer)
+ expect(created_book.title).to eql(:'Hello World')
+ expect(created_book.created_at).to be_kind_of(Time)
+
+ book = repo.books.to_a.first
+
+ expect(book).to eql(created_book)
+ end
end
end
diff --git a/spec/unit/struct_builder_spec.rb b/spec/unit/struct_builder_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/struct_builder_spec.rb
+++ b/spec/unit/struct_builder_spec.rb
@@ -7,7 +7,7 @@ RSpec.describe 'struct builder', '#call' do
aliased?: false,
wrapped?: false,
foreign_key?: false,
- type: ROM::Types.const_get(type),
+ to_read_type: ROM::Types.const_get(type),
**opts
)
end | Use read types in structs
fixes #<I> | rom-rb_rom | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.