hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
3470283106a51d35f86eda41605278a1be135bff
|
diff --git a/lib/linter.js b/lib/linter.js
index <HASH>..<HASH> 100644
--- a/lib/linter.js
+++ b/lib/linter.js
@@ -12,7 +12,9 @@ function lintManifest(manifest) {
// WARNING: if we want to go through resources in detail, we need to keep in mind it can be a string or {name, types, ?idPrefixes}
assertArray(manifest.resources, 'manifest.resources')
+ assertAllInSet(manifest.resources, ['catalog', 'meta', 'stream', 'subtitles'], 'manifest resources in valid set')
assertArray(manifest.types, 'manifest.types')
+ assertAllInSet(manifest.types, ['movie', 'series', 'channel', 'tv', 'other'], 'manifest.types all in set')
if (manifest.hasOwnProperty('catalogs')) assertArray(manifest.catalogs, 'manifest.catalogs')
if (manifest.hasOwnProperty('idPrefixes')) assertArray(manifest.idPrefixes, 'manifest.idPrefixes')
@@ -43,6 +45,14 @@ function lintManifest(manifest) {
errors.push(new Error(name+' must be an array'))
}
+ function assertAllInSet(val, set, name) {
+ if (!Array.isArray(val)) return
+ val.forEach(function(m) {
+ if (!set.includes(m))
+ errors.push(new Error(name+': invalid value '+val))
+ })
+ }
+
return { valid: !errors.length, errors: errors }
}
diff --git a/test/basic.js b/test/basic.js
index <HASH>..<HASH> 100644
--- a/test/basic.js
+++ b/test/basic.js
@@ -203,6 +203,6 @@ tape('collection - valid collection', function(t) {
let result = linter.lintCollection(col)
t.equal(result.valid, true, 'valid collection')
- t.equal(result.errors.length, 0, 'no errors')
+ t.deepEqual(result.errors, [], 'no errors')
t.end()
-})
\ No newline at end of file
+})
|
lib/linter: add tests for types/resources - whether they are in an allowed set
|
Stremio_stremio-addon-linter
|
train
|
b2bfe33b1aa0d192ff91cbbdd73314e8f54a6de9
|
diff --git a/LiSE/character.py b/LiSE/character.py
index <HASH>..<HASH> 100644
--- a/LiSE/character.py
+++ b/LiSE/character.py
@@ -762,16 +762,7 @@ class Thing(ThingPlace):
"""
destn = dest.name if hasattr(dest, 'name') else dest
graph = self.character if graph is None else graph
- if graph is None and '_paths' in self.character.graph:
- # use a cached path
- paths = self.character._paths
- path = paths[weight][self['location']][destn]
- elif hasattr(graph, 'graph') and '_paths' in graph.graph:
- # use a cached path from the given graph
- paths = graph._paths
- path = paths[weight][self['location']][destn]
- else:
- path = nx.shortest_path(graph, self["location"], destn, weight)
+ path = nx.shortest_path(graph, self["location"], destn, weight)
return self.follow_path(path, weight)
def travel_to_by(self, dest, arrival_tick, weight=None, graph=None):
@@ -1023,7 +1014,6 @@ class Portal(GraphEdgeMapping.Edge):
super().__setitem__(key, value)
return
if key in self.character._portal_traits:
- del self.character.graph['_paths']
self.character._portal_traits = set()
(branch, tick) = self.engine.time
cache_set(
@@ -1041,7 +1031,6 @@ class Portal(GraphEdgeMapping.Edge):
super().__delitem__(key)
return
if key in self.character._portal_traits:
- del self.character.graph['_paths']
self.character._portal_traits = set()
(branch, tick) = self.engine.time
cache_del(
@@ -1574,9 +1563,6 @@ class CharacterPortalSuccessorsMapping(GraphSuccessorsMapping, RuleFollower):
p.clear()
p.exists = True
p.update(value)
- if '_paths' in self.graph.graph:
- del self.graph.graph['_paths']
- self.graph._paths = {}
def __delitem__(self, nodeB):
if not self.engine.caching:
@@ -1631,10 +1617,6 @@ class CharacterPortalPredecessorsMapping(
p.clear()
p.exists = True
p.update(value)
- if '_paths' in self.graph.graph:
- del self.graph.graph['_paths']
- if hasattr(self.graph, '_paths'):
- self.graph._paths = {}
class CharacterAvatarGraphMapping(Mapping, RuleFollower):
@@ -2571,11 +2553,6 @@ class Character(DiGraph, RuleFollower):
)
if engine.caching:
self.stat = CharStatCache(self)
- self._paths = (
- self.graph['_paths']
- if '_paths' in self.graph
- else {}
- )
else:
self.stat = self.graph
self._portal_traits = set()
@@ -2589,32 +2566,6 @@ class Character(DiGraph, RuleFollower):
"""
self.travel_reqs.append(fun)
- def cache_paths(self):
- """Calculate all shortest paths in me, and cache them, to avoid having
- to do real pathfinding later.
-
- The cache will be deleted when a Portal is added or removed,
- or when any trait that all Portals have is changed or deleted
- on any of them.
-
- """
- path_d = {}
- # one set of shortest paths for every trait that all Portals have
- self._portal_traits = set()
- for (o, d, port) in self.in_edges_iter(data=True):
- for trait in port:
- self._portal_traits.add(trait)
- for (o, d, port) in self.in_edges_iter(data=True):
- for trait in self._portal_traits:
- if trait not in port:
- self._portal_traits.remove(trait)
- traits = self._portal_traits + set([None])
- for trait in traits:
- path_d[trait] = nx.shortest_path(self, weight=trait)
- if self.engine.caching:
- self._paths = path_d
- self.graph['_paths'] = path_d
-
def add_place(self, name, **kwargs):
"""Create a new Place by the given name, and set its initial
attributes based on the keyword arguments (if any).
|
get rid of cache_paths related stuff that I haven't been testing
|
LogicalDash_LiSE
|
train
|
51ce31a7414e26b0bff663c6fca7c62a244c58ce
|
diff --git a/src/main/java/com/restfb/scope/FacebookPermissions.java b/src/main/java/com/restfb/scope/FacebookPermissions.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/restfb/scope/FacebookPermissions.java
+++ b/src/main/java/com/restfb/scope/FacebookPermissions.java
@@ -975,6 +975,21 @@ public enum FacebookPermissions {
INSTAGRAM_MANAGE_INSIGHTS("instagram_manage_insights", Category.INSTAGRAM),
/**
+ * The instagram_manage_messages permission allows business users to read and respond to Instagram Direct messages.
+ *
+ * <p>
+ * Please see <a href="https://developers.facebook.com/docs/instagram-api/getting-started">Instagram's Getting Started
+ * Guide</a> for details.
+ *
+ * <p>
+ * <strong>Review</strong>
+ *
+ * <p>
+ * If your app requests this permission Facebook will have to review how your app uses it.
+ */
+ INSTAGRAM_MANAGE_MESSAGES("instagram_manage_messages", Category.INSTAGRAM),
+
+ /**
* Provides the ability to publish content to Instagram account you have access to.
*
* <p>
|
Issue #<I> - instagram messaging permission added
|
restfb_restfb
|
train
|
6abc0120934b856823d70539638854c5ffc0e293
|
diff --git a/lib/proxies/dom.js b/lib/proxies/dom.js
index <HASH>..<HASH> 100644
--- a/lib/proxies/dom.js
+++ b/lib/proxies/dom.js
@@ -65,7 +65,8 @@ function DomProxy(raja, opts) {
debug("Detected change releases page", resource.key);
Dom.pool.release(resource.page);
}
- if (resource.headers && typeis(resource.headers['Content-Type'], '*/javascript')) {
+ var contentType = resource.headers && resource.headers['Content-Type'];
+ if (contentType && (typeis(contentType, '*/javascript') || typeis(contentType, 'text/html'))) {
debug("Detected change in", key);
reload = true;
}
|
Flush page if a js or html dependency is invalid
|
kapouer_raja
|
train
|
8f9486b20e600fe781b0a2f13e3f0bbfdf96a397
|
diff --git a/src/Composer/Util/Http/Response.php b/src/Composer/Util/Http/Response.php
index <HASH>..<HASH> 100644
--- a/src/Composer/Util/Http/Response.php
+++ b/src/Composer/Util/Http/Response.php
@@ -90,12 +90,6 @@ class Response
foreach ($headers as $header) {
if (preg_match('{^'.preg_quote($name).':\s*(.+?)\s*$}i', $header, $match)) {
$value = $match[1];
- } elseif (preg_match('{^HTTP/}i', $header)) {
- // TODO ideally redirects would be handled in CurlDownloader/RemoteFilesystem and this becomes unnecessary
- //
- // In case of redirects, http_response_headers contains the headers of all responses
- // so we reset the flag when a new response is being parsed as we are only interested in the last response
- $value = null;
}
}
|
redirects are handled in userland now so no need for this hack anymore
|
composer_composer
|
train
|
81a84b3083bf6af9d9e4ebbe1fa81ae3764ae9b9
|
diff --git a/commons/src/main/java/io/wcm/sling/commons/util/package-info.java b/commons/src/main/java/io/wcm/sling/commons/util/package-info.java
index <HASH>..<HASH> 100644
--- a/commons/src/main/java/io/wcm/sling/commons/util/package-info.java
+++ b/commons/src/main/java/io/wcm/sling/commons/util/package-info.java
@@ -20,5 +20,5 @@
/**
* Miscellaneous helper classes.
*/
-@org.osgi.annotation.versioning.Version("0.5.0")
+@org.osgi.annotation.versioning.Version("0.6.0")
package io.wcm.sling.commons.util;
|
Add Escape.jcrQueryLiteral and Escape.jcrQueryContainsExpr methods.
|
wcm-io_wcm-io-sling
|
train
|
a33431a07c2798b7b1c96e13f8d93582eb309f58
|
diff --git a/redis/client.py b/redis/client.py
index <HASH>..<HASH> 100644
--- a/redis/client.py
+++ b/redis/client.py
@@ -389,7 +389,7 @@ class Redis(threading.local):
def delete(self, *names):
"Delete one or more keys specified by ``names``"
- return self.format_inline('DEL', ' '.join(names))
+ return self.format_inline('DEL', *names)
__delitem__ = delete
def flush(self, all_dbs=False):
|
no reason to join the names here -- just let the format_inline do it, that way we get the benefit of encoding, too!
|
andymccurdy_redis-py
|
train
|
eb99029f4c592a8aa5dc3bd6fe8fdd827f5b1a4b
|
diff --git a/lib/produce/config.rb b/lib/produce/config.rb
index <HASH>..<HASH> 100644
--- a/lib/produce/config.rb
+++ b/lib/produce/config.rb
@@ -24,8 +24,11 @@ module Produce
app_name: ENV['PRODUCE_APP_NAME'],
version: ENV['PRODUCE_VERSION'],
sku: ENV['PRODUCE_SKU'],
- skip_itc: skip_itc?(ENV['PRODUCE_SKIP_ITC'])
+ skip_itc: skip_itc?(ENV['PRODUCE_SKIP_ITC']),
+ team_id: ENV['PRODUCE_TEAM_ID'],
+ team_name: ENV['PRODUCE_TEAM_NAME']
}
+
if ENV['PRODUCE_LANGUAGE']
language = ENV['PRODUCE_LANGUAGE']
if is_valid_language?(language)
|
set team_id, team_name on config
|
fastlane_fastlane
|
train
|
5360823c28acdc4c8ba8e33be3e40c74974abb49
|
diff --git a/segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/ZooKeeperServiceRunner.java b/segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/ZooKeeperServiceRunner.java
index <HASH>..<HASH> 100644
--- a/segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/ZooKeeperServiceRunner.java
+++ b/segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/ZooKeeperServiceRunner.java
@@ -23,6 +23,7 @@ import org.apache.bookkeeper.util.IOUtils;
import org.apache.bookkeeper.util.LocalBookKeeper;
import org.apache.commons.io.FileUtils;
import org.apache.zookeeper.server.NIOServerCnxnFactory;
+import org.apache.zookeeper.server.ZKDatabase;
import org.apache.zookeeper.server.ZooKeeperServer;
/**
@@ -81,15 +82,29 @@ public class ZooKeeperServiceRunner implements AutoCloseable {
}
public void stop() {
- ZooKeeperServer zs = this.server.getAndSet(null);
- if (zs != null) {
- zs.shutdown();
+ try {
+ NIOServerCnxnFactory sf = this.serverFactory.getAndSet(null);
+ if (sf != null) {
+ sf.closeAll();
+ sf.shutdown();
+ }
+ } catch (Throwable e) {
+ log.warn("Unable to cleanly shutdown ZooKeeper connection factory", e);
}
- NIOServerCnxnFactory sf = this.serverFactory.getAndSet(null);
- if (sf != null) {
- sf.closeAll();
- sf.shutdown();
+ try {
+ ZooKeeperServer zs = this.server.getAndSet(null);
+ if (zs != null) {
+ zs.shutdown();
+ ZKDatabase zkDb = zs.getZKDatabase();
+ if (zkDb != null) {
+ // make ZK server close its log files
+ zkDb.close();
+ }
+ }
+
+ } catch (Throwable e) {
+ log.warn("Unable to cleanly shutdown ZooKeeper server", e);
}
}
|
[issue-<I>] Standalone mode should cleanly shutdown the embedded ZK server (#<I>)
cleanly stop `ZooKeeperServiceRunner`
|
pravega_pravega
|
train
|
4c45f992cc9c4fe89b9a2adc5cdb1528aea0e033
|
diff --git a/src/EncryptingCacheDecorator.php b/src/EncryptingCacheDecorator.php
index <HASH>..<HASH> 100644
--- a/src/EncryptingCacheDecorator.php
+++ b/src/EncryptingCacheDecorator.php
@@ -22,7 +22,7 @@ abstract class EncryptingCacheDecorator implements Cache
public function fetch($id)
{
$stored = $this->decorated->fetch($id);
- if ($this->isDataDecryptable($stored)) {
+ if ($this->isDataDecryptable($stored, $id)) {
return $this->decrypt($stored);
}
@@ -35,7 +35,7 @@ abstract class EncryptingCacheDecorator implements Cache
public function save($id, $data, $ttl = 0)
{
return $this->decorated
- ->save($id, $this->encrypt($data), $ttl);
+ ->save($id, $this->encrypt($data, $id), $ttl);
}
/**
@@ -44,7 +44,7 @@ abstract class EncryptingCacheDecorator implements Cache
public function contains($id)
{
if ($stored = $this->decorated->fetch($id)) {
- return $this->isDataDecryptable($stored);
+ return $this->isDataDecryptable($stored, $id);
}
return false;
@@ -79,9 +79,14 @@ abstract class EncryptingCacheDecorator implements Cache
return true;
}
- abstract protected function encrypt($data);
+ protected function hmac($encrypted, $id)
+ {
+ return hash_hmac('sha256', $encrypted, $id);
+ }
+
+ abstract protected function encrypt($data, $id);
abstract protected function decrypt($data);
- abstract protected function isDataDecryptable($data);
+ abstract protected function isDataDecryptable($data, $id);
}
diff --git a/src/PasswordEncryptionDecorator.php b/src/PasswordEncryptionDecorator.php
index <HASH>..<HASH> 100644
--- a/src/PasswordEncryptionDecorator.php
+++ b/src/PasswordEncryptionDecorator.php
@@ -13,36 +13,39 @@ class PasswordEncryptionDecorator extends EncryptingCacheDecorator
public function __construct(
Cache $decorated,
$passphrase,
- $cipher = 'aes256'
+ $cipher = 'aes-256-cbc'
) {
parent::__construct($decorated);
$this->passphrase = $passphrase;
$this->cipher = $cipher;
}
- protected function isDataDecryptable($data)
+ protected function isDataDecryptable($data, $id)
{
return is_array($data)
- && $this->arrayHasKeys($data, ['encrypted', 'iv', 'cipher'])
- && $data['cipher'] === $this->cipher;
+ && $this->arrayHasKeys($data, ['encrypted', 'iv', 'cipher', 'mac'])
+ && $data['cipher'] === $this->cipher
+ && $data['mac'] === $this->hmac($data['encrypted'], $id);
}
- protected function encrypt($data)
+ protected function encrypt($data, $id)
{
$iv = openssl_random_pseudo_bytes(
openssl_cipher_iv_length($this->cipher)
);
+ $encrypted = openssl_encrypt(
+ serialize($data),
+ $this->cipher,
+ $this->passphrase,
+ 0,
+ $iv
+ );
return [
'cipher' => $this->cipher,
'iv' => base64_encode($iv),
- 'encrypted' => openssl_encrypt(
- serialize($data),
- $this->cipher,
- $this->passphrase,
- 0,
- $iv
- ),
+ 'encrypted' => $encrypted,
+ 'mac' => $this->hmac($encrypted, $id),
];
}
diff --git a/src/PkiEncryptionDecorator.php b/src/PkiEncryptionDecorator.php
index <HASH>..<HASH> 100644
--- a/src/PkiEncryptionDecorator.php
+++ b/src/PkiEncryptionDecorator.php
@@ -47,26 +47,29 @@ class PkiEncryptionDecorator extends EncryptingCacheDecorator
openssl_free_key($this->privateKey);
}
- protected function isDataDecryptable($data)
+ protected function isDataDecryptable($data, $id)
{
return is_array($data)
- && $this->arrayHasKeys($data, ['encrypted', 'keys', 'cipher'])
+ && $this->arrayHasKeys($data, ['encrypted', 'keys', 'cipher', 'mac'])
&& isset($data['keys'][$this->publicKeyFingerprint])
- && $data['cipher'] === $this->cipher;
+ && $data['cipher'] === $this->cipher
+ && $data['mac'] === $this->hmac($data['encrypted'], $id);
}
- protected function encrypt($data)
+ protected function encrypt($data, $id)
{
$data = serialize($data);
openssl_seal($data, $encrypted, $keys, $this->publicKeys, $this->cipher);
+ $encrypted = base64_encode($encrypted);
return [
- 'encrypted' => base64_encode($encrypted),
+ 'encrypted' => $encrypted,
'keys' => array_combine(
array_keys($this->publicKeys),
array_map('base64_encode', $keys)
),
'cipher' => $this->cipher,
+ 'mac' => $this->hmac($encrypted, $id),
];
}
|
Add an authentication step to guard against chosen ciphertext attacks
|
jeskew_doctrine-cache-encrypter
|
train
|
f5fa8f9f0e2be3253f99478c3c2aabca97ceb62e
|
diff --git a/bundles/org.eclipse.orion.client.git/web/orion/git/gitRepositoryExplorer.js b/bundles/org.eclipse.orion.client.git/web/orion/git/gitRepositoryExplorer.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.git/web/orion/git/gitRepositoryExplorer.js
+++ b/bundles/org.eclipse.orion.client.git/web/orion/git/gitRepositoryExplorer.js
@@ -725,10 +725,10 @@ exports.GitRepositoryExplorer = (function() {
"<h1>Tags" + (mode === "full" ? "" : " (5 most recent)") + "</h1>" +
(mode === "full" ? "" : ("<h2 id=\"tagSubHeader\"><a href=\"/git/git-repository.html#" + tagLocation + "\">See all tags</a></h2>")) +
"<section class=\"extension-settings-content\">" +
- "<div class=\"extension-settings\">" +
- "<list id=\"tagNode\" class=\"extension-settings-list\">" +
- "</list>" +
- "</div>" +
+ "<div class=\"extension-settings\">" +
+ "<list id=\"tagNode\" class=\"extension-settings-list\">" +
+ "</list>" +
+ "</div>" +
"</section>" +
"</div>";
@@ -740,7 +740,7 @@ exports.GitRepositoryExplorer = (function() {
dojo.empty("tagNode");
dojo.byId("tagNode").innerHTML = "Loading...";
- this.registry.getService("orion.git.provider").getGitBranch(tagLocation).then(
+ this.registry.getService("orion.git.provider").getGitBranch(tagLocation + (mode === "full" ? "" : "?commits=1&page=1&pageSize=5")).then(
function(resp){
var tags = resp.Children.slice(0, 5);
if (mode === 'full')
@@ -752,18 +752,24 @@ exports.GitRepositoryExplorer = (function() {
dojo.empty("tagSubHeader");
return;
}
+
+ dojo.empty("tagNode");
+ for(var i=0; i<tags.length ;i++){
+ tags[i].Repository = repository;
+ that.renderTag(tags[i]);
+ };
- that.decorateTags(tags).then(
- function(){
- dojo.empty("tagNode");
- for(var i=0; i<tags.length ;i++){
- tags[i].Repository = repository;
- that.renderTag(tags[i]);
- };
- }
- );
+// that.decorateTags(tags).then(
+// function(){
+// dojo.empty("tagNode");
+// for(var i=0; i<tags.length ;i++){
+// tags[i].Repository = repository;
+// that.renderTag(tags[i]);
+// };
+// }
+// );
}, function(error){
-
+ that.handleError(error, that.registry);
}
);
};
@@ -794,10 +800,13 @@ exports.GitRepositoryExplorer = (function() {
dojo.create( "div", null, detailsView );
var description = dojo.create( "span", { "class":"extension-description"}, detailsView );
- link = dojo.create("a", {className: "navlinkonpage", href: "/git/git-commit.html#" + tag.Commit.Location + "?page=1&pageSize=1"}, description);
- dojo.place(document.createTextNode(tag.Commit.Message), link);
- dojo.place(document.createTextNode(" by " + tag.Commit.AuthorName + " on " +
- dojo.date.locale.format(new Date(tag.Commit.Time), {formatLength: "short"})), description, "last");
+ if (tag.Commit){
+ var commit = tag.Commit.Children[0];
+ link = dojo.create("a", {className: "navlinkonpage", href: "/git/git-commit.html#" + commit.Location + "?page=1&pageSize=1"}, description);
+ dojo.place(document.createTextNode(commit.Message), link);
+ dojo.place(document.createTextNode(" by " + commit.AuthorName + " on " +
+ dojo.date.locale.format(new Date(commit.Time), {formatLength: "short"})), description, "last");
+ }
var actionsArea = dojo.create( "div", {"id":"tagActionsArea"}, horizontalBox );
this.registry.getService("orion.page.command").renderCommands(actionsArea, "object", tag, this, "button", false);
|
Adapt to new Git API introduced by bug <I>
|
eclipse_orion.client
|
train
|
f4a4378292b776416c4549311e6b9ac732363933
|
diff --git a/salt/states/dockerio.py b/salt/states/dockerio.py
index <HASH>..<HASH> 100644
--- a/salt/states/dockerio.py
+++ b/salt/states/dockerio.py
@@ -6,7 +6,7 @@ Manage Docker containers
`Docker <https://en.wikipedia.org/wiki/Docker_(software)>`_
is a lightweight, portable, self-sufficient software container
-based on `Linux Containers (LXC)
+wrapper. The base supported wrapper type is LXC:
<https://en.wikipedia.org/wiki/Linux_Containers>`_,
`cgroups <https://en.wikipedia.org/wiki/Cgroups>`_, and the
`Linux Kernel <https://en.wikipedia.org/wiki/Linux_kernel>`_.
@@ -18,7 +18,7 @@ based on `Linux Containers (LXC)
.. note::
- This state module requires a
+ This state module requires
`docker-py <https://github.com/dotcloud/docker-py>`_
which supports `Docker Remote API version 1.6
<https://docs.docker.io/en/latest/api/docker_remote_api_v1.6/>`_.
@@ -80,8 +80,10 @@ Available Functions
- unless: grep -q something /var/log/foo
- docker_unless: grep -q done /install_log
-.. note:: The docker modules are named `dockerio` because
- the name 'docker' would conflict with the underlying docker-py library.
+.. note::
+
+ The docker modules are named `dockerio` because
+ the name 'docker' would conflict with the underlying docker-py library.
'''
@@ -105,7 +107,7 @@ __virtualname__ = 'docker'
def __virtual__():
'''
- Only load if the docker libs are available (`import docker`).
+ Only load if the docker libs are available.
'''
if HAS_DOCKER:
return __virtualname__
@@ -215,18 +217,19 @@ def pulled(name, force=False, *args, **kwargs):
'''
Pull an image from a docker registry. (`docker pull`)
- .. note:: The image must already be loaded in docker; see the
- documentation for `docker login`, `docker pull`, `docker push`,
- and `docker.import_image <https://github.com/dotcloud/docker-py#api>`_
- (`docker import
- <http://docs.docker.io/en/latest/commandline/cli/#import>`_).
+ .. note::
+
+ The image must already be loaded in docker; see the
+ documentation for `docker login`, `docker pull`, `docker push`,
+ and `docker.import_image <https://github.com/dotcloud/docker-py#api>`_
+ (`docker import
+ <http://docs.docker.io/en/latest/commandline/cli/#import>`_).
name
Tag of the image
force
Pull even if the image is already pulled
-
'''
ins = __salt('docker.inspect_image')
iinfos = ins(name)
@@ -308,7 +311,6 @@ def installed(name,
path
Path in the filesystem to the dockerfile
- XXX: TODO: does this support a URL?
environment
Environment variables for the container, either
@@ -328,21 +330,16 @@ def installed(name,
<http://docs.docker.io/en/latest/commandline/cli/#run>`_ for the
`docker run` command.
- XXX TODO: It would be helpful to list the supported kwargs here.
-
You can create it either by specifying :
- an image
- an absolute path on the filesystem
- This mean that you need one of those two parameters.
-
- XXX TODO: Image appears to be a required parameter.
-
- .. note:: This command does not verify that the named container
- is running the specified image.
-
+ This mean that one of two parameters are required.
+ .. note::
+ This command does not verify that the named container
+ is running the specified image.
'''
ins_image = __salt('docker.inspect_image')
ins_container = __salt('docker.inspect_container')
@@ -417,10 +414,6 @@ def absent(name):
name:
Either the container name or id
-
- .. note:: eventually the grain matching will be removed
- XXX TODO: is this removed?
-
'''
ins_container = __salt__['docker.inspect_container']
cinfos = ins_container(name)
@@ -453,7 +446,6 @@ def present(name):
name:
Either a `state_id` or container id
-
'''
ins_container = __salt('docker.inspect_container')
cinfos = ins_container(name)
@@ -622,12 +614,10 @@ def script(name,
docked_onlyif=None,
docked_unless=None,
*args, **kwargs):
- '''Run a command in a specific container
-
- XXX: TODO: IMPLEMENT
- XXX: TODO: is this the same as `.run()`?
-
- You can match by either name or hostname
+ '''
+ Run a command in a specific container
+
+ Matching can be done by either name or hostname
name
command to run in the docker
|
Clean up dockerio state docs
@kiorky, did I miss anything? Also we want the docs to never
be in first person, still need to clean this up.
|
saltstack_salt
|
train
|
7ed208b05353f0d545e651c6ed9d571abe227136
|
diff --git a/concrete/src/Page/Controller/DashboardExpressEntriesPageController.php b/concrete/src/Page/Controller/DashboardExpressEntriesPageController.php
index <HASH>..<HASH> 100644
--- a/concrete/src/Page/Controller/DashboardExpressEntriesPageController.php
+++ b/concrete/src/Page/Controller/DashboardExpressEntriesPageController.php
@@ -106,7 +106,10 @@ abstract class DashboardExpressEntriesPageController extends DashboardPageContro
return StreamedResponse::create(function () use ($entity, $me, $bom) {
$entryList = new EntryList($entity);
- $writer = new CsvWriter($this->app->make(WriterFactory::class)->createFromPath('php://output', 'w'), new Date());
+ $writer = $this->app->make(CsvWriter::class, [
+ $this->app->make(WriterFactory::class)->createFromPath('php://output', 'w'),
+ new Date()
+ ]);
echo $bom;
$writer->insertHeaders($entity);
$writer->insertEntryList($entryList);
|
Use container to create CsvWriter instance
|
concrete5_concrete5
|
train
|
72f9f5df6aae6796d7a527c646c45faa6f8b9241
|
diff --git a/web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/tests/BaselineExperimentsControllerIT.java b/web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/tests/BaselineExperimentsControllerIT.java
index <HASH>..<HASH> 100644
--- a/web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/tests/BaselineExperimentsControllerIT.java
+++ b/web/src/test/java/uk/ac/ebi/atlas/acceptance/selenium/tests/BaselineExperimentsControllerIT.java
@@ -44,6 +44,7 @@ public class BaselineExperimentsControllerIT extends SinglePageSeleniumFixture {
@Test
public void countNumberOfSpecies() {
assertThat(subject.getAllSpeciesItems().size(), is(10));
+
}
@Test
|
Fix tests: species are <I>
|
ebi-gene-expression-group_atlas
|
train
|
fb8fbfb850941c76e35a3a15aafa19d6f1afa327
|
diff --git a/src/UriTemplate/UriTemplate.php b/src/UriTemplate/UriTemplate.php
index <HASH>..<HASH> 100644
--- a/src/UriTemplate/UriTemplate.php
+++ b/src/UriTemplate/UriTemplate.php
@@ -161,7 +161,7 @@ private static function expandExpression($template, $variables, $keySort)
continue;
}
- if ((is_array($value) || is_object($value)) && $varspec['prefix'] !== null) {
+ if (is_array($value) && $varspec['prefix'] !== null) {
throw new UriTemplateException('Prefix modifier used with array value: %s', array($template));
}
|
$value can't be an object
|
mcrumley_uritemplate
|
train
|
15550ed06057d37a28209e611f41c8160be66414
|
diff --git a/lib/rubocop/cli.rb b/lib/rubocop/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/rubocop/cli.rb
+++ b/lib/rubocop/cli.rb
@@ -116,7 +116,7 @@ module Rubocop
path = File.join(dir, '.rubocop.yml')
if File.exist?(path)
@configs[target_file_dir] = YAML.load_file(path)
- break
+ return @configs[target_file_dir]
end
dir = File.expand_path('..', dir)
end
diff --git a/spec/rubocop/cli_spec.rb b/spec/rubocop/cli_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/rubocop/cli_spec.rb
+++ b/spec/rubocop/cli_spec.rb
@@ -1,6 +1,7 @@
# encoding: utf-8
require 'fileutils'
+require 'tmpdir'
require 'spec_helper'
module Rubocop
@@ -235,6 +236,37 @@ module Rubocop
end
end
+ it 'prefers a config file in ancestor directory to another in home' do
+ FileUtils.mkdir 'example_src'
+ File.open('example_src/example1.rb', 'w') do |f|
+ f.puts '# encoding: utf-8'
+ f.puts '#' * 90
+ end
+ File.open('example_src/.rubocop.yml', 'w') do |f|
+ f.puts('LineLength:',
+ ' Enabled: true',
+ ' Max: 100')
+ end
+ Dir.mktmpdir do |tmpdir|
+ @original_home = ENV['HOME']
+ ENV['HOME'] = tmpdir
+ File.open("#{Dir.home}/.rubocop.yml", 'w') do |f|
+ f.puts('LineLength:',
+ ' Enabled: true',
+ ' Max: 80')
+ end
+ begin
+ expect(cli.run(['example_src/example1.rb'])).to eq(0)
+ expect($stdout.string.uncolored).to eq(
+ ['', '1 files inspected, 0 offences detected',
+ ''].join("\n"))
+ ensure
+ FileUtils.rm_rf 'example_src'
+ ENV['HOME'] = @original_home
+ end
+ end
+ end
+
it 'finds no violations when checking the rubocop source code' do
cli.run
expect($stdout.string.uncolored).to match(
|
Fix config files in ancestor dirs are ignored if another exists in home
|
rubocop-hq_rubocop
|
train
|
bba2b54a7d47955e42d86ec4c09403a3628f5d04
|
diff --git a/src/utilities/behaviors/JointCollisionEvents.js b/src/utilities/behaviors/JointCollisionEvents.js
index <HASH>..<HASH> 100644
--- a/src/utilities/behaviors/JointCollisionEvents.js
+++ b/src/utilities/behaviors/JointCollisionEvents.js
@@ -31,14 +31,12 @@ window.altspace.utilities.behaviors = window.altspace.utilities.behaviors || {};
* @param {Number} [config.jointCubeSize=15] Size of dummy cube used to track each joint
* @memberof module:altspace/utilities/behaviors
**/
- // TODO: Add scale option?
-altspace.utilities.behaviors.JointCollisionEvents = function (config) {
+altspace.utilities.behaviors.JointCollisionEvents = function(_config) {
var object3d;
+ var config = _config || {};
- config = config || {};
-
- if (config.jointCubeSize === undefined) config.jointCubeSize = 15;
- if (config.joints === undefined) config.joints = [
+ config.jointCubeSize = config.jointCubeSize || 15;
+ config.joints = config.joints || [
['Hand', 'Left', 0],
['Thumb', 'Left', 3],
['Index', 'Left', 3],
@@ -56,30 +54,51 @@ altspace.utilities.behaviors.JointCollisionEvents = function (config) {
var skeleton;
var jointCube;
+ var hasCollided = false;
+
+ function initSkeleton(scene) {
+ return new Promise(function(resolve, reject) {
+ var skel = null;
+
+ // Attempt to use existing skeleton when available
+ scene.traverse(function(child) {
+ if(child.type === 'TrackingSkeleton') {
+ skel = child;
+ return;
+ }
+ });
+
+ if(skel) return resolve(skel);
- // Get the tracking skeleton and the enclosure
- var promises = [altspace.getThreeJSTrackingSkeleton(), altspace.getEnclosure()];
- Promise.all(promises).then(function (array) {
- // Attach skeleton
- skeleton = array[0];
- sim.scene.add(skeleton);
- enclosure = array[1]; // TODO: Use enclosure for scale?
- }).catch(function (err) {
- console.log('Failed to get Altspace browser properties', err);
- });
-
- function awake(o) {
+ // Skeleton has not been assigned to scene yet
+ altspace.getThreeJSTrackingSkeleton().then(function(trackingSkeleton) {
+ skel = trackingSkeleton;
+ scene.add(skel);
+ return resolve(skel);
+ });
+ });
+ }
+
+ function awake(o, s) {
object3d = o;
- // TODO: Scale jointCubeSize?
- jointCube = new THREE.Vector3(
- config.jointCubeSize,
- config.jointCubeSize,
- config.jointCubeSize
- );
+
+ // Get the tracking skeleton and the enclosure
+ initSkeleton(s).then(function(_skeleton) {
+ // Attach skeleton
+ skeleton = _skeleton;
+
+ jointCube = new THREE.Vector3(
+ config.jointCubeSize,
+ config.jointCubeSize,
+ config.jointCubeSize
+ );
+ }).catch(function (err) {
+ console.log('Failed to get Altspace browser properties', err);
+ });
}
function update(deltaTime) {
- if(!skeleton) { return; }
+ if(!skeleton) return;
// Collect joints based on joints config option
var joints = [];
@@ -96,7 +115,9 @@ altspace.utilities.behaviors.JointCollisionEvents = function (config) {
// Add up all colliding joint intersects
var jointIntersectUnion;
- var hasCollided = false;
+ var collidedJoints = [];
+ var hasPrevCollided = hasCollided;
+ hasCollided = false;
for(var i = 0; i < config.joints.length; i++) {
var joint = joints[i];
if(joint && joint.confidence !== 0) {
@@ -109,18 +130,47 @@ altspace.utilities.behaviors.JointCollisionEvents = function (config) {
} else {
jointIntersectUnion = intersectBB;
}
+
hasCollided = true;
+ collidedJoints.push(joint);
}
}
}
// Dispatch collision event
+ if(!hasPrevCollided && hasCollided) {
+ var event = new CustomEvent(
+ 'jointcollisionenter',
+ {
+ detail: {
+ intersect: jointIntersectUnion,
+ joints: collidedJoints
+ },
+ bubbles: true,
+ cancelable: true
+ }
+ );
+ object3d.dispatchEvent(event);
+ }
+ else if(hasPrevCollided && !hasCollided) {
+ var event = new CustomEvent(
+ 'jointcollisionleave',
+ {
+ bubbles: true,
+ cancelable: true
+ }
+ );
+ object3d.dispatchEvent(event);
+ }
+
+ // Dispatch collision event
if(hasCollided) {
var event = new CustomEvent(
'jointcollision',
{
detail: {
- intersect: jointIntersectUnion
+ intersect: jointIntersectUnion,
+ joints: collidedJoints
},
bubbles: true,
cancelable: true
|
Updated JointCollisionEvents behavior:
Corrected issue with scene object relying on global variable during behavior initialization.
Updated behavior to check for and reuse existing skeleton object in scene during behavior initialization.
Updated jointcollision event to provide an array of joints that were included in the intersection union.
Added jointcollisionenter (not colliding -> colliding) and jointcollisionleave (colliding -> not colliding) events which are fired only once when a change in collision state has occurred.
|
AltspaceVR_AltspaceSDK
|
train
|
4244f624c0f610987efb7cbe3d6d10ae720eed42
|
diff --git a/yasi.py b/yasi.py
index <HASH>..<HASH> 100644
--- a/yasi.py
+++ b/yasi.py
@@ -170,8 +170,8 @@ def trim(string):
string = re.sub(r'({)[ \t]*(?=({))', r'\1', string)
# remove leading whitespace ' print' ==> 'print'
string = re.sub('^[ \t]*', '', string)
- # Remove space before list literal, " ' (1 2 3)" ==> " '(1 2 3)"
- string = re.sub(r" ('|`) (\(|\[|{)", r' \1\2', string)
+ # Remove space between quote and opening bracket, "' (1 2 3)" ==> "'(1 2 3)"
+ string = re.sub("('|`)[ \t]+(\(|\[|{)", r'\1\2', string)
return string
|
Make trim function remove space after quote regardless any space before
The previous regex wouldn't work because any leading spaces before the quote
would have been removed before that
|
nkmathew_yasi-sexp-indenter
|
train
|
d08fea6176e3e530d376534f093a296d8adc1883
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -50,7 +50,7 @@ export class CDLL {
let next = this.head.next
cb(next.value)
- while (next !== this.head) {
+ while (next !== this.head && this.size > 0) {
next = next.next
if (cb(next.value) === false)
break
|
allows forEach to delete elements within the loop
|
jaredLunde_cdll-memoize
|
train
|
dba8cd07ef322fb717ec467de99932921b08458e
|
diff --git a/dist/iota.js b/dist/iota.js
index <HASH>..<HASH> 100644
--- a/dist/iota.js
+++ b/dist/iota.js
@@ -1194,7 +1194,7 @@ var Iota = function () {
}, {
key: '_createAppConfigOutputLegacy',
value: function _createAppConfigOutputLegacy() {
- var struct = new _struct2.default().word8('app_max_bundle_size').word8('app_version_major').word8('app_version_minor').word8('app_version_patch');
+ var struct = new _struct2.default().word8('app_flags').word8('app_version_major').word8('app_version_minor').word8('app_version_patch');
return struct;
}
diff --git a/src/iota.js b/src/iota.js
index <HASH>..<HASH> 100644
--- a/src/iota.js
+++ b/src/iota.js
@@ -620,7 +620,7 @@ class Iota {
_createAppConfigOutputLegacy() {
const struct = new Struct()
- .word8('app_max_bundle_size')
+ .word8('app_flags')
.word8('app_version_major')
.word8('app_version_minor')
.word8('app_version_patch');
|
Fix legacy app config contains flags instead of bundle size
|
IOTA-Ledger_hw-app-iota.js
|
train
|
9d41309e41c80e82acffdb942bc8abd19da0939a
|
diff --git a/src/App.php b/src/App.php
index <HASH>..<HASH> 100644
--- a/src/App.php
+++ b/src/App.php
@@ -113,7 +113,14 @@ class App
ob_start();
if (strlen($this->config->appDir) > 0 && is_file($this->config->appDir . DIRECTORY_SEPARATOR . 'index.php')) {
- include realpath($this->config->appDir . DIRECTORY_SEPARATOR . 'index.php');
+ ob_start();
+ try {
+ include realpath($this->config->appDir . DIRECTORY_SEPARATOR . 'index.php');
+ ob_end_clean();
+ } catch (\Exception $e) {
+ ob_end_clean();
+ throw $e;
+ }
}
if ($this->config->assetsPathPrefix !== null) {
diff --git a/src/App/Addons.php b/src/App/Addons.php
index <HASH>..<HASH> 100644
--- a/src/App/Addons.php
+++ b/src/App/Addons.php
@@ -59,7 +59,14 @@ class Addons
if ($__indexFilename !== false) {
unset($id); // Hide this variable from the file scope
unset($options); // Hide this variable from the file scope
- include_once $__indexFilename;
+ ob_start();
+ try {
+ include_once $__indexFilename;
+ ob_end_clean();
+ } catch (\Exception $e) {
+ ob_end_clean();
+ throw $e;
+ }
return true;
} else {
throw new \InvalidArgumentException('Invalid addon (the index file is missing)');
diff --git a/src/App/Config.php b/src/App/Config.php
index <HASH>..<HASH> 100644
--- a/src/App/Config.php
+++ b/src/App/Config.php
@@ -136,8 +136,13 @@ class Config
throw new \InvalidArgumentException('The filename specified (' . $filename . ') is not valid');
}
ob_start();
- $data = include $filename;
- ob_end_clean();
+ try {
+ $data = include $filename;
+ ob_end_clean();
+ } catch (\Exception $e) {
+ ob_end_clean();
+ throw $e;
+ }
if (is_array($data)) {
foreach ($data as $name => $value) {
$this->$name = $value;
diff --git a/src/App/Container.php b/src/App/Container.php
index <HASH>..<HASH> 100644
--- a/src/App/Container.php
+++ b/src/App/Container.php
@@ -62,7 +62,14 @@ class Container
if (is_string($result)) {
$result = new $result();
} elseif (is_callable($result)) {
- $result = call_user_func($result);
+ ob_start();
+ try {
+ $result = call_user_func($result);
+ ob_end_clean();
+ } catch (\Exception $e) {
+ ob_end_clean();
+ throw $e;
+ }
} elseif (is_object($result)) {
return $result;
}
diff --git a/src/App/Hooks.php b/src/App/Hooks.php
index <HASH>..<HASH> 100644
--- a/src/App/Hooks.php
+++ b/src/App/Hooks.php
@@ -92,7 +92,14 @@ class Hooks
});
}
foreach ($callbacks as $callback) {
- call_user_func_array($callback[0], $arguments);
+ ob_start();
+ try {
+ call_user_func_array($callback[0], $arguments);
+ ob_end_clean();
+ } catch (\Exception $e) {
+ ob_end_clean();
+ throw $e;
+ }
}
}
}
diff --git a/src/App/Routes.php b/src/App/Routes.php
index <HASH>..<HASH> 100644
--- a/src/App/Routes.php
+++ b/src/App/Routes.php
@@ -99,8 +99,13 @@ class Routes
}
if ($found) {
ob_start();
- $response = call_user_func($route[1]);
- ob_end_clean();
+ try {
+ $response = call_user_func($route[1]);
+ ob_end_clean();
+ } catch (\Exception $e) {
+ ob_end_clean();
+ throw $e;
+ }
if ($response instanceof App\Response) {
return $response;
}
|
Added output buffer cleaning on error.
|
bearframework_bearframework
|
train
|
68b6ba2fc99e5fdc8e41f682436d52cc3e5a0e39
|
diff --git a/support/cas-server-support-oidc-core/src/main/java/org/apereo/cas/services/OidcRegisteredService.java b/support/cas-server-support-oidc-core/src/main/java/org/apereo/cas/services/OidcRegisteredService.java
index <HASH>..<HASH> 100644
--- a/support/cas-server-support-oidc-core/src/main/java/org/apereo/cas/services/OidcRegisteredService.java
+++ b/support/cas-server-support-oidc-core/src/main/java/org/apereo/cas/services/OidcRegisteredService.java
@@ -28,6 +28,9 @@ public class OidcRegisteredService extends OAuthRegisteredService {
@Column(updatable = true, insertable = true)
private boolean signIdToken = true;
+ @Column(updatable = true, insertable = true)
+ private boolean implicit;
+
public OidcRegisteredService() {
setJsonFormat(Boolean.TRUE);
}
@@ -48,6 +51,14 @@ public class OidcRegisteredService extends OAuthRegisteredService {
this.jwks = jwks;
}
+ public boolean isImplicit() {
+ return implicit;
+ }
+
+ public void setImplicit(final boolean implicit) {
+ this.implicit = implicit;
+ }
+
@Override
protected AbstractRegisteredService newInstance() {
return new OidcRegisteredService();
@@ -69,6 +80,7 @@ public class OidcRegisteredService extends OAuthRegisteredService {
return builder
.appendSuper(super.equals(obj))
.append(this.jwks, rhs.jwks)
+ .append(this.implicit, rhs.implicit)
.append(this.signIdToken, rhs.signIdToken)
.isEquals();
}
@@ -79,6 +91,7 @@ public class OidcRegisteredService extends OAuthRegisteredService {
.appendSuper(super.hashCode())
.append(jwks)
.append(signIdToken)
+ .append(implicit)
.toHashCode();
}
@@ -87,6 +100,7 @@ public class OidcRegisteredService extends OAuthRegisteredService {
return new ToStringBuilder(this)
.appendSuper(super.toString())
.append("jwks", jwks)
+ .append("implicit", implicit)
.append("signIdToken", signIdToken)
.toString();
}
@@ -97,6 +111,7 @@ public class OidcRegisteredService extends OAuthRegisteredService {
try {
final OidcRegisteredService oidcService = (OidcRegisteredService) source;
setJwks(oidcService.getJwks());
+ setImplicit(oidcService.isImplicit());
setSignIdToken(oidcService.isSignIdToken());
} catch (final Exception e) {
throw Throwables.propagate(e);
|
Add implicit support to oidc svc
|
apereo_cas
|
train
|
3ffa5f61494aa67434a9b408540a9efb32e332cf
|
diff --git a/integration-cli/docker_cli_build_test.go b/integration-cli/docker_cli_build_test.go
index <HASH>..<HASH> 100644
--- a/integration-cli/docker_cli_build_test.go
+++ b/integration-cli/docker_cli_build_test.go
@@ -661,27 +661,6 @@ RUN ls -le /file`
}
-func (s *DockerSuite) TestBuildSixtySteps(c *check.C) {
- testRequires(c, DaemonIsLinux) // TODO Windows: This test passes on Windows,
- // but currently adds a disproportionate amount of time for the value it has.
- // Removing it from Windows CI for now, but this will be revisited in the
- // TP5 timeframe when perf is better.
- name := "foobuildsixtysteps"
-
- ctx, err := fakeContext("FROM "+minimalBaseImage()+"\n"+strings.Repeat("ADD foo /\n", 60),
- map[string]string{
- "foo": "test1",
- })
- if err != nil {
- c.Fatal(err)
- }
- defer ctx.Close()
-
- if _, err := buildImageFromContext(name, ctx, true); err != nil {
- c.Fatal(err)
- }
-}
-
func (s *DockerSuite) TestBuildAddSingleFileToRoot(c *check.C) {
testRequires(c, DaemonIsLinux) // Linux specific test
name := "testaddimg"
|
Remove build <I> steps
This test is already covered in the individual graph driver tests and it
adds <I>s to the test run without adding value. The original idea was to
test max number of layers, this is fulfilled by the graph drivers.
|
moby_moby
|
train
|
d4944b2e572969f629bfc712a2edeab20331a995
|
diff --git a/morphia/src/main/java/xyz/morphia/IndexHelper.java b/morphia/src/main/java/xyz/morphia/IndexHelper.java
index <HASH>..<HASH> 100644
--- a/morphia/src/main/java/xyz/morphia/IndexHelper.java
+++ b/morphia/src/main/java/xyz/morphia/IndexHelper.java
@@ -52,6 +52,7 @@ import static java.lang.String.format;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static xyz.morphia.AnnotationBuilder.toMap;
+import static xyz.morphia.internal.MorphiaUtils.join;
import static xyz.morphia.utils.IndexType.fromValue;
final class IndexHelper {
@@ -66,17 +67,6 @@ final class IndexHelper {
this.database = database;
}
- private static String join(final List<String> path, final char delimiter) {
- StringBuilder builder = new StringBuilder();
- for (String element : path) {
- if (builder.length() != 0) {
- builder.append(delimiter);
- }
- builder.append(element);
- }
- return builder.toString();
- }
-
private void calculateWeights(final Index index, final com.mongodb.client.model.IndexOptions indexOptions) {
Document weights = new Document();
for (Field field : index.fields()) {
diff --git a/morphia/src/main/java/xyz/morphia/mapping/MappedField.java b/morphia/src/main/java/xyz/morphia/mapping/MappedField.java
index <HASH>..<HASH> 100644
--- a/morphia/src/main/java/xyz/morphia/mapping/MappedField.java
+++ b/morphia/src/main/java/xyz/morphia/mapping/MappedField.java
@@ -534,16 +534,7 @@ public class MappedField {
final Type[] types = pt.getActualTypeArguments();
realType = toClass(pt);
- for (Type type : types) {
- if (type instanceof ParameterizedType) {
- typeParameters.add(new EphemeralMappedField((ParameterizedType) type, this, mapper));
- } else {
- if (type instanceof WildcardType) {
- type = ((WildcardType) type).getUpperBounds()[0];
- }
- typeParameters.add(new EphemeralMappedField(type, this, mapper));
- }
- }
+ collectTypeParameters(mapper, types);
} else if (genericType instanceof WildcardType) {
final WildcardType wildcardType = (WildcardType) genericType;
final Type[] types = wildcardType.getUpperBounds();
@@ -557,16 +548,7 @@ public class MappedField {
realType = toClass(genericType);
final Type[] types = pt.getActualTypeArguments();
- for (Type type : types) {
- if (type instanceof ParameterizedType) {
- typeParameters.add(new EphemeralMappedField((ParameterizedType) type, this, mapper));
- } else {
- if (type instanceof WildcardType) {
- type = ((WildcardType) type).getUpperBounds()[0];
- }
- typeParameters.add(new EphemeralMappedField(type, this, mapper));
- }
- }
+ collectTypeParameters(mapper, types);
} else {
if (genericComponentType instanceof TypeVariable) {
realType = toClass(genericType);
@@ -588,6 +570,19 @@ public class MappedField {
}
}
+ private void collectTypeParameters(final Mapper mapper, final Type[] types) {
+ for (Type type : types) {
+ if (type instanceof ParameterizedType) {
+ typeParameters.add(new EphemeralMappedField((ParameterizedType) type, this, mapper));
+ } else {
+ if (type instanceof WildcardType) {
+ type = ((WildcardType) type).getUpperBounds()[0];
+ }
+ typeParameters.add(new EphemeralMappedField(type, this, mapper));
+ }
+ }
+ }
+
private Class extractTypeVariable(final TypeVariable<?> type) {
final Class typeArgument = ReflectionUtils.getTypeArgument(persistedClass, type);
return typeArgument != null ? typeArgument : Object.class;
diff --git a/util/pom.xml b/util/pom.xml
index <HASH>..<HASH> 100644
--- a/util/pom.xml
+++ b/util/pom.xml
@@ -26,4 +26,14 @@
</plugins>
</build>
+ <dependencies>
+ <dependency>
+ <groupId>java</groupId>
+ <artifactId>tools</artifactId>
+ <version>${java.version}</version>
+ <scope>system</scope>
+ <systemPath>${java.home}/../lib/tools.jar</systemPath>
+ </dependency>
+ </dependencies>
+
</project>
|
readd tools.jar dep to compile taglets properly on java8
|
MorphiaOrg_morphia
|
train
|
b0d6fe0c9eed9cdc005c7d0e5020d3cf1d50e567
|
diff --git a/Gemfile.lock b/Gemfile.lock
index <HASH>..<HASH> 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,7 +1,7 @@
GEM
remote: https://rubygems.org/
specs:
- codeclimate-test-reporter (0.4.8)
+ codeclimate-test-reporter (0.5.0)
simplecov (>= 0.7.1, < 1.0.0)
docile (1.1.5)
json (1.8.3)
@@ -9,7 +9,7 @@ GEM
rack (1.6.4)
rack-test (0.6.3)
rack (>= 1.0)
- rake (10.5.0)
+ rake (11.1.2)
simplecov (0.11.2)
docile (~> 1.1.0)
json (~> 1.8)
diff --git a/test/test_basic_http_auth.rb b/test/test_basic_http_auth.rb
index <HASH>..<HASH> 100644
--- a/test/test_basic_http_auth.rb
+++ b/test/test_basic_http_auth.rb
@@ -8,7 +8,7 @@ class BasicAuthRoutesTest < RackStepTest
# Testing invalid credentials (none).
def test_access_to_protected_page_passing_no_credentials
# Requesting the protectedPage of the application.
- uri = URI.escape('/protectedPage')
+ uri = '/protectedPage'
request = @requester.get(uri)
# The response should be Unauthorized (401).
assert_equal 401, request.status
@@ -24,7 +24,7 @@ class BasicAuthRoutesTest < RackStepTest
# Testing valid credentials.
def test_access_to_protected_page_passing_right_credentials
# Requesting the protectedPage of the application.
- request = @requester.get( URI.escape('/protectedPage'),
+ request = @requester.get( '/protectedPage',
{ 'HTTP_AUTHORIZATION'=> encode_credentials('myBoringUsername', 'myBoringPassword') } )
# The response should be OK (200)
@@ -41,7 +41,7 @@ class BasicAuthRoutesTest < RackStepTest
# Testing invalid credentials (wrong username and password)
def test_access_to_protected_page_passing_wrong_credentials
# Requesting the protectedPage of the application.
- request = @requester.get( URI.escape('/protectedPage'),
+ request = @requester.get( '/protectedPage',
{ 'HTTP_AUTHORIZATION'=> encode_credentials('myWrongUsername', 'myWrongPassword') } )
# The response should be OK (200)
diff --git a/test/test_invalid_route.rb b/test/test_invalid_route.rb
index <HASH>..<HASH> 100644
--- a/test/test_invalid_route.rb
+++ b/test/test_invalid_route.rb
@@ -8,7 +8,7 @@ class InvalidRoutesTest < RackStepTest
# Test if the invalid route is returning 404.
def test_invalid_route
# Requesting an invalid page.
- request = @requester.get URI.escape('/justAnInvalidPageRoute')
+ request = @requester.get '/justAnInvalidPageRoute'
# The response should be NOT FOUND (404)
assert_equal 404, request.status
end
diff --git a/test/test_valid_routes.rb b/test/test_valid_routes.rb
index <HASH>..<HASH> 100644
--- a/test/test_valid_routes.rb
+++ b/test/test_valid_routes.rb
@@ -8,7 +8,7 @@ class ValidRoutesTest < RackStepTest
# Test if the main route is returning the expected message.
def test_main_route
# Requesting the root page of the application.
- request = @requester.get URI.escape('/')
+ request = @requester.get '/'
# The response should be OK (200)
assert_equal 200, request.status
# Content type should be HTML
@@ -20,7 +20,7 @@ class ValidRoutesTest < RackStepTest
# Test if the json route is returning the expected content.
def test_json_route
# Requesting the myJsonService page of the application.
- request = @requester.get URI.escape('/myJsonService')
+ request = @requester.get '/myJsonService'
# The response should be OK (200)
assert_equal 200, request.status
# Content type should be JSON
@@ -34,7 +34,7 @@ class ValidRoutesTest < RackStepTest
# test if render_template is working properly.
def test_render_erb_route
# Requesting the htmlPage page of the application.
- request = @requester.get URI.escape('/erbPage')
+ request = @requester.get '/erbPage'
# The response should be OK (200)
assert_equal 200, request.status
# Content type should be HTML
|
Removing URI.escape from tests
|
mfdavid_rackstep
|
train
|
a6fe3e5f7af3a28ebb2bee1b73da5114a3c75804
|
diff --git a/src/main/java/com/basho/riak/client/operations/mapreduce/BucketMapReduce.java b/src/main/java/com/basho/riak/client/operations/mapreduce/BucketMapReduce.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/basho/riak/client/operations/mapreduce/BucketMapReduce.java
+++ b/src/main/java/com/basho/riak/client/operations/mapreduce/BucketMapReduce.java
@@ -17,7 +17,7 @@ public class BucketMapReduce extends MapReduce
public static class Builder extends MapReduce.Builder<Builder>
{
- private Location bucket;
+ private Location location;
private final List<KeyFilter> filters = new ArrayList<KeyFilter>();
@Override
@@ -26,9 +26,9 @@ public class BucketMapReduce extends MapReduce
return this;
}
- public Builder withBucket(Location bucket)
+ public Builder withLocation(Location location)
{
- this.bucket = bucket;
+ this.location = location;
return this;
}
@@ -40,12 +40,12 @@ public class BucketMapReduce extends MapReduce
public BucketMapReduce build()
{
- if (bucket == null)
+ if (location == null)
{
throw new IllegalStateException("A bucket must be specified");
}
- return new BucketMapReduce(new BucketInput(bucket, filters), this);
+ return new BucketMapReduce(new BucketInput(location, filters), this);
}
}
}
|
Small change to method names.
All method names now refer to "location" rather than "bucket"
|
basho_riak-java-client
|
train
|
fa9da313621ee355b0464bb64d5447cf78fb8e1c
|
diff --git a/strict.go b/strict.go
index <HASH>..<HASH> 100644
--- a/strict.go
+++ b/strict.go
@@ -42,7 +42,7 @@ func Strict(r *http.Request, c martini.Context) {
// An empty type will allow requests with empty or missing Content-Type header.
func ContentType(ctypes ...string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
- if !checkCT(r.Header.Get("Content-Type"), ctypes...) {
+ if contentMethod(r.Method) && !checkCT(r.Header.Get("Content-Type"), ctypes...) {
w.WriteHeader(http.StatusUnsupportedMediaType)
}
}
@@ -55,7 +55,7 @@ func ContentCharset(charsets ...string) http.HandlerFunc {
charsets[i] = strings.ToLower(c)
}
return func(w http.ResponseWriter, r *http.Request) {
- if !checkCC(r.Header.Get("Content-Type"), charsets...) {
+ if contentMethod(r.Method) && !checkCC(r.Header.Get("Content-Type"), charsets...) {
w.WriteHeader(http.StatusUnsupportedMediaType)
}
}
@@ -159,6 +159,12 @@ func checkCC(ce string, charsets ...string) bool {
return false
}
+// Check if the request method can contain a content
+func contentMethod(m string) bool {
+ // No Content-Type for GET, HEAD, OPTIONS, DELETE and CONNECT requests.
+ return m == "POST" || m == "PATCH" || m == "PUT"
+}
+
// Split a string in two parts, cleaning any whitespace.
func split(str, sep string) (a, b string) {
parts := strings.SplitN(str, sep, 2)
|
only check content-type for POST, PATCH and PUT requests
|
martini-contrib_strict
|
train
|
5b3e4ffe15b6499be7da23246985b99b61b8c567
|
diff --git a/lib/rules/indentation.js b/lib/rules/indentation.js
index <HASH>..<HASH> 100644
--- a/lib/rules/indentation.js
+++ b/lib/rules/indentation.js
@@ -78,6 +78,8 @@ module.exports = {
node.body.forEach (inspectProgramChild);
});
+
+
//Ensure level 1 indentation before all immediate children of top-level declarations
topLevelDeclarations.forEach (function (event) {
@@ -123,6 +125,8 @@ module.exports = {
});
+
+
//Ensure 1 extra indentation inside Block than before it
context.on ('BlockStatement', function (emitted) {
var node = emitted.node;
@@ -183,8 +187,9 @@ module.exports = {
node.body.forEach (inspectBlockItem.bind (null, blockIndent));
});
- context.on ('StructDeclaration', function (emitted) {
+
+ context.on ('StructDeclaration', function (emitted) {
var node = emitted.node,
body = node.body || [],
endingLineNum = sourceCode.getEndingLine (node);
@@ -233,6 +238,54 @@ module.exports = {
});
+
+
+ context.on ('ArrayExpression', function (emitted) {
+ var node = emitted.node, elements = node.elements;
+ var endingLineNum = sourceCode.getEndingLine (node),
+ arrayExpressionLineText, currentIndent, currentIndentLevel, arrayIndent;
+ var MAX_ELEMS_IN_SINGLE_LINE = 3;
+
+ function inspectElement (arrayIndent, elem) {
+ var indentRegExp = new RegExp ('^' + arrayIndent + '[^\\s(\/\*)]'),
+ elemLineText = sourceCode.getTextOnLine (sourceCode.getLine (elem));
+
+ //element declaration must be preceded by only correct level of indentation & no comments
+ !indentRegExp.test (elemLineText) && context.report ({
+ node: elem,
+ message: 'Incorrect Indentation: Make sure you use exacly \"' + arrayIndent + '\" for indentation on this line and don\'t preceed the declaration by comment(s).'
+ });
+ }
+
+ if (emitted.exit) {
+ return;
+ }
+
+ if (elements.length > MAX_ELEMS_IN_SINGLE_LINE && sourceCode.getLine (node) === endingLineNum) {
+ return context.report ({
+ node: node,
+ message: 'In case of more than 3 elements, array expression needs to be spread over multiple lines with 1 element per line.'
+ });
+ }
+
+ arrayExpressionLineText = sourceCode.getTextOnLine (sourceCode.getLine (node));
+
+ currentIndent = arrayExpressionLineText.slice (
+ 0,
+ arrayExpressionLineText.indexOf (arrayExpressionLineText.trim ())
+ );
+
+ currentIndentLevel = (currentIndent.match (BASE_INDENTATION_STYLE_REGEXP_GLOBAL) || []).length;
+
+ //ensure that there is only whitespace of correct level on the line containing array expression
+ if (getIndentString (BASE_INDENTATION_STYLE, currentIndentLevel) !== currentIndent) {
+ return; //exit now, we can' proceed further unless this is fixed
+ }
+
+ arrayIndent = getIndentString (BASE_INDENTATION_STYLE, currentIndentLevel + 1);
+ elements.forEach (inspectElement.bind (null, arrayIndent));
+ });
+
}
};
\ No newline at end of file
|
indentation: ArrayExpression
|
duaraghav8_Ethlint
|
train
|
788d7f2211b3990df420a79492556ae24d113de1
|
diff --git a/nodeconductor/iaas/tests/test_provisioning.py b/nodeconductor/iaas/tests/test_provisioning.py
index <HASH>..<HASH> 100644
--- a/nodeconductor/iaas/tests/test_provisioning.py
+++ b/nodeconductor/iaas/tests/test_provisioning.py
@@ -904,6 +904,19 @@ class InstanceListRetrieveTest(test.APITransactionTestCase):
self.assertEqual(len(response.data['backups']), 1)
self.assertEqual(response.data['backups'][0]['url'], backup_factories.BackupFactory.get_url(backup))
+ def test_descending_sort_by_start_time_puts_instances_with_null_value_last(self):
+ self.client.force_authenticate(self.staff)
+
+ factories.InstanceFactory.create_batch(2, start_time=None)
+ factories.InstanceFactory()
+
+ response = self.client.get(factories.InstanceFactory.get_list_url(),
+ data={'o': 'start_time'})
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ for i in (-1, -2):
+ self.assertEqual(response.data[i]['start_time'], None)
+
class InstanceUsageTest(test.APITransactionTestCase):
diff --git a/nodeconductor/iaas/views.py b/nodeconductor/iaas/views.py
index <HASH>..<HASH> 100644
--- a/nodeconductor/iaas/views.py
+++ b/nodeconductor/iaas/views.py
@@ -7,7 +7,7 @@ import time
from django.db import models as django_models
-from django.db.models import Sum
+from django.db.models import Sum, Count
from django.http import Http404
from django.shortcuts import get_object_or_404
import django_filters
@@ -116,7 +116,6 @@ class InstanceFilter(django_filters.FilterSet):
'-hostname',
'state',
'-state',
- 'start_time',
'-start_time',
'cloud_project_membership__project__customer__name',
'-cloud_project_membership__project__customer__name',
@@ -174,6 +173,16 @@ class InstanceViewSet(mixins.CreateModelMixin,
permission_classes = (permissions.IsAuthenticated, permissions.DjangoObjectPermissions)
filter_class = InstanceFilter
+ def get_queryset(self):
+ queryset = super(InstanceViewSet, self).get_queryset()
+
+ order = self.request.QUERY_PARAMS.get('o', None)
+ if order == 'start_time':
+ # http://stackoverflow.com/questions/5235209/
+ queryset = queryset.annotate(is_null=Count('start_time')).order_by('-is_null', 'start_time')
+
+ return queryset
+
def get_serializer_class(self):
if self.request.method == 'POST':
return serializers.InstanceCreateSerializer
@@ -259,6 +268,9 @@ class InstanceViewSet(mixins.CreateModelMixin,
from nodeconductor.iaas.tasks import push_instance_security_groups
push_instance_security_groups.delay(self.object.uuid.hex)
+ def order_start_time(self, queryset, o=None):
+ return
+
def change_flavor(self, instance, flavor):
instance_cloud = instance.cloud_project_membership.cloud
|
Fix instances desc sort by start time
ITACLOUD-<I>
|
opennode_waldur-core
|
train
|
e6fdeea2f08cfe16a82dc0345954eb1edf700e12
|
diff --git a/src/Lib/Parser/AnimePicturesParse.php b/src/Lib/Parser/AnimePicturesParse.php
index <HASH>..<HASH> 100755
--- a/src/Lib/Parser/AnimePicturesParse.php
+++ b/src/Lib/Parser/AnimePicturesParse.php
@@ -24,7 +24,7 @@ class AnimePicturesParse extends TemplateParse
while(true) {
$line = $this->file[$this->lineNo + $i];
- if (preg_match('~<div class="fl-l">~', $line)) {
+ if (preg_match('~<div style="clear:both;"></div>~', $line)) {
break;
}
diff --git a/src/Lib/Parser/CharacterPicturesParse.php b/src/Lib/Parser/CharacterPicturesParse.php
index <HASH>..<HASH> 100755
--- a/src/Lib/Parser/CharacterPicturesParse.php
+++ b/src/Lib/Parser/CharacterPicturesParse.php
@@ -24,7 +24,7 @@ class CharacterPicturesParse extends TemplateParse
while(true) {
$line = $this->file[$this->lineNo + $i];
- if (preg_match('~<div class="fl-l">~', $line)) {
+ if (preg_match('~<div style="clear:both;"></div>~', $line)) {
break;
}
diff --git a/src/Lib/Parser/MangaPicturesParse.php b/src/Lib/Parser/MangaPicturesParse.php
index <HASH>..<HASH> 100755
--- a/src/Lib/Parser/MangaPicturesParse.php
+++ b/src/Lib/Parser/MangaPicturesParse.php
@@ -24,7 +24,7 @@ class MangaPicturesParse extends TemplateParse
while(true) {
$line = $this->file[$this->lineNo + $i];
- if (preg_match('~<div class="fl-l">~', $line)) {
+ if (preg_match('~<div style="clear:both;"></div>~', $line)) {
break;
}
diff --git a/src/Lib/Parser/PersonPicturesParse.php b/src/Lib/Parser/PersonPicturesParse.php
index <HASH>..<HASH> 100755
--- a/src/Lib/Parser/PersonPicturesParse.php
+++ b/src/Lib/Parser/PersonPicturesParse.php
@@ -24,7 +24,7 @@ class PersonPicturesParse extends TemplateParse
while(true) {
$line = $this->file[$this->lineNo + $i];
- if (preg_match('~<div class="fl-l">~', $line)) {
+ if (preg_match('~<div style="clear:both;"></div>~', $line)) {
break;
}
|
patch extended request `pictures` parsing for some clients #<I>
|
jikan-me_jikan
|
train
|
196b4101f0dd0a8a19c99fbb3eb52b4e59dae37e
|
diff --git a/packages/enzyme-adapter-react-16.3/src/ReactSixteenThreeAdapter.js b/packages/enzyme-adapter-react-16.3/src/ReactSixteenThreeAdapter.js
index <HASH>..<HASH> 100644
--- a/packages/enzyme-adapter-react-16.3/src/ReactSixteenThreeAdapter.js
+++ b/packages/enzyme-adapter-react-16.3/src/ReactSixteenThreeAdapter.js
@@ -417,26 +417,26 @@ class ReactSixteenThreeAdapter extends EnzymeAdapter {
displayNameOfNode(node) {
if (!node) return null;
const { type, $$typeof } = node;
-
+
const nodeType = type || $$typeof;
// newer node types may be undefined, so only test if the nodeType exists
if (nodeType) {
switch (nodeType) {
- case AsyncMode: return 'AsyncMode';
- case Fragment: return 'Fragment';
- case StrictMode: return 'StrictMode';
- case Profiler: return 'Profiler';
- case Portal: return 'Portal';
+ case AsyncMode || NaN: return 'AsyncMode';
+ case Fragment || NaN: return 'Fragment';
+ case StrictMode || NaN: return 'StrictMode';
+ case Profiler || NaN: return 'Profiler';
+ case Portal || NaN: return 'Portal';
}
}
const $$typeofType = type && type.$$typeof;
switch ($$typeofType) {
- case ContextConsumer: return 'ContextConsumer';
- case ContextProvider: return 'ContextProvider';
- case ForwardRef: {
+ case ContextConsumer || NaN: return 'ContextConsumer';
+ case ContextProvider || NaN: return 'ContextProvider';
+ case ForwardRef || NaN: {
const name = type.render.displayName || functionName(type.render);
return name ? `ForwardRef(${name})` : 'ForwardRef';
}
diff --git a/packages/enzyme-adapter-react-16/src/ReactSixteenAdapter.js b/packages/enzyme-adapter-react-16/src/ReactSixteenAdapter.js
index <HASH>..<HASH> 100644
--- a/packages/enzyme-adapter-react-16/src/ReactSixteenAdapter.js
+++ b/packages/enzyme-adapter-react-16/src/ReactSixteenAdapter.js
@@ -417,26 +417,30 @@ class ReactSixteenAdapter extends EnzymeAdapter {
if (!node) return null;
const { type, $$typeof } = node;
- switch (type || $$typeof) {
- case AsyncMode: return 'AsyncMode';
- case Fragment: return 'Fragment';
- case StrictMode: return 'StrictMode';
- case Profiler: return 'Profiler';
- case Portal: return 'Portal';
-
- default: {
- const $$typeofType = type && type.$$typeof;
-
- switch ($$typeofType) {
- case ContextConsumer: return 'ContextConsumer';
- case ContextProvider: return 'ContextProvider';
- case ForwardRef: {
- const name = type.render.displayName || functionName(type.render);
- return name ? `ForwardRef(${name})` : 'ForwardRef';
- }
- default: return displayNameOfNode(node);
- }
+ const nodeType = type || $$typeof;
+
+ // newer node types may be undefined, so only test if the nodeType exists
+ if (nodeType) {
+ switch (nodeType) {
+ case AsyncMode || NaN: return 'AsyncMode';
+ case Fragment || NaN: return 'Fragment';
+ case StrictMode || NaN: return 'StrictMode';
+ case Profiler || NaN: return 'Profiler';
+ case Portal || NaN: return 'Portal';
+ default:
+ }
+ }
+
+ const $$typeofType = type && type.$$typeof;
+
+ switch ($$typeofType) {
+ case ContextConsumer || NaN: return 'ContextConsumer';
+ case ContextProvider || NaN: return 'ContextProvider';
+ case ForwardRef || NaN: {
+ const name = type.render.displayName || functionName(type.render);
+ return name ? `ForwardRef(${name})` : 'ForwardRef';
}
+ default: return displayNameOfNode(node);
}
}
|
Use `|| NaN` to ensure missing React properties do not match
|
airbnb_enzyme
|
train
|
7a2be131bd675769bfdb2e19731d58b434c892e7
|
diff --git a/helpers/postgresql.py b/helpers/postgresql.py
index <HASH>..<HASH> 100644
--- a/helpers/postgresql.py
+++ b/helpers/postgresql.py
@@ -1,6 +1,7 @@
import logging
import os
import psycopg2
+import shutil
import subprocess
import sys
import time
@@ -43,6 +44,7 @@ class Postgresql:
self.superuser = config['superuser']
self.admin = config['admin']
self.recovery_conf = os.path.join(self.data_dir, 'recovery.conf')
+ self.postgresql_conf = os.path.join(self.data_dir, 'postgresql.conf')
self._pg_ctl = 'pg_ctl -w -D ' + self.data_dir
self._wal_e = 'envdir {} wal-e --aws-instance-profile '.format(os.environ.get('WALE_ENV_DIR', '/home/postgres/etc/wal-e.d/env'))
@@ -89,7 +91,8 @@ class Postgresql:
return not os.path.exists(self.data_dir) or os.listdir(self.data_dir) == []
def initialize(self):
- if os.system(self._pg_ctl + ' initdb -o --encoding=UTF8') == 0:
+ if os.system(self._pg_ctl + ' initdb') == 0:
+ self.save_postgresql_conf()
self.write_pg_hba()
return True
@@ -122,7 +125,10 @@ class Postgresql:
data_dir=self.data_dir, **master_connection))
def create_replica_with_s3(self):
- return os.system(self._wal_e + ' backup-fetch {} LATEST'.format(self.data_dir))
+ ret = os.system(self._wal_e + ' backup-fetch {} LATEST'.format(self.data_dir))
+ self.restore_postgresql_conf()
+ return ret
+
def should_use_s3_to_create_replica(self, master_connurl):
""" determine whether it makes sense to use S3 and not pg_basebackup """
@@ -296,6 +302,20 @@ primary_conninfo = '{}'
self.write_recovery_conf(leader)
self.restart()
+ def save_posgresql_conf(self):
+ """
+ copy postgresql.conf to postgresql.conf.backup to preserve it in the WAL-e backup.
+ see http://comments.gmane.org/gmane.comp.db.postgresql.wal-e/239
+ """
+ shutil.copy(self.postgresql_conf, self.postgresql_conf+'.backup')
+
+ def restore_postgresql_conf(self):
+ """ restore a previously saved postgresql.conf """
+ try:
+ shutil.copy(self.postgresql_conf+'.backup', self.postgresql_conf)
+ except Exception as e:
+ logger.error("unable to restore postgresql.conf from WAL-E backup: {}".format(e))
+
def promote(self):
return os.system(self._pg_ctl + ' promote') == 0
|
save/restore postgresql.conf for WAL-e backups, since WAL-E excludes postgresql.conf from the backup/restore.
|
zalando_patroni
|
train
|
f7e4be1b9ec04f2f143722ab60f6dad3e96d3412
|
diff --git a/spec/unit/3scale_toolbox_spec.rb b/spec/unit/3scale_toolbox_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/3scale_toolbox_spec.rb
+++ b/spec/unit/3scale_toolbox_spec.rb
@@ -6,24 +6,22 @@ RSpec.describe ThreeScaleToolbox do
include_context :random_name
let(:name) { random_lowercase_name }
- let(:dest_plugin_file) { File.join(tmp_dir, '3scale_toolbox_plugin.rb') }
+ let(:dest_plugin_file) { tmp_dir.join('3scale_toolbox_plugin.rb') }
around(:each) do |example|
plugin = get_plugin_content(name.capitalize, name)
- File.open(dest_plugin_file, 'w') do |file|
- file.write(plugin)
- end
+ dest_plugin_file.write(plugin)
$LOAD_PATH.unshift(tmp_dir) unless $LOAD_PATH.include?(tmp_dir)
example.run
$LOAD_PATH.delete(tmp_dir)
end
it '.plugin_paths finds plugin' do
- expect(described_class.plugin_paths).to include(dest_plugin_file)
+ expect(described_class.plugin_paths).to include(dest_plugin_file.to_s)
end
it '.load_plugins loads plugin' do
expect { described_class.load_plugins }.not_to raise_error
- expect(Object.const_get(name.capitalize.to_sym)).not_to be_nil
+ expect(Object.const_get(name.capitalize.to_sym)).to be_a_kind_of(ThreeScaleToolbox::Command)
end
end
|
spec/unit/3scale_toolbox_spec: tmp dir as pathname object
|
3scale_3scale_toolbox
|
train
|
dc2926db1d0ed4816932a2001e0ba0c29bbb62c7
|
diff --git a/lib/Post.php b/lib/Post.php
index <HASH>..<HASH> 100644
--- a/lib/Post.php
+++ b/lib/Post.php
@@ -689,47 +689,52 @@ class Post extends Core implements CoreInterface {
}
}
- $term_class_objects = array();
-
- foreach ( $taxonomies as $taxonomy ) {
- // @todo Remove in 2.x
+ // @todo Remove in 2.x
+ $taxonomies = array_map( function( $taxonomy ) {
if ( in_array( $taxonomy, array( 'tag', 'tags' ), true ) ) {
$taxonomy = 'post_tag';
} elseif ( 'categories' === $taxonomy ) {
$taxonomy = 'category';
}
- // Maybe this is not needed?
- if ( isset( $args['query']['taxonomy'] ) ) {
- unset( $args['query']['taxonomy'] );
- }
+ return $taxonomy;
+ }, $taxonomies );
- $terms = wp_get_post_terms( $this->ID, $taxonomy, $args['query'] );
+ $terms = wp_get_post_terms( $this->ID, $taxonomies, $args['query'] );
- if ( is_wp_error( $terms ) ) {
- /**
- * @var $terms \WP_Error
- */
- Helper::error_log("Error retrieving terms for taxonomy '$taxonomy' on a post in timber-post.php");
- Helper::error_log('tax = '.print_r($tax, true));
- Helper::error_log('WP_Error: '.$terms->get_error_message());
+ if ( is_wp_error( $terms ) ) {
+ /**
+ * @var $terms \WP_Error
+ */
+ Helper::error_log( "Error retrieving terms for taxonomies on a post in timber-post.php" );
+ Helper::error_log( 'tax = ' . print_r( $tax, true ) );
+ Helper::error_log( 'WP_Error: ' . $terms->get_error_message() );
- return $term_class_objects;
- }
+ return $terms;
+ }
- // Map over array of WordPress terms and transform them into instances of the chosen term class.
- $terms = array_map(function( $term ) use ($term_class, $taxonomy) {
- return call_user_func(array($term_class, 'from'), $term->term_id, $taxonomy);
- }, $terms);
+ // Map over array of WordPress terms and transform them into instances of the chosen term class.
+ $terms = array_map( function( $term ) use ( $term_class ) {
+ return call_user_func( array( $term_class, 'from' ), $term->term_id, $term->taxonomy );
+ }, $terms );
- if ( $merge && is_array($terms) ) {
- $term_class_objects = array_merge($term_class_objects, $terms);
- } else if ( count($terms) ) {
- $term_class_objects[$taxonomy] = $terms;
+ if ( ! $merge ) {
+ $terms_sorted = array();
+
+ // Initialize sub-arrays.
+ foreach ( $taxonomies as $taxonomy ) {
+ $terms_sorted[ $taxonomy ] = array();
+ }
+
+ // Fill terms into arrays.
+ foreach ( $terms as $term ) {
+ $terms_sorted[ $term->taxonomy ][] = $term;
}
+
+ return $terms_sorted;
}
- return $term_class_objects;
+ return $terms;
}
/**
|
Make merge argument work with term query arguments
|
timber_timber
|
train
|
9d5800ea49730dab04d187a6a492cc3262598508
|
diff --git a/angular-moment.js b/angular-moment.js
index <HASH>..<HASH> 100644
--- a/angular-moment.js
+++ b/angular-moment.js
@@ -87,4 +87,17 @@ angular.module('angularMoment', [])
return $window.moment(value).format(format);
};
+ }]).filter('amDurationFormat', ['$window', function ($window) {
+ 'use strict';
+
+ return function (value, format, suffix) {
+ if (typeof value === 'undefined' || value === null) {
+ return '';
+ }
+ /*if (!isNaN(parseFloat(value)) && isFinite(value)) {
+ return '';
+ }*/
+ // else assume the given value is already a duration in a format (miliseconds, etc)
+ return $window.moment.duration(value, format).humanize(suffix);
+ };
}]);
diff --git a/tests.js b/tests.js
index <HASH>..<HASH> 100644
--- a/tests.js
+++ b/tests.js
@@ -204,6 +204,50 @@ describe('module angularMoment', function () {
});
});
+ describe('amDurationFormat filter', function () {
+ it('should support displaying format in milliseconds', function () {
+ $rootScope.testDate = 1000;
+ var element = angular.element('<span>{{testDate|amDurationFormat:\'milliseconds\'}}</span>');
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect(element.text()).toBe('a few seconds');
+ });
+
+ it('should support give a day with 24 hours', function () {
+ $rootScope.testDate = 24;
+ var element = angular.element('<span>{{testDate|amDurationFormat:\'hours\'}}</span>');
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect(element.text()).toBe('a day');
+ });
+
+ it('should support suffix or not within duration: 1 minute', function () {
+ $rootScope.testDate = 1;
+ var element = angular.element('<span>{{testDate|amDurationFormat:\'minutes\':true}}</span>');
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect(element.text()).toBe('in a minute');
+ });
+
+ it('should support suffix or not within a negative duration: 1 minute', function () {
+ $rootScope.testDate = -1;
+ var element = angular.element('<span>{{testDate|amDurationFormat:\'minutes\':true}}</span>');
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect(element.text()).toBe('a minute ago');
+ });
+
+ it('should gracefully handle undefined values for duration', function () {
+ var element = angular.element('<span>{{testDate|amDurationFormat:\'D.M.YYYY\'}}</span>');
+ element = $compile(element)($rootScope);
+ $rootScope.$digest();
+ expect(element.text()).toBe('');
+ });
+
+
+ });
+
+
describe('amTimeAgoConfig constant', function () {
it('should generate time with suffix by default', function () {
expect(amTimeAgoConfig.withoutSuffix).toBe(false);
|
adding amDuration filter closes #<I>
|
urish_angular-moment
|
train
|
8bc91e7322252dbdfab938d20c4f0f221d1fcb70
|
diff --git a/docs/source/conf.py b/docs/source/conf.py
index <HASH>..<HASH> 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -64,9 +64,9 @@ author = u'John Vinyard'
# built documents.
#
# The short X.Y version.
-version = '0.20.12'
+version = '0.46.0'
# The full version, including alpha/beta/rc tags.
-release = '0.20.12'
+release = '0.46.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@@ -326,6 +326,11 @@ MOCK_MODULES = [
'matplotlib',
'zounds.nputil.countbits',
+
+ 'torch',
+ 'torch.nn',
+ 'torch.optim',
+ 'torch.autograd'
]
|
See if I can get the docs to build
|
JohnVinyard_zounds
|
train
|
df88df7f314b1dda87b59197fa5dc4a40c6cacea
|
diff --git a/src/Commands/Init.php b/src/Commands/Init.php
index <HASH>..<HASH> 100644
--- a/src/Commands/Init.php
+++ b/src/Commands/Init.php
@@ -33,7 +33,7 @@ class Init extends Command
`id` int(11) NOT NULL AUTO_INCREMENT,
`version` char(3) COLLATE utf8_unicode_ci NOT NULL,
`author` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
- `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
+ `description` text COLLATE utf8_unicode_ci NOT NULL,
`filename` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
diff --git a/src/Commands/Listing.php b/src/Commands/Listing.php
index <HASH>..<HASH> 100644
--- a/src/Commands/Listing.php
+++ b/src/Commands/Listing.php
@@ -37,13 +37,14 @@ class Listing extends Command
'id' => $migration->id,
'version' => $migration->version,
'author' => $migration->author,
- 'description' => $migration->description,
- 'created at' => $migration->created_at,
- 'updated at' => $migration->updated_at,
+ 'description' => wordwrap($migration->description, 30),
+ 'created at' => substr($migration->created_at, 0, 10),
+ 'updated at' => substr($migration->updated_at, 0, 10),
];
}
$table = new Table($output);
+ $table->setColumnWidths(array(3, 5, 10, 30));
$table
->setHeaders(['Id', 'Version', 'Author', 'Description', 'Created At', 'Updated At'])
->setRows($datas);
|
Migration description to text. A better migrate:list
|
groovey_Migration
|
train
|
e3525d2433655d6ff726c4983ccbf659a50afe69
|
diff --git a/lib/kpeg/compiled_parser.rb b/lib/kpeg/compiled_parser.rb
index <HASH>..<HASH> 100644
--- a/lib/kpeg/compiled_parser.rb
+++ b/lib/kpeg/compiled_parser.rb
@@ -32,8 +32,8 @@ module KPeg
end
attr_reader :string
- attr_reader :result, :failing_rule_offset
- attr_accessor :pos
+ attr_reader :failing_rule_offset
+ attr_accessor :result, :pos
include Position
@@ -218,6 +218,7 @@ module KPeg
begin
if val = __send__(rule, *args)
other.pos = @pos
+ other.result = @result
else
other.set_failed_rule "#{self.class}##{rule}"
end
|
Fix result not making it back to the external invoker
|
evanphx_kpeg
|
train
|
360887fb28375a045732cfa8c29f53a2da01fd6d
|
diff --git a/.travis.yml b/.travis.yml
index <HASH>..<HASH> 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,5 +1,7 @@
language: node_js
node_js:
+ - "iojs"
+ - "0.12"
- "0.10"
- "0.8"
notifications:
diff --git a/lib/resource.js b/lib/resource.js
index <HASH>..<HASH> 100644
--- a/lib/resource.js
+++ b/lib/resource.js
@@ -67,9 +67,9 @@ Resource.prototype.get = function(cb) {
uri = this.apiDomain + '/' + this.API_VERSION + '/public/' + lower(this.resource)
qs = merge({
- apikey: this.publicKey
- , ts: ts
- , hash: this.hash(ts)
+ apikey: this.publicKey
+ , ts: ts
+ , hash: this.hash(ts)
}, this.param)
req = {
@@ -98,12 +98,12 @@ Resource.prototype.limit = function() {
}
resources = [
- 'Comic'
-, 'Character'
-, 'Creator'
-, 'Event'
-, 'Series'
-, 'Story'
+ 'Comic'
+ , 'Character'
+ , 'Creator'
+ , 'Event'
+ , 'Series'
+ , 'Story'
]
for (var i = 0; i < resources.length; i++) {
diff --git a/test/resource.js b/test/resource.js
index <HASH>..<HASH> 100644
--- a/test/resource.js
+++ b/test/resource.js
@@ -18,14 +18,14 @@ describe('Resource', function() {
})
resourceCalls = [
- 'issueNumber'
- , 'name'
- , 'nameStartsWith'
- , 'offset'
- , 'orderBy'
- , 'startYear'
- , 'title'
- , 'titleStartsWith'
+ 'issueNumber'
+ , 'name'
+ , 'nameStartsWith'
+ , 'offset'
+ , 'orderBy'
+ , 'startYear'
+ , 'title'
+ , 'titleStartsWith'
]
for (var i = 0; i < resourceCalls.length; i++) {
|
Add <I> and iojs to travis testing
|
swang_marvel
|
train
|
b26dd9e3a0da42650ab19fed88447274d418f25b
|
diff --git a/bin/milestoner b/bin/milestoner
index <HASH>..<HASH> 100755
--- a/bin/milestoner
+++ b/bin/milestoner
@@ -5,5 +5,5 @@ require "milestoner"
require "milestoner/cli"
require "milestoner/identity"
-Process.setproctitle Milestoner::Identity.version_label
+Process.setproctitle Milestoner::Identity::VERSION_LABEL
Milestoner::CLI.start
diff --git a/lib/milestoner/cli.rb b/lib/milestoner/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/milestoner/cli.rb
+++ b/lib/milestoner/cli.rb
@@ -9,10 +9,10 @@ module Milestoner
class CLI < Thor
include Thor::Actions
- package_name Identity.version_label
+ package_name Identity::VERSION_LABEL
def self.configuration
- Runcom::Config.new "#{Identity.name}/configuration.yml",
+ Runcom::Config.new "#{Identity::NAME}/configuration.yml",
defaults: {
git_commit_prefixes: %w[Fixed Added Updated Removed Refactored],
git_tag_sign: false
@@ -100,7 +100,7 @@ module Milestoner
desc "-v, [--version]", "Show gem version."
map %w[-v --version] => :version
def version
- say Identity.version_label
+ say Identity::VERSION_LABEL
end
desc "-h, [--help=COMMAND]", "Show this message or get help for a command."
diff --git a/lib/milestoner/identity.rb b/lib/milestoner/identity.rb
index <HASH>..<HASH> 100644
--- a/lib/milestoner/identity.rb
+++ b/lib/milestoner/identity.rb
@@ -3,20 +3,9 @@
module Milestoner
# Gem identity information.
module Identity
- def self.name
- "milestoner"
- end
-
- def self.label
- "Milestoner"
- end
-
- def self.version
- "10.0.2"
- end
-
- def self.version_label
- "#{label} #{version}"
- end
+ NAME = "milestoner"
+ LABEL = "Milestoner"
+ VERSION = "10.0.2"
+ VERSION_LABEL = "#{LABEL} #{VERSION}"
end
end
diff --git a/lib/milestoner/tagger.rb b/lib/milestoner/tagger.rb
index <HASH>..<HASH> 100644
--- a/lib/milestoner/tagger.rb
+++ b/lib/milestoner/tagger.rb
@@ -103,7 +103,7 @@ module Milestoner
# :reek:BooleanParameter
# :reek:TooManyStatements
def git_tag sign: false
- message_file = Tempfile.new Identity.name
+ message_file = Tempfile.new Identity::NAME
File.open(message_file, "w") { |file| file.write git_message }
status = system "git tag #{git_options message_file, sign: sign}"
fail Errors::Git, "Unable to create tag: #{@version}." unless status
diff --git a/milestoner.gemspec b/milestoner.gemspec
index <HASH>..<HASH> 100644
--- a/milestoner.gemspec
+++ b/milestoner.gemspec
@@ -3,8 +3,8 @@
require_relative "lib/milestoner/identity"
Gem::Specification.new do |spec|
- spec.name = Milestoner::Identity.name
- spec.version = Milestoner::Identity.version
+ spec.name = Milestoner::Identity::NAME
+ spec.version = Milestoner::Identity::VERSION
spec.platform = Gem::Platform::RUBY
spec.authors = ["Brooke Kuhlmann"]
spec.email = ["brooke@alchemists.io"]
diff --git a/spec/lib/milestoner/cli_spec.rb b/spec/lib/milestoner/cli_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/milestoner/cli_spec.rb
+++ b/spec/lib/milestoner/cli_spec.rb
@@ -133,13 +133,13 @@ RSpec.describe Milestoner::CLI do
shared_examples_for "a version command" do
it "prints version" do
result = -> { cli }
- expect(&result).to output(/#{Milestoner::Identity.version_label}\n/).to_stdout
+ expect(&result).to output(/#{Milestoner::Identity::VERSION_LABEL}\n/).to_stdout
end
end
shared_examples_for "a help command" do
it "prints usage" do
- regex = /#{Milestoner::Identity.version_label}\scommands:\n/
+ regex = /#{Milestoner::Identity::VERSION_LABEL}\scommands:\n/
result = -> { cli }
expect(&result).to output(regex).to_stdout
|
Updated gem identity to use constants
Reduces lines of code and mimics behavior found when using Bundler so
code style differs less for those switching from Bundler to Gemsmith.
|
bkuhlmann_milestoner
|
train
|
5e8e6eb399ac665f305eee8233f309ec2beaaea0
|
diff --git a/user/view.php b/user/view.php
index <HASH>..<HASH> 100644
--- a/user/view.php
+++ b/user/view.php
@@ -39,7 +39,11 @@
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context
}
$usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context
-
+
+ // make sure user can view this student's profile
+ if ($USER->id != $user->id && !has_capability('moodle/user:viewdetails', $coursecontext) && !has_capability('moodle/user:viewdetails', $usercontext)) {
+ error('You can not view the profile of this user');
+ }
if (!empty($CFG->forceloginforprofiles)) {
require_login();
|
merged fix for MDL-<I>, preventing users with no capability to view user profiles
|
moodle_moodle
|
train
|
054d90e6121a1387894861b9cd2c372d1c62bdc9
|
diff --git a/client/lib/domains/dns/index.js b/client/lib/domains/dns/index.js
index <HASH>..<HASH> 100644
--- a/client/lib/domains/dns/index.js
+++ b/client/lib/domains/dns/index.js
@@ -61,6 +61,11 @@ function isValidName( name, type, selectedDomainName ) {
isValidCname( name, selectedDomainName ) &&
isValidDomainName( name, type )
);
+ case 'SRV':
+ return (
+ name === '' ||
+ isValidDomainName( name, type )
+ );
default:
return isValidDomainName( name, type );
}
|
Domains: DNS: allow empty name in SRV records
This is needed, for example, for Office <I>.
|
Automattic_wp-calypso
|
train
|
c1a1701014c131bb60d569c5cc33b7d6f177c2ba
|
diff --git a/server/src/main/java/io/atomix/copycat/server/state/MemberState.java b/server/src/main/java/io/atomix/copycat/server/state/MemberState.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/io/atomix/copycat/server/state/MemberState.java
+++ b/server/src/main/java/io/atomix/copycat/server/state/MemberState.java
@@ -123,4 +123,9 @@ class MemberState {
return this;
}
+ @Override
+ public String toString() {
+ return address.toString();
+ }
+
}
diff --git a/server/src/main/java/io/atomix/copycat/server/state/ServerState.java b/server/src/main/java/io/atomix/copycat/server/state/ServerState.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/io/atomix/copycat/server/state/ServerState.java
+++ b/server/src/main/java/io/atomix/copycat/server/state/ServerState.java
@@ -205,7 +205,7 @@ public class ServerState {
Assert.state(address != null, "unknown leader: ", leader);
this.leader = leader;
this.lastVotedFor = 0;
- LOGGER.debug("{} - Found leader {}", this.address, address);
+ LOGGER.info("{} - Found leader {}", this.address, address);
electionListeners.forEach(l -> l.accept(address));
}
} else if (leader != 0) {
@@ -214,7 +214,7 @@ public class ServerState {
Assert.state(address != null, "unknown leader: ", leader);
this.leader = leader;
this.lastVotedFor = 0;
- LOGGER.debug("{} - Found leader {}", this.address, address);
+ LOGGER.info("{} - Found leader {}", this.address, address);
electionListeners.forEach(l -> l.accept(address));
}
} else {
|
Minor improvements to server logging formatting.
|
atomix_copycat
|
train
|
7a021245b849ded77527337b0a86620bd5412260
|
diff --git a/src/ElementalEditor.php b/src/ElementalEditor.php
index <HASH>..<HASH> 100644
--- a/src/ElementalEditor.php
+++ b/src/ElementalEditor.php
@@ -70,6 +70,18 @@ class ElementalEditor
}
/**
+ * @return array
+ */
+ public function getTypes()
+ {
+ $types = $this->types;
+
+ $this->extend('updateGetTypes', $types);
+
+ return $types;
+ }
+
+ /**
* @return ElementalArea
*/
public function getArea()
@@ -113,7 +125,7 @@ class ElementalEditor
if ($this->types) {
$adder = Injector::inst()->create(ElementalGridFieldAddNewMultiClass::class, 'toolbar-header-left');
- $adder->setClasses($this->types);
+ $adder->setClasses($this->getTypes());
$config->addComponent($adder);
}
|
NEW Allow ElementEditor extensions to customise the type
|
dnadesign_silverstripe-elemental
|
train
|
a003d84258faed397a1dba2ed9134a34795205fd
|
diff --git a/bloop/condition.py b/bloop/condition.py
index <HASH>..<HASH> 100644
--- a/bloop/condition.py
+++ b/bloop/condition.py
@@ -55,8 +55,15 @@ class ConditionRenderer:
def name_ref(self, column, path=None):
pieces = [column.dynamo_name]
pieces.extend(path or [])
- refs = map(self._name_ref, pieces)
- return ".".join(refs)
+ str_pieces = []
+ for piece in pieces:
+ # List indexes are attached to last path item directly
+ if isinstance(piece, int):
+ str_pieces[-1] += "[{}]".format(piece)
+ # Path keys are attached with a "."
+ else:
+ str_pieces.append(self._name_ref(piece))
+ return ".".join(str_pieces)
def refs(self, pair):
""" Return (#n0, #v1) tuple for a given (column, value) pair """
diff --git a/tests/test_condition.py b/tests/test_condition.py
index <HASH>..<HASH> 100644
--- a/tests/test_condition.py
+++ b/tests/test_condition.py
@@ -224,8 +224,8 @@ def test_list_path(renderer, Document):
""" render list indexes correctly """
condition = Document.numbers[1] >= 3
expected = {
- 'ExpressionAttributeValues': {':v2': {'N': '3'}},
- 'ConditionExpression': '(#n0[1] >= :v2)',
+ 'ExpressionAttributeValues': {':v1': {'N': '3'}},
+ 'ConditionExpression': '(#n0[1] >= :v1)',
'ExpressionAttributeNames': {'#n0': 'numbers'}}
renderer.render(condition, "condition")
assert renderer.rendered == expected
|
Fix name_ref rendering for list indexes. Resolves #<I>, Resolves #<I>
|
numberoverzero_bloop
|
train
|
0e043e5e9a1dd6d6a5324fc5fe3b69b4450ea42d
|
diff --git a/openquake/hazardlib/geo/geodetic.py b/openquake/hazardlib/geo/geodetic.py
index <HASH>..<HASH> 100644
--- a/openquake/hazardlib/geo/geodetic.py
+++ b/openquake/hazardlib/geo/geodetic.py
@@ -165,7 +165,7 @@ def min_distance_to_segment(seglons, seglats, lons, lats):
# from the first point to the second one) have a positive distance and
# the others a negative one.
dists = abs(dists)
- dists[idx_neg] = -1 * dists[idx_neg]
+ dists[idx_neg] = - dists[idx_neg]
return dists
diff --git a/openquake/hazardlib/geo/surface/base.py b/openquake/hazardlib/geo/surface/base.py
index <HASH>..<HASH> 100644
--- a/openquake/hazardlib/geo/surface/base.py
+++ b/openquake/hazardlib/geo/surface/base.py
@@ -288,12 +288,12 @@ class BaseQuadrilateralSurface(BaseSurface):
azimuth,
mesh.lons, mesh.lats)
else:
- tmp = geodetic.min_distance_from_segment([p1.longitude,
- p2.longitude],
- [p1.latitude,
- p2.latitude],
- mesh.lons,
- mesh.lats)
+ tmp = geodetic.min_distance_to_segment([p1.longitude,
+ p2.longitude],
+ [p1.latitude,
+ p2.latitude],
+ mesh.lons,
+ mesh.lats)
# Correcting the sign of the distance
if i == 0:
tmp *= -1
|
Fix the call of the min_distance_to_segment function in base.py
|
gem_oq-engine
|
train
|
93ab5b1e4549e08b032685e55b1e5b8c83f785d1
|
diff --git a/tool.js b/tool.js
index <HASH>..<HASH> 100644
--- a/tool.js
+++ b/tool.js
@@ -19,7 +19,7 @@ module.exports = function(options) {
// Fix slash style for our poor windows brothern
var joinPath = function (directory, filename) {
- return path.join(directory, filename).replace('\\', '/');
+ return path.join(directory, filename).replace(/\\/g, '/');
};
this.joinPath = joinPath;
|
Update tool.js
A path may contain more than a single backslash, updated findPath to replace all backslashes, not just the first instance
|
smysnk_gulp-rev-all
|
train
|
3a4eed00c93f1afa72e44389de670b2612f480dd
|
diff --git a/katcp/sensortree.py b/katcp/sensortree.py
index <HASH>..<HASH> 100644
--- a/katcp/sensortree.py
+++ b/katcp/sensortree.py
@@ -50,7 +50,7 @@ class GenericSensorTree(object):
sensor : :class:`katcp.Sensor`
The sensor whose value has changed.
"""
- parents = self._child_to_parents[sensor]
+ parents = list(self._child_to_parents[sensor])
for parent in parents:
self.recalculate(parent, (sensor,))
|
Handle addition of new sensors to the sensor tree during a sensor update without crashing (missing part from last commit).
git-svn-id: <URL>
|
ska-sa_katcp-python
|
train
|
09fcb0eea6f7beeef2705ed185a2e08f771effa1
|
diff --git a/.moban.cd/moban.yml b/.moban.cd/moban.yml
index <HASH>..<HASH> 100644
--- a/.moban.cd/moban.yml
+++ b/.moban.cd/moban.yml
@@ -6,7 +6,7 @@ contact: wangc_2011@hotmail.com
license: MIT
version: 0.4.4
current_version: 0.4.4
-release: 0.4.3
+release: 0.4.4
branch: master
master: index
command_line_interface: "moban"
diff --git a/docs/conf.py b/docs/conf.py
index <HASH>..<HASH> 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -27,7 +27,7 @@ author = 'Onni Software Ltd.'
# The short X.Y version
version = '0.4.4'
# The full version, including alpha/beta/rc tags
-release = '0.4.3'
+release = '0.4.4'
# -- General configuration ---------------------------------------------------
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -41,7 +41,7 @@ DESCRIPTION = (
'Yet another jinja2 cli command for static text generation'
)
URL = 'https://github.com/moremoban/moban'
-DOWNLOAD_URL = '%s/archive/0.4.3.tar.gz' % URL
+DOWNLOAD_URL = '%s/archive/0.4.4.tar.gz' % URL
FILES = ['README.rst', 'CONTRIBUTORS.rst', 'CHANGELOG.rst']
KEYWORDS = [
'python',
@@ -79,8 +79,8 @@ EXTRAS_REQUIRE = {
# You do not need to read beyond this line
PUBLISH_COMMAND = '{0} setup.py sdist bdist_wheel upload -r pypi'.format(
sys.executable)
-GS_COMMAND = ('gs moban v0.4.3 ' +
- "Find 0.4.3 in changelog for more details")
+GS_COMMAND = ('gs moban v0.4.4 ' +
+ "Find 0.4.4 in changelog for more details")
NO_GS_MESSAGE = ('Automatic github release is disabled. ' +
'Please install gease to enable it.')
UPLOAD_FAILED_MSG = (
|
:bug: :books: update release version
|
moremoban_moban
|
train
|
db18fd728e9e1120ec2c8d27658384fd5b18d0d8
|
diff --git a/src/Asset/Exceptions/AsseticException.php b/src/Asset/Exceptions/AsseticException.php
index <HASH>..<HASH> 100644
--- a/src/Asset/Exceptions/AsseticException.php
+++ b/src/Asset/Exceptions/AsseticException.php
@@ -7,7 +7,7 @@
* @license https://github.com/dframe/dframe/blob/master/LICENCE (MIT)
*/
-namespace Dframe;
+namespace Dframe\Asset\Exceptions;
/**
* AsseticException Class
diff --git a/src/Loader/Exceptions/LoaderException.php b/src/Loader/Exceptions/LoaderException.php
index <HASH>..<HASH> 100644
--- a/src/Loader/Exceptions/LoaderException.php
+++ b/src/Loader/Exceptions/LoaderException.php
@@ -7,7 +7,7 @@
* @license https://github.com/dframe/dframe/blob/master/LICENCE (MIT)
*/
-namespace Dframe;
+namespace Dframe\Loader\Exceptions;
/**
* LoaderException Class
diff --git a/src/Router/Exceptions/InvalidArgumentException.php b/src/Router/Exceptions/InvalidArgumentException.php
index <HASH>..<HASH> 100644
--- a/src/Router/Exceptions/InvalidArgumentException.php
+++ b/src/Router/Exceptions/InvalidArgumentException.php
@@ -7,7 +7,7 @@
* @license https://github.com/dframe/dframe/blob/master/LICENCE (MIT)
*/
-namespace Dframe;
+namespace Dframe\Router\Exceptions;
/**
* InvalidArgumentException Class
diff --git a/src/Router/Exceptions/RouterException.php b/src/Router/Exceptions/RouterException.php
index <HASH>..<HASH> 100644
--- a/src/Router/Exceptions/RouterException.php
+++ b/src/Router/Exceptions/RouterException.php
@@ -7,7 +7,7 @@
* @license https://github.com/dframe/dframe/blob/master/LICENCE (MIT)
*/
-namespace Dframe;
+namespace Dframe\Router\Exceptions;
/**
* RouterException Class
diff --git a/src/Router/Exceptions/RuntimeException.php b/src/Router/Exceptions/RuntimeException.php
index <HASH>..<HASH> 100644
--- a/src/Router/Exceptions/RuntimeException.php
+++ b/src/Router/Exceptions/RuntimeException.php
@@ -7,7 +7,7 @@
* @license https://github.com/dframe/dframe/blob/master/LICENCE (MIT)
*/
-namespace Dframe;
+namespace Dframe\Router\Exceptions;
/**
* RuntimeException Class
diff --git a/src/View/Exceptions/ViewException.php b/src/View/Exceptions/ViewException.php
index <HASH>..<HASH> 100644
--- a/src/View/Exceptions/ViewException.php
+++ b/src/View/Exceptions/ViewException.php
@@ -7,7 +7,7 @@
* @license https://github.com/dframe/dframe/blob/master/LICENCE (MIT)
*/
-namespace Dframe;
+namespace Dframe\View\Exceptions;
/**
* ViewException Class
|
Resolved #<I>, Exception not found
|
dframe_dframe
|
train
|
fb0167939c2b6113047d6e153412459970a0df72
|
diff --git a/datajoint/__init__.py b/datajoint/__init__.py
index <HASH>..<HASH> 100644
--- a/datajoint/__init__.py
+++ b/datajoint/__init__.py
@@ -38,6 +38,6 @@ from .schema import create_virtual_module
from .erd import ERD
from .admin import set_password, kill
from .errors import DataJointError, DuplicateError
-from .fetch import PRIMARY_KEY as key
+from .fetch import key
diff --git a/datajoint/fetch.py b/datajoint/fetch.py
index <HASH>..<HASH> 100644
--- a/datajoint/fetch.py
+++ b/datajoint/fetch.py
@@ -6,15 +6,16 @@ from .errors import DataJointError
import warnings
-class PRIMARY_KEY:
+class key:
"""
- object that allows requesting the primary key in Fetch.__getitem__
+ object that allows requesting the primary key as an argument in expression.fetch()
+ The string "KEY" can be used instead of the class key
"""
pass
def is_key(attr):
- return attr is PRIMARY_KEY or attr == 'KEY'
+ return attr is key or attr == 'KEY'
def to_dicts(recarray):
|
rename `PRIMARY_KEY` to `key` in fetch.py
|
datajoint_datajoint-python
|
train
|
72719128c0a896c412db20e3b42c377b27043b7f
|
diff --git a/chalice/app.py b/chalice/app.py
index <HASH>..<HASH> 100644
--- a/chalice/app.py
+++ b/chalice/app.py
@@ -556,10 +556,14 @@ class Chalice(object):
request_accept_header = request_headers.get('accept')
response_content_type = response_headers.get(
'content-type', 'application/json')
- response_is_binary = response_content_type in self.api.binary_types
- request_accepts_binary = request_accept_header in self.api.binary_types
- if response_is_binary != request_accepts_binary:
- return False
+ response_is_binary = _matches_content_type(response_content_type,
+ self.api.binary_types)
+ expects_binary_response = False
+ if request_accept_header is not None:
+ expects_binary_response = _matches_content_type(request_accept_header,
+ self.api.binary_types)
+ if response_is_binary and not expects_binary_response:
+ return False
return True
def _get_view_function_response(self, view_function, function_args):
diff --git a/tests/unit/test_app.py b/tests/unit/test_app.py
index <HASH>..<HASH> 100644
--- a/tests/unit/test_app.py
+++ b/tests/unit/test_app.py
@@ -456,6 +456,24 @@ def test_can_base64_encode_binary_media_types_bytes():
assert response['headers']['Content-Type'] == 'application/octet-stream'
+def test_can_return_text_even_with_binary_content_type_configured():
+ demo = app.Chalice('demo-app')
+
+ @demo.route('/index')
+ def index_view():
+ return app.Response(
+ status_code=200,
+ body='Plain text',
+ headers={'Content-Type': 'text/plain'})
+
+ event = create_event('/index', 'GET', {})
+ event['headers']['Accept'] = 'application/octet-stream'
+ response = demo(event, context=None)
+ assert response['statusCode'] == 200
+ assert response['body'] == 'Plain text'
+ assert response['headers']['Content-Type'] == 'text/plain'
+
+
def test_route_equality():
view_function = lambda: {"hello": "world"}
a = app.RouteEntry(
|
Fix binary validation logic
The only case we care about is where we might send
base<I> content back to the user when they were expecting binary.
The new validation checks if the response is actually binary.
If the response is binary, then the user must specify they
want binary content via the Accept header otherwise we
return an error.
|
aws_chalice
|
train
|
fc7c3868069ede1d3867a0a9b99f271144d9f015
|
diff --git a/phypno/ioeeg/blackrock.py b/phypno/ioeeg/blackrock.py
index <HASH>..<HASH> 100644
--- a/phypno/ioeeg/blackrock.py
+++ b/phypno/ioeeg/blackrock.py
@@ -100,7 +100,7 @@ class BlackRock:
# we need these two items to read the data
self.BOData = orig['BOData']
- self.DataPoints = n_samples
+ self.n_samples = n_samples
self.factor = 0.25 * ones(len(orig['ChannelID']))
# make up names
|
self.n_samples not none when reading NEURALSG in BlackRock
|
wonambi-python_wonambi
|
train
|
6bb856f5298dda95fc4225731ca1b3882129a774
|
diff --git a/ipmag.py b/ipmag.py
index <HASH>..<HASH> 100755
--- a/ipmag.py
+++ b/ipmag.py
@@ -1832,13 +1832,13 @@ def core_depthplot(input_dir_path='.', meas_file='magic_measurements.txt', spc_f
return main_plot, figname
-def download_magic(infile, dir_path='.', input_dir_path='.', overwrite=False):
+def download_magic(infile, dir_path='.', input_dir_path='.',overwrite=False,print_progress=True):
"""
takes the name of a text file downloaded from the MagIC database and
unpacks it into magic-formatted files. by default, download_magic assumes
that you are doing everything in your current directory. if not, you may
provide optional arguments dir_path (where you want the results to go) and
- input_dir_path (where the dowloaded file is).
+ input_dir_path (where the downloaded file is).
"""
f=open(os.path.join(input_dir_path, infile),'rU')
infile=f.readlines()
@@ -1856,7 +1856,8 @@ def download_magic(infile, dir_path='.', input_dir_path='.', overwrite=False):
file_type=file_type.lower()
if file_type=='delimited':file_type=Input[skip].split('\t')[2]
if file_type[-1]=="\n":file_type=file_type[:-1]
- print 'working on: ',repr(file_type)
+ if print_progress==True:
+ print 'working on: ',repr(file_type)
if file_type not in type_list:
type_list.append(file_type)
else:
@@ -1886,7 +1887,8 @@ def download_magic(infile, dir_path='.', input_dir_path='.', overwrite=False):
rec['magic_method_codes']=methods[:-1]
NewRecs.append(rec)
pmag.magic_write(outfile,Recs,file_type)
- print file_type," data put in ",outfile
+ if print_progress==True:
+ print file_type," data put in ",outfile
if file_type =='pmag_specimens' and 'magic_measurements.txt' in File and 'measurement_step_min' in File and 'measurement_step_max' in File: # sort out zeq_specimens and thellier_specimens
os.system('mk_redo.py')
os.system('zeq_magic_redo.py')
@@ -1928,14 +1930,16 @@ def download_magic(infile, dir_path='.', input_dir_path='.', overwrite=False):
rec['magic_method_codes']=methods[:-1]
NewRecs.append(rec)
pmag.magic_write(outfile,Recs,file_type)
- print file_type," data put in ",outfile
+ if print_progress==True:
+ print file_type," data put in ",outfile
# look through locations table and create separate directories for each location
locs,locnum=[],1
if 'er_locations' in type_list:
locs,file_type=pmag.magic_read(dir_path+'/er_locations.txt')
if len(locs)>0: # at least one location
for loc in locs:
- print 'location_'+str(locnum)+": ",loc['er_location_name']
+ if print_progress==True:
+ print 'location_'+str(locnum)+": ",loc['er_location_name']
lpath=dir_path+'/Location_'+str(locnum)
locnum+=1
try:
@@ -1946,19 +1950,23 @@ def download_magic(infile, dir_path='.', input_dir_path='.', overwrite=False):
print "-W- download_magic encountered a duplicate subdirectory ({}) and could not finish.\nRerun with overwrite=True, or unpack this file in a different directory.".format(lpath)
return False
for f in type_list:
- print 'unpacking: ',dir_path+'/'+f+'.txt'
+ if print_progress==True:
+ print 'unpacking: ',dir_path+'/'+f+'.txt'
recs,file_type=pmag.magic_read(dir_path+'/'+f+'.txt')
- print len(recs),' read in'
+ if print_progress==True:
+ print len(recs),' read in'
if 'results' not in f:
lrecs=pmag.get_dictitem(recs,'er_location_name',loc['er_location_name'],'T')
if len(lrecs)>0:
pmag.magic_write(lpath+'/'+f+'.txt',lrecs,file_type)
- print len(lrecs),' stored in ',lpath+'/'+f+'.txt'
+ if print_progress==True:
+ print len(lrecs),' stored in ',lpath+'/'+f+'.txt'
else:
lrecs=pmag.get_dictitem(recs,'er_location_names',loc['er_location_name'],'T')
if len(lrecs)>0:
pmag.magic_write(lpath+'/'+f+'.txt',lrecs,file_type)
- print len(lrecs),' stored in ',lpath+'/'+f+'.txt'
+ if print_progress==True:
+ print len(lrecs),' stored in ',lpath+'/'+f+'.txt'
return True
|
put option in download_magic to reduce printing while executing
All of the print statements during download magic fill up a lot of
space when executed in a notebook. There is now an optional argument to
not print as much of these progress statements.
|
PmagPy_PmagPy
|
train
|
3d0f9a6e30ff09746ac5d70e93643685b3d3b07c
|
diff --git a/esgfpid/rabbit/asynchronous/thread_builder.py b/esgfpid/rabbit/asynchronous/thread_builder.py
index <HASH>..<HASH> 100644
--- a/esgfpid/rabbit/asynchronous/thread_builder.py
+++ b/esgfpid/rabbit/asynchronous/thread_builder.py
@@ -2,6 +2,7 @@ import logging
import pika
import time
import copy
+import datetime
from esgfpid.utils import get_now_utc_as_formatted_string as get_now_utc_as_formatted_string
import esgfpid.defaults as defaults
import esgfpid.rabbit.connparams
@@ -57,6 +58,11 @@ class ConnectionBuilder(object):
''' To count how many times we have tried to reconnect to the same RabbitMQ URL.'''
self.__reconnect_counter = 0
+ '''
+ To see how much time it takes to connect.
+ '''
+ self.__start_connect_time = None
+
####################
### Start ioloop ###
####################
@@ -103,7 +109,8 @@ class ConnectionBuilder(object):
except pika.exceptions.ProbableAuthenticationError as e:
- logerror(LOGGER, 'Caught Authentication Exception during connection ("%s").', e.__class__.__name__)
+ time_passed = datetime.datetime.now() - self.__start_connect_time
+ logerror(LOGGER, 'Caught Authentication Exception after %s seconds during connection ("%s").', time_passed.total_seconds(), e.__class__.__name__)
self.statemachine.set_to_waiting_to_be_available()
self.statemachine.detail_authentication_exception = True # TODO WHAT FOR?
@@ -158,6 +165,7 @@ class ConnectionBuilder(object):
''' Asynchronous, waits for answer from RabbitMQ.'''
def __please_open_connection(self):
params = self.__node_manager.get_connection_parameters()
+ self.__start_connect_time = datetime.datetime.now()
logdebug(LOGGER, 'Connecting to RabbitMQ at %s... (%s)',
params.host, get_now_utc_as_formatted_string())
loginfo(LOGGER, 'Opening connection to RabbitMQ...')
@@ -193,7 +201,8 @@ class ConnectionBuilder(object):
''' Callback, called by RabbitMQ. '''
def on_channel_open(self, channel):
- logdebug(LOGGER, 'Opening channel... done.')
+ time_passed = datetime.datetime.now() - self.__start_connect_time
+ logdebug(LOGGER, 'Opening channel... done. Took %s seconds.' % time_passed.total_seconds())
logtrace(LOGGER, 'Channel has number: %s.', channel.channel_number)
self.thread._channel = channel
self.__reconnect_counter = 0
@@ -271,7 +280,8 @@ class ConnectionBuilder(object):
def on_connection_error(self, connection, msg):
oldhost = self.__node_manager.get_connection_parameters().host
- loginfo(LOGGER, 'Failed connection to RabbitMQ at %s. Reason: %s.', oldhost, msg)
+ time_passed = datetime.datetime.now() - self.__start_connect_time
+ loginfo(LOGGER, 'Failed connection to RabbitMQ at %s after %s seconds. Reason: %s.', oldhost, time_passed.total_seconds(), msg)
# If there was a force-finish, we do not reconnect.
if self.statemachine.is_FORCE_FINISHED():
|
Log statements now print how much time it took to connect, or to fail to connect.
|
IS-ENES-Data_esgf-pid
|
train
|
8fb3bab04dfb6b9eb54b9e060e5ff6a2effcb6c0
|
diff --git a/lib/knife-cloudformation/knife/stack.rb b/lib/knife-cloudformation/knife/stack.rb
index <HASH>..<HASH> 100644
--- a/lib/knife-cloudformation/knife/stack.rb
+++ b/lib/knife-cloudformation/knife/stack.rb
@@ -8,6 +8,8 @@ module KnifeCloudformation
module InstanceMethods
+ # un-packed stack name joiner/identifier
+ UNPACK_NAME_JOINER = '-sfn-'
# maximum number of attempts to get valid parameter value
MAX_PARAMETER_ATTEMPTS = 5
@@ -28,7 +30,7 @@ module KnifeCloudformation
file['Resources'].each do |stack_resource_name, stack_resource|
- nested_stack_name = "#{name}-#{stack_resource_name}"
+ nested_stack_name = "#{name}#{UNPACK_NAME_JOINER}#{stack_resource_name}"
nested_stack_template = stack_resource['Properties']['Stack']
Chef::Config[:knife][:cloudformation][:options][:parameters] = orig_params
|
Use defined string joiner for generated unpacked names to allow easy identification
|
sparkleformation_sfn
|
train
|
2a0bb808462e484e4cd5c4c7095c95ad34218ff0
|
diff --git a/resource_aws_vpn_gateway_test.go b/resource_aws_vpn_gateway_test.go
index <HASH>..<HASH> 100644
--- a/resource_aws_vpn_gateway_test.go
+++ b/resource_aws_vpn_gateway_test.go
@@ -62,10 +62,9 @@ func TestAccAWSVpnGateway_disappears(t *testing.T) {
var v ec2.VpnGateway
resource.Test(t, resource.TestCase{
- PreCheck: func() { testAccPreCheck(t) },
- IDRefreshName: "aws_vpn_gateway.foo",
- Providers: testAccProviders,
- CheckDestroy: testAccCheckVpnGatewayDestroy,
+ PreCheck: func() { testAccPreCheck(t) },
+ Providers: testAccProviders,
+ CheckDestroy: testAccCheckVpnGatewayDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: testAccVpnGatewayConfig,
|
provider/aws: Clear up test failure for TestAccAWSVpnGateway_disappears
|
terraform-providers_terraform-provider-aws
|
train
|
4474184478b0aeb32029d83ad6d34cf9cc1c3a0b
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -29,7 +29,7 @@ nodeq.connect({host: "localhost", port: 5000}, function(err, con) {
```javascript
var nodeq = require("node-q");
-nodeq.connect({host: "localhost", port: "localhost", 5000, user: "user", password: "password"}, function(err, con) {
+nodeq.connect({host: "localhost", port: 5000, user: "user", password: "password"}, function(err, con) {
if (err) throw err;
console.log("connected");
// interact with con like demonstrated below
@@ -84,6 +84,15 @@ con.ks("show", [1, 2, 3], function(err) {
```javascript
con.k(function(err, res) {
if (err) throw err;
+ console.log('result', res);
+});
+```
+
+### Listen to a handle
+
+```javascript
+con.k(function(err, res) {
+ if (err) throw err;
console.log('result'm res);
});
```
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -72,6 +72,10 @@ Connection.prototype.listen = function() {
} else {
if (err === undefined && Array.isArray(o) && o[0] === "upd") {
self.emit("upd", o[1], o[2]);
+ } else {
+ responseNo = self.nextResponseNo;
+ self.nextResponseNo += 1;
+ self.emit("response:" + responseNo, err, o);
}
}
if (buffer.length > length) {
diff --git a/itest/readme.js b/itest/readme.js
index <HASH>..<HASH> 100644
--- a/itest/readme.js
+++ b/itest/readme.js
@@ -65,6 +65,21 @@ describe("readme", function() {
it("Async execute function with parameters", function(done) {
con.ks("show", [1, 2, 3], done);
});
+ it("Async execute and get async response", function(done) {
+ con.ks("show 1;neg[.z.w][33]", function(err) {
+ if (err) {
+ throw err;
+ }
+ });
+ con.k(function(err, res) {
+ if (err) {
+ done(err);
+ } else {
+ assert.equal(res, 33);
+ done();
+ }
+ });
+ });
it("Subscribe to kdb+tick", function(done) {
con.once("upd", function(table, data) {
assert.equal(table, "trade");
|
Fix listen to handle (#<I>)
* Add listen on handle
* Add documentation for listen
* Fix bug in listen
* Fix typos in README
* Add integration test for listening to handle
|
michaelwittig_node-q
|
train
|
69b534fc7f086f9a01752d5a6fd94c73f4006db4
|
diff --git a/bottery/platform/__init__.py b/bottery/platform/__init__.py
index <HASH>..<HASH> 100644
--- a/bottery/platform/__init__.py
+++ b/bottery/platform/__init__.py
@@ -2,7 +2,6 @@ import importlib
import logging
import os
-from bottery.conf import settings
from bottery.exceptions import ImproperlyConfigured
@@ -28,20 +27,31 @@ def discover_view(message):
class BaseEngine:
+ # Should we use ABC for required attributes and methods?
- def __init__(self, **kw):
- self.tasks = []
-
- for item, value in kw.items():
+ def __init__(self, **kwargs):
+ # For each named parameters received, set it as an instance
+ # attribute
+ for item, value in kwargs.items():
setattr(self, item, value)
@property
- def webhook_endpoint(self):
- return '/hook/{}'.format(self.platform)
+ def platform(self):
+ """Platform name"""
+ raise NotImplementedError('platform attribute not implemented')
@property
- def webhook_url(self):
- return 'https://{}{}'.format(settings.HOSTNAME, self.webhook_endpoint)
+ def tasks(self):
+ """List of tasks to be added to the main event loop"""
+ raise NotImplementedError('tasks attribute not implemented')
def build_message(self):
- raise NotImplementedError('create_message not implemented')
+ """
+ Build Message instance according to the data received from the
+ platform API.
+ """
+ raise NotImplementedError('build_message not implemented')
+
+ def configure(self):
+ """Called by App instance to configure the platform"""
+ raise NotImplementedError('configure not implemented')
diff --git a/bottery/platform/telegram.py b/bottery/platform/telegram.py
index <HASH>..<HASH> 100644
--- a/bottery/platform/telegram.py
+++ b/bottery/platform/telegram.py
@@ -79,7 +79,9 @@ class TelegramEngine(platform.BaseEngine):
if not hasattr(self, 'mode'):
self.mode = 'polling'
- self.tasks = [self.polling]
+ @property
+ def tasks(self):
+ return [self.polling]
def configure(self):
response = self.api.delete_webhook()
diff --git a/tests/test_platform.py b/tests/test_platform.py
index <HASH>..<HASH> 100644
--- a/tests/test_platform.py
+++ b/tests/test_platform.py
@@ -3,12 +3,29 @@ import pytest
from bottery.platform import BaseEngine
-def test_platform_baseplatform():
- platform = 'TEST_PLATFORM'
- bp = BaseEngine(platform=platform)
+def test_baseengine_platform():
+ """Check if platform attr raise NotImplementedError"""
+ engine = BaseEngine()
+ with pytest.raises(NotImplementedError):
+ engine.platform
- assert bp.webhook_endpoint == '/hook/{}'.format(platform)
- assert not len(bp.tasks)
- with pytest.raises(Exception):
- bp.build_message()
+def test_baseengine_tasks():
+ """Check if tasks attr raise NotImplementedError"""
+ engine = BaseEngine()
+ with pytest.raises(NotImplementedError):
+ engine.tasks
+
+
+def test_baseengine_build_message():
+ """Check if build_message method raise NotImplementedError"""
+ engine = BaseEngine()
+ with pytest.raises(NotImplementedError):
+ engine.build_message()
+
+
+def test_baseengine_configure():
+ """Check if configure method raise NotImplementedError"""
+ engine = BaseEngine()
+ with pytest.raises(NotImplementedError):
+ engine.configure()
|
Create required properties and methods from all engines
|
rougeth_bottery
|
train
|
7aff4a6c5841b2ec39ff4c96e8b654f78c7026d8
|
diff --git a/packet/bmp/bmp.go b/packet/bmp/bmp.go
index <HASH>..<HASH> 100644
--- a/packet/bmp/bmp.go
+++ b/packet/bmp/bmp.go
@@ -540,9 +540,15 @@ const (
BMP_MSG_TERMINATION
)
-func ParseBMPMessage(data []byte) (*BMPMessage, error) {
- msg := &BMPMessage{}
- err := msg.Header.DecodeFromBytes(data)
+func ParseBMPMessage(data []byte) (msg *BMPMessage, err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("not all data bytes are available")
+ }
+ }()
+
+ msg = &BMPMessage{}
+ err = msg.Header.DecodeFromBytes(data)
if err != nil {
return nil, err
}
|
packet: Avoid panic() during decoding BMP messages
|
osrg_gobgp
|
train
|
d7ce1874f01fa388a8ffb1c3fac126e7eddd9064
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -14,16 +14,17 @@ function Promise(block) {
rejectNext = reject;
});
- if (typeof onFulfilled === 'function') {
- deferred.onFulfilled(wrapHandler(onFulfilled, resolveNext, rejectNext));
- } else {
- deferred.onFulfilled(wrapProxy(resolveNext));
- }
- if (typeof onRejected === 'function') {
- deferred.onRejected(wrapHandler(onRejected, resolveNext, rejectNext));
- } else {
- deferred.onRejected(wrapProxy(rejectNext));
- }
+ ifFunction(onFulfilled, function () {
+ return deferred.onFulfilled(wrapHandler(onFulfilled, resolveNext, rejectNext));
+ }, function () {
+ return deferred.onFulfilled(wrapProxy(resolveNext));
+ });
+
+ ifFunction(onRejected, function () {
+ return deferred.onRejected(wrapHandler(onRejected, resolveNext, rejectNext));
+ }, function () {
+ return deferred.onRejected(wrapProxy(rejectNext));
+ })
return promise;
};
@@ -45,6 +46,8 @@ Promise.reject = function (error) {
return promise;
};
+exports.Promise = Promise;
+
function newDefer(promise) {
var self = Object.create(null)
, status = PENDING
@@ -52,55 +55,49 @@ function newDefer(promise) {
, fulfillmentHandlers = []
, rejectionHandlers = []
- self.resolve = function deferred_resolve(value) {
- commitPromise(value, promise, function (value) {
- process.nextTick(function resolveNextTick() {
- if (status !== PENDING) return;
- status = FULFILLED;
- knownFate = value;
- fulfillmentHandlers.forEach(function (handler) {
- handler(status, knownFate);
- });
- });
- }, self.reject);
+ self.resolve = function (value) {
+ var resolve = commit(fulfillmentHandlers, FULFILLED)
+ resolveValue(value, promise, resolve, self.reject);
};
- self.reject = function deferred_reject(error) {
- process.nextTick(function rejectNextTick() {
- if (status !== PENDING) return;
- status = REJECTED;
- knownFate = error;
- rejectionHandlers.forEach(function (handler) {
- handler(status, knownFate);
- });
- });
- };
+ self.reject = commit(rejectionHandlers, REJECTED);
- self.onFulfilled = function (handler) {
- if (status === PENDING) {
- fulfillmentHandlers.push(handler);
- } else if (status === FULFILLED) {
- process.nextTick(function () {
- handler(status, knownFate);
- });
- }
- };
+ self.onFulfilled = addHandler(fulfillmentHandlers, FULFILLED);
+
+ self.onRejected = addHandler(rejectionHandlers, REJECTED);
+
+ function addHandler(handlers, expect) {
+ return function (handler) {
+ if (status === PENDING) {
+ handlers.push(handler);
+ } else if (status === expect) {
+ queue(handler);
+ }
+ };
+ }
- self.onRejected = function (handler) {
- if (status === PENDING) {
- rejectionHandlers.push(handler);
- } else if (status === REJECTED) {
- process.nextTick(function () {
- handler(status, knownFate);
+ function queue(handler) {
+ process.nextTick(function () {
+ handler(status, knownFate);
+ });
+ }
+
+ function commit(handlers, committedStatus) {
+ return function (fate) {
+ return process.nextTick(function () {
+ if (status !== PENDING) return;
+ status = committedStatus;
+ knownFate = fate;
+ handlers.forEach(function (handler) {
+ handler(status, knownFate);
+ });
});
- }
- };
+ };
+ }
return self;
}
-exports.Promise = Promise;
-
function wrapHandler(handler, resolve, reject) {
return function wrappedHandler(state, fate) {
@@ -121,7 +118,7 @@ function wrapProxy(next) {
};
}
-function commitPromise(x, promise, resolve, reject) {
+function resolveValue(x, promise, resolve, reject) {
var invokeResolve = invoke(resolve, [x])
function rejectWithSameObject() {
@@ -155,7 +152,7 @@ function commitPromise(x, promise, resolve, reject) {
then.call(x, function (y) {
if (resolved) return;
resolved = true;
- commitPromise(y, promise, resolve, reject);
+ resolveValue(y, promise, resolve, reject);
}, function (r) {
if (resolved) return;
resolved = true;
|
Functional refactoring.
On branch v_2_ecma6
modified: index.js
|
kixxauth_iou
|
train
|
48929afd60aab28574b2356773ab24f80dfa193b
|
diff --git a/src/test/java/org/jboss/netty/buffer/DuplicateChannelBufferTest.java b/src/test/java/org/jboss/netty/buffer/DuplicateChannelBufferTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/jboss/netty/buffer/DuplicateChannelBufferTest.java
+++ b/src/test/java/org/jboss/netty/buffer/DuplicateChannelBufferTest.java
@@ -33,7 +33,7 @@ public class DuplicateChannelBufferTest extends AbstractChannelBufferTest {
@Override
protected ChannelBuffer newBuffer(int length) {
- buffer = ChannelBuffers.buffer(length).duplicate();
+ buffer = new DuplicatedChannelBuffer(ChannelBuffers.buffer(length));
assertEquals(0, buffer.writerIndex());
return buffer;
}
|
Fixed a bug where DuplicateChannelBufferTest doesn't test DuplicateChannelBuffer
|
netty_netty
|
train
|
e52a2d857902a77c665b418e898a242d0f11f42d
|
diff --git a/gui.py b/gui.py
index <HASH>..<HASH> 100644
--- a/gui.py
+++ b/gui.py
@@ -70,14 +70,14 @@ class BasicStream(object):
if text.strip():
self.nextTitle = text.strip()
- if text.startswith('\n'):
+ if text.startswith(os.linesep):
self.contents.append('')
if self.currout:
self.outdict[self.currout].append('')
- self.contents[-1] += text.strip('\n')
+ self.contents[-1] += text.strip(os.linesep)
if self.currout:
- self.outdict[self.currout][-1] += text.strip('\n')
- if text.endswith('\n') and text.strip():
+ self.outdict[self.currout][-1] += text.strip(os.linesep)
+ if text.endswith(os.linesep) and text.strip():
self.contents.append('')
if self.currout:
self.outdict[self.currout].append('')
@@ -227,7 +227,7 @@ class LintGui(object):
#buttons
Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT)
- Button(top_frame, text='Open Package',
+ Button(top_frame, text='Open Package',
command=(lambda : self.file_open(package=True))).pack(side=LEFT)
self.btnRun = Button(top_frame, text='Run', command=self.run_lint)
|
Fix line ending issues causing GUI to error out on Windows
|
PyCQA_pylint
|
train
|
654a2373a1ef0a1dbaa088a0cf3c90fac9ee779c
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## 1.5.1 (July, 1, 2015)
+
+### improvements
+
+- Update `filepicker_image_url` to merge query params into current url params if they exist
+
## 1.5.0 (June, 10, 2015)
### features
diff --git a/app/helpers/filepicker_rails/application_helper.rb b/app/helpers/filepicker_rails/application_helper.rb
index <HASH>..<HASH> 100644
--- a/app/helpers/filepicker_rails/application_helper.rb
+++ b/app/helpers/filepicker_rails/application_helper.rb
@@ -179,15 +179,10 @@ module FilepickerRails
end
def execute
- url_with_path = if convert_options.any?
- "#{cdn_url}/convert"
- else
- cdn_url
- end
-
- query_params = all_options.merge(policy_config).to_query
+ base_url = url_with_path.split("?").first
+ query_params = original_url_options.merge(all_options).merge(policy_config).to_query
- [url_with_path, query_params.presence].compact.join('?')
+ [base_url, query_params.presence].compact.join("?")
end
private
@@ -202,8 +197,18 @@ module FilepickerRails
options.select { |option| CONVERT_OPTIONS.include?(option) }
end
+ def original_url_options
+ query_string = url_with_path.split("?")[1]
+
+ if query_string
+ query_to_hash(query_string)
+ else
+ {}
+ end
+ end
+
def cdn_host
- ::Rails.application.config.filepicker_rails.cdn_host
+ @cdn_host ||= ::Rails.application.config.filepicker_rails.cdn_host
end
def cdn_url
@@ -218,6 +223,22 @@ module FilepickerRails
def policy_config
Policy.apply
end
+
+ def query_to_hash(query_string)
+ Hash[
+ CGI::parse(query_string).map do |k, v|
+ [k, v.first]
+ end
+ ]
+ end
+
+ def url_with_path
+ @url_with_path ||= if convert_options.any? && !cdn_url.match("/convert")
+ "#{cdn_url}/convert"
+ else
+ cdn_url
+ end
+ end
end
private_constant :FilepickerImageUrl
diff --git a/lib/filepicker_rails/version.rb b/lib/filepicker_rails/version.rb
index <HASH>..<HASH> 100644
--- a/lib/filepicker_rails/version.rb
+++ b/lib/filepicker_rails/version.rb
@@ -1,3 +1,3 @@
module FilepickerRails
- VERSION = "1.5.0"
+ VERSION = "1.5.1"
end
diff --git a/spec/helpers/application_helper_spec.rb b/spec/helpers/application_helper_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/helpers/application_helper_spec.rb
+++ b/spec/helpers/application_helper_spec.rb
@@ -254,6 +254,13 @@ RSpec.describe FilepickerRails::ApplicationHelper do
end
end
+ context "with convert options provided and convert options already in the url" do
+ it "merges the options into the query params" do
+ url = filepicker_image_url("foo/convert?crop=0,0,1024,1024", watersize: 70)
+ expect(url).to eq("foo/convert?crop=0%2C0%2C1024%2C1024&watersize=70")
+ end
+ end
+
context "with cdn host" do
before do
|
Merge url options with query string if already present in url
|
filestack_filestack-rails
|
train
|
d977bc25fc86d00d73381298ed2e56f64539311d
|
diff --git a/applications/default/extensions/user/user.js b/applications/default/extensions/user/user.js
index <HASH>..<HASH> 100644
--- a/applications/default/extensions/user/user.js
+++ b/applications/default/extensions/user/user.js
@@ -316,8 +316,7 @@ user.route = function(routes, callback) {
// We create routes to form submits until we figure out what approach to use
// for handling form submits.
newRoutes['/create-account-submit'] = {
- //access: 'create account',
- access: true,
+ access: 'create-account',
callback: function(request, response, callback) {
var data = request.body;
@@ -355,7 +354,7 @@ user.route = function(routes, callback) {
};
newRoutes['/sign-in-submit'] = {
- access: true,
+ access: 'sign-in',
callback: function(request, response, callback) {
// Check if there are both an username and a password.
// @todo in the long run we may need a way to validate forms that aren't
@@ -385,7 +384,7 @@ user.route = function(routes, callback) {
};
newRoutes['/sign-out'] = {
- access: true,
+ access: 'sign-out',
callback: function(request, response, callback) {
// Log user out.
request.logout();
@@ -406,14 +405,21 @@ user.role = function(routes, callback) {
// logged in.
newRoles['anonymous'] = {
title: 'Anonymous',
- description: 'Anonymous, unauthenticated user.'
+ description: 'Anonymous, unauthenticated user.',
+ permissions: [
+ 'create-account',
+ 'sign-in'
+ ]
};
// The 'authenticated' role is a magic role that's set to every authenticated
// user.
newRoles['authenticated'] = {
title: 'Authenticated',
- description: 'Authenticated, signed in user.'
+ description: 'Authenticated, signed in user.',
+ permissions: [
+ 'sign-out'
+ ]
};
// The 'administrator' role is a magic default role that's used to grant
|
Adding some default permissions to anonymous users and making it check for them when appropriate.
|
recidive_choko
|
train
|
c143c1bdcae3c5c02fc4fc19f791212237433372
|
diff --git a/store/src/main/java/com/buschmais/jqassistant/core/store/impl/AbstractGraphStore.java b/store/src/main/java/com/buschmais/jqassistant/core/store/impl/AbstractGraphStore.java
index <HASH>..<HASH> 100644
--- a/store/src/main/java/com/buschmais/jqassistant/core/store/impl/AbstractGraphStore.java
+++ b/store/src/main/java/com/buschmais/jqassistant/core/store/impl/AbstractGraphStore.java
@@ -4,19 +4,19 @@ import com.buschmais.jqassistant.core.model.api.descriptor.Descriptor;
import com.buschmais.jqassistant.core.store.api.DescriptorDAO;
import com.buschmais.jqassistant.core.store.api.QueryResult;
import com.buschmais.jqassistant.core.store.api.Store;
-import com.buschmais.jqassistant.core.store.api.model.NodeLabel;
import com.buschmais.jqassistant.core.store.api.model.PrimaryLabel;
import com.buschmais.jqassistant.core.store.impl.dao.DescriptorDAOImpl;
import com.buschmais.jqassistant.core.store.impl.dao.DescriptorMapperRegistry;
-import com.buschmais.jqassistant.core.store.impl.dao.mapper.*;
+import com.buschmais.jqassistant.core.store.impl.dao.mapper.DescriptorMapper;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.schema.IndexDefinition;
import org.neo4j.kernel.GraphDatabaseAPI;
-import java.util.ArrayList;
import java.util.Collections;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import static com.buschmais.jqassistant.core.store.api.model.NodeProperty.FQN;
@@ -48,11 +48,13 @@ public abstract class AbstractGraphStore implements Store {
@Override
public void start(List<DescriptorMapper<?>> mappers) {
database = startDatabase();
- List<PrimaryLabel> primaryLabels = new ArrayList<>();
+ Set<PrimaryLabel> primaryLabels = new HashSet<>();
mapperRegistry = new DescriptorMapperRegistry();
for (DescriptorMapper<?> mapper : mappers) {
+ if (!primaryLabels.add(mapper.getPrimaryLabel())) {
+ throw new IllegalStateException("Primary label is already defined " + mapper.getPrimaryLabel() + ":" + primaryLabels);
+ }
mapperRegistry.register(mapper);
- primaryLabels.add(mapper.getPrimaryLabel());
}
descriptorDAO = new DescriptorDAOImpl(mapperRegistry, database);
beginTransaction();
|
#<I> added check for duplicate primary labels
|
buschmais_jqa-core-framework
|
train
|
1cd0e23c6aa9c30f462582f03da957e6043d753f
|
diff --git a/anoncreds/protocol/cred_def_secret_key.py b/anoncreds/protocol/cred_def_secret_key.py
index <HASH>..<HASH> 100644
--- a/anoncreds/protocol/cred_def_secret_key.py
+++ b/anoncreds/protocol/cred_def_secret_key.py
@@ -4,9 +4,9 @@ from config.config import cmod
# TODO Should be renamed to something like IssuerCoreSecretKey
class CredDefSecretKey:
- def __init__(self, p: cmod.integer=None, q: cmod.integer=None):
- self._p = p if p else genPrime() * 2 + 1
- self._q = q if q else genPrime() * 2 + 1
+ def __init__(self, p=None, q=None):
+ self._p = cmod.integer(p) if p else genPrime() * 2 + 1
+ self._q = cmod.integer(q) if q else genPrime() * 2 + 1
self._n = self.p * self.q
@classmethod
|
made CredDefSecretKey constructor more forgiving
|
hyperledger-archives_indy-anoncreds
|
train
|
79497dd240676aa2dd12bbc2a1b37f0c478f68e0
|
diff --git a/src/main/java/ca/mjdsystems/jmatio/io/MatFileReader.java b/src/main/java/ca/mjdsystems/jmatio/io/MatFileReader.java
index <HASH>..<HASH> 100755
--- a/src/main/java/ca/mjdsystems/jmatio/io/MatFileReader.java
+++ b/src/main/java/ca/mjdsystems/jmatio/io/MatFileReader.java
@@ -1091,6 +1091,12 @@ public class MatFileReader
if ( !className.equals("FileWrapper__") ) {
MLUInt32 content = (MLUInt32) readMatrix(buf, false);
int[][] t = content.getArray();
+
+ // Check that the first four numbers are the same, as expected.
+ if (t[0][0] != 0xdd000000 || t[1][0] != 2 || t[2][0] != 1 || t[3][0] != 1) {
+ throw new IOException("MCOS per-object header was different then expected! Got: " + content.contentToString());
+ }
+
mlArray = new MLObjectPlaceholder(arrName, className, t);
haveMCOS = true;
} else { // This is where we get the useful MCOS data. Only used on FileWrapper__ classes.
|
Make sure the MCOS header for objects is present.
To avoid future surprises, make sure that the MCOS header bytes for an object
are correct.
|
diffplug_JMatIO
|
train
|
525627a551914aa04c6cef6b456e75a031af7613
|
diff --git a/src/dsv.js b/src/dsv.js
index <HASH>..<HASH> 100644
--- a/src/dsv.js
+++ b/src/dsv.js
@@ -6,7 +6,7 @@ var EOL = {},
function objectConverter(columns) {
return new Function("d", "return {" + columns.map(function(name, i) {
- return JSON.stringify(name) + ": d[" + i + "]";
+ return JSON.stringify(name) + ": d[" + i + "] || \"\"";
}).join(",") + "}");
}
diff --git a/test/csv-test.js b/test/csv-test.js
index <HASH>..<HASH> 100644
--- a/test/csv-test.js
+++ b/test/csv-test.js
@@ -47,17 +47,17 @@ tape("csvParse(string) ignores a blank last line", function(test) {
});
tape("csvParse(string) treats a blank non-last line as a single-column empty string", function(test) {
- test.deepEqual(dsv.csvParse("a,b,c\n1,2,3\n\n"), table([{a: "1", b: "2", c: "3"}, {a: "", b: undefined, c: undefined}], ["a", "b", "c"]));
+ test.deepEqual(dsv.csvParse("a,b,c\n1,2,3\n\n"), table([{a: "1", b: "2", c: "3"}, {a: "", b: "", c: ""}], ["a", "b", "c"]));
test.end();
});
-tape("csvParse(string) returns undefined values for missing columns", function(test) {
- test.deepEqual(dsv.csvParse("a,b,c\n1\n1,2"), table([{a: "1", b: undefined, c: undefined}, {a: "1", b: "2", c: undefined}], ["a", "b", "c"]));
+tape("csvParse(string) returns empty strings for missing columns", function(test) {
+ test.deepEqual(dsv.csvParse("a,b,c\n1\n1,2"), table([{a: "1", b: "", c: ""}, {a: "1", b: "2", c: ""}], ["a", "b", "c"]));
test.end();
});
tape("csvParse(string) does not ignore a whitespace-only last line", function(test) {
- test.deepEqual(dsv.csvParse("a,b,c\n1,2,3\n "), table([{a: "1", b: "2", c: "3"}, {a: " ", b: undefined, c: undefined}], ["a", "b", "c"]));
+ test.deepEqual(dsv.csvParse("a,b,c\n1,2,3\n "), table([{a: "1", b: "2", c: "3"}, {a: " ", b: "", c: ""}], ["a", "b", "c"]));
test.end();
});
|
Return empty string for missing columns, instead of undefined
Reverses one test, so technically we can say that it breaks the API. However README is silent about this situation, so I don't know.
Fixes <URL>
|
d3_d3-dsv
|
train
|
d45752960ac89fab4df4c6b18d250bdf050eadcd
|
diff --git a/debug.go b/debug.go
index <HASH>..<HASH> 100644
--- a/debug.go
+++ b/debug.go
@@ -20,6 +20,13 @@ import (
)
func describeRequest(op interface{}) (s string) {
+ // Handle special cases with custom formatting.
+ switch typed := op.(type) {
+ case *interruptOp:
+ s = fmt.Sprintf("interruptOp(fuseid=0x%08x)", typed.FuseID)
+ return
+ }
+
v := reflect.ValueOf(op).Elem()
t := v.Type()
|
Use a custom logging for interruptOp, to aid in debugging.
|
jacobsa_fuse
|
train
|
cea2feb6b25b074dcf41995b45345a613530346e
|
diff --git a/pyqode/core/panels/search_and_replace.py b/pyqode/core/panels/search_and_replace.py
index <HASH>..<HASH> 100644
--- a/pyqode/core/panels/search_and_replace.py
+++ b/pyqode/core/panels/search_and_replace.py
@@ -394,10 +394,13 @@ class SearchAndReplacePanel(Panel, DelayJobRunner, Ui_SearchPanel):
occurrences = self.getOccurrences()
if cr == -1:
self.selectNext()
+ cr = self.__getCurrentOccurrence()
try:
+ # prevent search request due to editor textChanged
try:
self.editor.textChanged.disconnect(self.requestSearch)
- except RuntimeError:
+ except (RuntimeError, TypeError):
+ # already disconnected
pass
occ = occurrences[cr]
tc = self.editor.textCursor()
@@ -408,8 +411,6 @@ class SearchAndReplacePanel(Panel, DelayJobRunner, Ui_SearchPanel):
offset = len_replacement - len_to_replace
tc.insertText(text)
self.editor.setTextCursor(tc)
- self.editor.textChanged.connect(self.requestSearch)
- # prevent search request due to editor textChanged
self.__removeOccurrence(cr, offset)
cr -= 1
self.__setCurrentOccurrence(cr)
@@ -420,6 +421,8 @@ class SearchAndReplacePanel(Panel, DelayJobRunner, Ui_SearchPanel):
return True
except IndexError:
return False
+ finally:
+ self.editor.textChanged.connect(self.requestSearch)
def replaceAll(self, text=None):
"""
|
Fix bug #<I>
Current selection was not update if cursor is not on a selection
|
pyQode_pyqode.core
|
train
|
c8358ba3273c18f10b72eb24feb2cf48d5c228b8
|
diff --git a/SqlServerConnection.php b/SqlServerConnection.php
index <HASH>..<HASH> 100755
--- a/SqlServerConnection.php
+++ b/SqlServerConnection.php
@@ -1,5 +1,7 @@
<?php namespace Illuminate\Database;
+use Closure;
+
class SqlServerConnection extends Connection {
/**
|
added missing "use Closure;" to SqlServerConnection.php
|
illuminate_database
|
train
|
cfd4d6198fc9f5a5ae3a3d79943c0e199daab4ab
|
diff --git a/async-data/src/main/java/com/nextfaze/asyncdata/ArrayData.java b/async-data/src/main/java/com/nextfaze/asyncdata/ArrayData.java
index <HASH>..<HASH> 100644
--- a/async-data/src/main/java/com/nextfaze/asyncdata/ArrayData.java
+++ b/async-data/src/main/java/com/nextfaze/asyncdata/ArrayData.java
@@ -215,9 +215,11 @@ public abstract class ArrayData<T> extends AbstractData<T> implements List<T> {
public final void clear() {
onClear();
int size = mData.size();
- mData.clear();
- setAvailable(Integer.MAX_VALUE);
- notifyItemRangeRemoved(0, size);
+ if (size > 0) {
+ mData.clear();
+ setAvailable(Integer.MAX_VALUE);
+ notifyItemRangeRemoved(0, size);
+ }
}
@Override
diff --git a/async-data/src/main/java/com/nextfaze/asyncdata/Data.java b/async-data/src/main/java/com/nextfaze/asyncdata/Data.java
index <HASH>..<HASH> 100644
--- a/async-data/src/main/java/com/nextfaze/asyncdata/Data.java
+++ b/async-data/src/main/java/com/nextfaze/asyncdata/Data.java
@@ -25,6 +25,8 @@ import java.util.Iterator;
* <h3>Threading</h3>
* <p>
* In general this class is not thread-safe. It's intended to be accessed from the UI thread only.
+ * <h3>Notifications</h3>
+ * Change notifications must be dispatched BEFORE the other notifications.
* </p>
*/
public interface Data<T> extends Iterable<T> {
|
Ensure ArrayData.clear() doesn't notify if already empty
|
NextFaze_power-adapters
|
train
|
4f8c3063d50de8216267969ec3cdfe2e35538523
|
diff --git a/out_request.js b/out_request.js
index <HASH>..<HASH> 100644
--- a/out_request.js
+++ b/out_request.js
@@ -381,7 +381,7 @@ TChannelOutRequest.prototype.sendArg1 = function sendArg1(arg1) {
self.emitError(errors.RequestDrained({
reason: self.drainReason
}));
- return;
+ return self;
}
self.arg1 = arg1;
@@ -404,7 +404,7 @@ TChannelOutRequest.prototype.send = function send(arg1, arg2, arg3, callback) {
self.emitError(errors.RequestDrained({
reason: self.drainReason
}));
- return;
+ return self;
}
self.sendArg1(arg1);
|
linting: [out_request] comply with consistent-return rule
|
uber_tchannel-node
|
train
|
301f62a80140c319735d37fdab80b66712722de0
|
diff --git a/h2o-bindings/bin/custom/R/gen_isolationforest.py b/h2o-bindings/bin/custom/R/gen_isolationforest.py
index <HASH>..<HASH> 100644
--- a/h2o-bindings/bin/custom/R/gen_isolationforest.py
+++ b/h2o-bindings/bin/custom/R/gen_isolationforest.py
@@ -1,10 +1,12 @@
def update_param(name, param):
+ if name == 'validation_response_column':
+ param['name'] = None
+ return param
if name == 'stopping_metric':
param['values'] = ['AUTO', 'anomaly_score']
return param
return None # param untouched
-
extensions = dict(
required_params=['training_frame', 'x'],
validate_required_params="",
@@ -13,6 +15,7 @@ parms$training_frame <- training_frame
if(!missing(x))
parms$ignored_columns <- .verify_datacols(training_frame, x)$cols_ignore
""",
+ skip_default_set_params_for=['validation_response_column', 'training_frame', 'ignored_columns'],
)
doc = dict(
|
Disable validation_response_column in R (only Python supported at first)
|
h2oai_h2o-3
|
train
|
adf5a2880969beae15bdeef712bcef96407d59f1
|
diff --git a/src/Reflection/Php/PhpClassReflectionExtension.php b/src/Reflection/Php/PhpClassReflectionExtension.php
index <HASH>..<HASH> 100644
--- a/src/Reflection/Php/PhpClassReflectionExtension.php
+++ b/src/Reflection/Php/PhpClassReflectionExtension.php
@@ -137,7 +137,20 @@ class PhpClassReflectionExtension
private function createMethods(ClassReflection $classReflection): array
{
$methods = [];
- foreach ($classReflection->getNativeReflection()->getMethods() as $methodReflection) {
+ $reflectionMethods = $classReflection->getNativeReflection()->getMethods();
+ if ($classReflection->getName() === \Closure::class || $classReflection->isSubclassOf(\Closure::class)) {
+ $hasInvokeMethod = false;
+ foreach ($reflectionMethods as $reflectionMethod) {
+ if ($reflectionMethod->getName() === '__invoke') {
+ $hasInvokeMethod = true;
+ break;
+ }
+ }
+ if (!$hasInvokeMethod) {
+ $reflectionMethods[] = $classReflection->getNativeReflection()->getMethod('__invoke');
+ }
+ }
+ foreach ($reflectionMethods as $methodReflection) {
$declaringClass = $this->broker->getClass($methodReflection->getDeclaringClass()->getName());
$phpDocParameterTypes = [];
diff --git a/src/Reflection/Php/PhpMethodReflection.php b/src/Reflection/Php/PhpMethodReflection.php
index <HASH>..<HASH> 100644
--- a/src/Reflection/Php/PhpMethodReflection.php
+++ b/src/Reflection/Php/PhpMethodReflection.php
@@ -189,6 +189,19 @@ class PhpMethodReflection implements MethodReflection
true
);
}
+ if (
+ $this->declaringClass->getName() === 'Closure'
+ && $this->reflection->getName() === '__invoke'
+ && count($this->parameters) < 1
+ ) {
+ $this->parameters[] = new DummyParameter(
+ 'args',
+ new MixedType(),
+ true,
+ false,
+ true
+ );
+ }
}
return $this->parameters;
@@ -199,8 +212,16 @@ class PhpMethodReflection implements MethodReflection
$isNativelyVariadic = $this->reflection->isVariadic();
if (
!$isNativelyVariadic
- && $this->declaringClass->getName() === 'ReflectionMethod'
- && $this->reflection->getName() === 'invoke'
+ && (
+ (
+ $this->declaringClass->getName() === 'ReflectionMethod'
+ && $this->reflection->getName() === 'invoke'
+ )
+ || (
+ $this->declaringClass->getName() === 'Closure'
+ && $this->reflection->getName() === '__invoke'
+ )
+ )
) {
return true;
}
diff --git a/tests/PHPStan/Rules/Methods/data/call-methods.php b/tests/PHPStan/Rules/Methods/data/call-methods.php
index <HASH>..<HASH> 100644
--- a/tests/PHPStan/Rules/Methods/data/call-methods.php
+++ b/tests/PHPStan/Rules/Methods/data/call-methods.php
@@ -133,4 +133,9 @@ class ClassWithToString
function () {
$foo = new ClassWithToString();
$foo->acceptsString($foo);
+
+ $closure = function () {
+
+ };
+ $closure->__invoke(1, 2, 3);
};
|
Closure::__invoke is not in PHP reflection
|
phpstan_phpstan
|
train
|
bfbcdd5a9b10fdd63bc9debbeb0ced489c86f423
|
diff --git a/lib/media.js b/lib/media.js
index <HASH>..<HASH> 100644
--- a/lib/media.js
+++ b/lib/media.js
@@ -63,7 +63,7 @@ function splice(str, index, items) {
*
* @param {{styles: Array, scripts: Array}} mediaMap
* @param {string} html
- * @returns {function}
+ * @returns {string}
*/
function appendMediaToTop(mediaMap, html) {
var index = findTop(html),
@@ -80,7 +80,7 @@ function appendMediaToTop(mediaMap, html) {
* Append at the bottom of the body tag, or if no body tag, then the bottom of the root tag.
* @param {{styles: Array, scripts: Array}} mediaMap
* @param {string} html
- * @returns {function}
+ * @returns {string}
*/
function appendMediaToBottom(mediaMap, html) {
var index = findBottom(html),
@@ -98,20 +98,29 @@ function appendMediaToBottom(mediaMap, html) {
* @returns {object}
*/
function append(data) {
- var mediaMap = data[mediaMapProperty],
- tasks = [];
+ const mediaMap = data[mediaMapProperty];
+
+ // assertion
+ if (!_.isObject(mediaMap)) {
+ return _.identity;
+ }
+
+ return function (html) {
+ // assertion
+ if (!_.isString(html)) {
+ throw new Error('Missing html parameter');
+ }
- if (mediaMap) {
if (mediaMap.styles && mediaMap.styles.length > 0) {
- tasks.push(_.partial(appendMediaToTop, mediaMap));
+ html = appendMediaToTop(mediaMap, html);
}
if (mediaMap.scripts && mediaMap.scripts.length > 0) {
- tasks.push(_.partial(appendMediaToBottom, mediaMap));
+ html = appendMediaToBottom(mediaMap, html);
}
- }
- return _.compose.apply(_, tasks);
+ return html;
+ };
}
/**
diff --git a/lib/media.test.js b/lib/media.test.js
index <HASH>..<HASH> 100644
--- a/lib/media.test.js
+++ b/lib/media.test.js
@@ -39,6 +39,22 @@ describe(_.startCase(filename), function () {
describe('append', function () {
const fn = lib[this.title];
+ it('does not throw when missing mediaMap', function () {
+ components.getStyles.onCall(0).returns([]);
+
+ expect(function () {
+ fn({})(basicHtml);
+ }).to.not.throw();
+ });
+
+ it('throws when missing html', function () {
+ components.getStyles.onCall(0).returns([]);
+
+ expect(function () {
+ fn(mediaMap({scripts:[], styles: []}))();
+ }).to.throw('Missing html parameter');
+ });
+
it('adds nothing to bottom of head when no styles', function () {
components.getStyles.onCall(0).returns([]);
diff --git a/lib/services/components.js b/lib/services/components.js
index <HASH>..<HASH> 100644
--- a/lib/services/components.js
+++ b/lib/services/components.js
@@ -49,7 +49,13 @@ function get(uri, locals) {
promise = db.get(uri).then(JSON.parse);
}
- return promise;
+ return promise.then(function (data) {
+ if (!_.isObject(data)) {
+ throw new Error('Client: Invalid data type for component at ' + uri + ' of ' + (typeof data));
+ }
+
+ return data;
+ });
}
/**
diff --git a/lib/services/components.test.js b/lib/services/components.test.js
index <HASH>..<HASH> 100644
--- a/lib/services/components.test.js
+++ b/lib/services/components.test.js
@@ -364,6 +364,14 @@ describe(_.startCase(filename), function () {
return fn('domain.com/path/components/whatever');
});
+ it('blocks get that returns non-object', function (done) {
+ sandbox.stub(db, 'get').returns(bluebird.resolve('"a"'));
+ files.getComponentModule.withArgs('whatever').returns(null);
+ fn('domain.com/path/components/whatever').then(done).catch(function () {
+ done();
+ });
+ });
+
it('gets even with bad name', function () {
sandbox.stub(db, 'get').returns(bluebird.resolve('{}'));
files.getComponentModule.withArgs('whatever').returns(null);
@@ -372,7 +380,7 @@ describe(_.startCase(filename), function () {
it('gets using component module', function () {
const ref = 'domain.com/path/components/whatever',
- someModule = sinon.spy(_.constant(bluebird.resolve('{}')));
+ someModule = sinon.spy(_.constant(bluebird.resolve({})));
files.getComponentModule.returns(someModule);
return fn(ref).then(function () {
@@ -381,10 +389,20 @@ describe(_.startCase(filename), function () {
});
});
+ it('blocks component module returning non-object', function (done) {
+ const ref = 'domain.com/path/components/whatever',
+ someModule = sinon.spy(_.constant(bluebird.resolve('{}')));
+
+ files.getComponentModule.returns(someModule);
+ fn(ref).then(done).catch(function () {
+ done();
+ });
+ });
+
it('gets using component module with locals', function () {
const ref = 'domain.com/path/components/whatever',
locals = {},
- someModule = sinon.spy(_.constant(bluebird.resolve('{}')));
+ someModule = sinon.spy(_.constant(bluebird.resolve({})));
files.getComponentModule.returns(someModule);
return fn(ref, locals).then(function () {
|
better/sooner error messaging when templating eats an exception
|
clay_amphora
|
train
|
38a8ef399d62fed64048d5652e9ccf82aec491ae
|
diff --git a/test/extended/prometheus/prometheus.go b/test/extended/prometheus/prometheus.go
index <HASH>..<HASH> 100644
--- a/test/extended/prometheus/prometheus.go
+++ b/test/extended/prometheus/prometheus.go
@@ -253,7 +253,6 @@ var _ = g.Describe("[sig-instrumentation] Prometheus", func() {
// Currently following targets do not secure their /metrics endpoints:
// job="cco-metrics" - https://bugzilla.redhat.com/show_bug.cgi?id=1809194
// job="cluster-version-operator" - https://bugzilla.redhat.com/show_bug.cgi?id=1809195
- // job="dns-default" - https://bugzilla.redhat.com/show_bug.cgi?id=1809197
// job="crio" - https://issues.redhat.com/browse/MON-1034 + https://issues.redhat.com/browse/OCPNODE-321
// job="sdn" - https://bugzilla.redhat.com/show_bug.cgi?id=1809205
// job="multus-admission-controller-monitor-service" - https://bugzilla.redhat.com/show_bug.cgi?id=1809204
@@ -263,7 +262,6 @@ var _ = g.Describe("[sig-instrumentation] Prometheus", func() {
exclude := map[string]bool{
"cco-metrics": true,
"cluster-version-operator": true,
- "dns-default": true,
"crio": true,
"sdn": true,
"multus-admission-controller-monitor-service": true,
|
Enables secure metrics tests for dns
|
openshift_origin
|
train
|
d1c58b4ba94946bfb9685dbcc544e97faf84a965
|
diff --git a/widgets/table.go b/widgets/table.go
index <HASH>..<HASH> 100644
--- a/widgets/table.go
+++ b/widgets/table.go
@@ -85,7 +85,7 @@ func (self *Table) Draw(buf *Buffer) {
// draw vertical separators
separatorXCoordinate := self.Inner.Min.X
- verticalCell := NewCell(VERTICAL_LINE, NewStyle(ColorWhite))
+ verticalCell := NewCell(VERTICAL_LINE, self.Block.BorderStyle)
for _, width := range columnWidths {
separatorXCoordinate += width
buf.SetCell(verticalCell, image.Pt(separatorXCoordinate, yCoordinate))
@@ -95,7 +95,7 @@ func (self *Table) Draw(buf *Buffer) {
yCoordinate++
// draw horizontal separator
- horizontalCell := NewCell(HORIZONTAL_LINE, NewStyle(ColorWhite))
+ horizontalCell := NewCell(HORIZONTAL_LINE, self.Block.BorderStyle)
if self.RowSeparator && yCoordinate < self.Inner.Max.Y && i != len(self.Rows)-1 {
buf.Fill(horizontalCell, image.Rect(self.Inner.Min.X, yCoordinate, self.Inner.Max.X, yCoordinate+1))
yCoordinate++
|
Set the separator styles to that of the block
|
gizak_termui
|
train
|
d695cba7f6c87e3b7d7fab27a3e762ab9f8be4f0
|
diff --git a/PelJpeg.php b/PelJpeg.php
index <HASH>..<HASH> 100644
--- a/PelJpeg.php
+++ b/PelJpeg.php
@@ -87,8 +87,7 @@ class PelJpegInvalidMarkerException extends PelException {
* get hold of the Exif data by saying:
*
* <code>
- * $jpeg = new PelJpeg();
- * $jpeg->loadFile($filename);
+ * $jpeg = new PelJpeg($filename);
* $exif = $jpeg->getExif();
* $tiff = $exif->getTiff();
* $ifd0 = $tiff->getIfd();
@@ -138,17 +137,16 @@ class PelJpeg {
/**
* Construct a new JPEG object.
*
- * The new object will be empty, use the {@link load()} or {@link
- * loadFile()} methods to load JPEG data from a {@link
- * PelDataWindow} or a file, respectively.
+ * The new object will be empty unless an argument is given from
+ * which it can initialize itself. This can either be the filename
+ * of a JPEG image, a {@link PelDataWindow} object or a PHP image
+ * resource handle.
*
- * New Exif data (in the form of a {@link PelExif} object) be
+ * New Exif data (in the form of a {@link PelExif} object) can be
* inserted with the {@link setExif()} method:
*
* <code>
- * $jpeg = new PelJpeg();
- * // Initialize $jpeg with some data:
- * $jpeg->load($data);
+ * $jpeg = new PelJpeg($data);
* // Create container for the Exif information:
* $exif = new PelExif();
* // Now Add a PelTiff object with a PelIfd object with one or more
@@ -156,8 +154,28 @@ class PelJpeg {
* $jpeg->setExif($exif);
* </code>
*/
- function __construct() {
-
+ function __construct($data = false) {
+ if ($data === false)
+ return;
+
+ if (is_string($data)) {
+ Pel::debug('Initializing PelJpeg object from %s', $data);
+ $this->loadFile($data);
+ } elseif ($data instanceof PelDataWindow) {
+ Pel::debug('Initializing PelJpeg object from PelDataWindow.');
+ $this->load($data);
+ } elseif (is_resource($data) && get_resource_type($data) == 'gd') {
+ /* The ImageJpeg() function insists on printing the bytes
+ * instead of returning them in a more civil way as a string, so
+ * we have to buffer the output... */
+ ob_start();
+ ImageJpeg($data);
+ $bytes = ob_get_clean();
+ $this->load(new PelDataWindow($bytes));
+ } else {
+ throw new PelInvalidArgumentException('Bad type for $data: %s',
+ gettype($data));
+ }
}
/**
@@ -347,6 +365,22 @@ class PelJpeg {
/**
+ * Clear any Exif data.
+ *
+ * This method will only clear the first @{link PelJpegMarker::APP1}
+ * section found (there should normally be just one).
+ */
+ function clearExif() {
+ for ($i = 0; $i < count($this->sections); $i++) {
+ if ($this->sections[$i][0] == PelJpegMarker::APP1) {
+ unset($this->sections[$i]);
+ return;
+ }
+ }
+ }
+
+
+ /**
* Append a new section.
*
* Used only when loading an image. If it used again later, then the
diff --git a/PelTiff.php b/PelTiff.php
index <HASH>..<HASH> 100644
--- a/PelTiff.php
+++ b/PelTiff.php
@@ -3,7 +3,7 @@
/* PEL: PHP Exif Library. A library with support for reading and
* writing all Exif headers in JPEG and TIFF images using PHP.
*
- * Copyright (C) 2004, 2005 Martin Geisler.
+ * Copyright (C) 2004, 2005, 2006 Martin Geisler.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -90,15 +90,30 @@ class PelTiff {
/**
* Construct a new object for holding TIFF data.
*
- * The new object will be empty, containing no {@link PelIfd}. Use
- * the {@link setIfd()} method to set the IFD explictly, or use the
- * {@link load()} method to load TIFF data from a {@link
- * PelDataWindow}.
+ * The new object will be empty (with no {@link PelIfd}) unless an
+ * argument is given from which it can initialize itself. This can
+ * either be the filename of a TIFF image or a {@link PelDataWindow}
+ * object.
+ *
+ * Use {@link setIfd()} to explicitly set the IFD.
*/
- function __construct() {
-
+ function __construct($data = false) {
+ if ($data === false)
+ return;
+
+ if (is_string($data)) {
+ Pel::debug('Initializing PelTiff object from %s', $data);
+ $this->loadFile($data);
+ } elseif ($data instanceof PelDataWindow) {
+ Pel::debug('Initializing PelTiff object from PelDataWindow.');
+ $this->load($data);
+ } else {
+ throw new PelInvalidArgumentException('Bad type for $data: %s',
+ gettype($data));
+ }
}
+
/**
* Load TIFF data.
*
|
A more convenient interface for creating new PelJpeg and PelTiff
objects: simply pass a filename or an image resource.
|
pel_pel
|
train
|
1ba90e05096518a79641e77fabdec2f3abf2aed3
|
diff --git a/src/Capture.php b/src/Capture.php
index <HASH>..<HASH> 100644
--- a/src/Capture.php
+++ b/src/Capture.php
@@ -167,7 +167,7 @@ class Capture
}
$data = array(
- 'url' => $this->url,
+ 'url' => (string) $this->url,
'width' => $this->width,
'height' => $this->height,
'imageLocation' => LocalPath::sanitize($this->imageLocation),
|
Cast the URL to string to prevent empty object serialization (#<I>)
|
microweber_screen
|
train
|
f1f019a9cee3f70c0a98b27dbaae3a82dc72df19
|
diff --git a/shoebot/__init__.py b/shoebot/__init__.py
index <HASH>..<HASH> 100644
--- a/shoebot/__init__.py
+++ b/shoebot/__init__.py
@@ -50,7 +50,7 @@ class Bot:
DEFAULT_WIDTH = 200
DEFAULT_HEIGHT = 200
- def __init__ (self, inputscript=None, targetfilename=None, canvas=None, gtkmode=False):
+ def __init__ (self, inputscript=None, targetfilename=None, canvas=None, gtkmode=False, ns=None):
self.inputscript = inputscript
self.targetfilename = targetfilename
@@ -91,7 +91,10 @@ class Bot:
width = self.WIDTH,
height = self.HEIGHT,
gtkmode = self.gtkmode)
-
+ # from nodebox
+ if ns is None:
+ ns = {}
+ self._ns = ns
#### Object
@@ -230,6 +233,14 @@ class Bot:
elif surface:
self.canvas.output(surface)
+ # from Nodebox, a function to import Nodebox libraries
+ def ximport(self, libName):
+ lib = __import__(libName)
+ self._ns[libName] = lib
+ lib._ctx = self
+ return lib
+
+
#### Core functions
def size(self,w=None,h=None):
|
added ximport function for imorting nodebox style libraries
|
shoebot_shoebot
|
train
|
85a6087cd40f06cfa80b36c2158848315a684f4a
|
diff --git a/src/IsoCodes/Iban.php b/src/IsoCodes/Iban.php
index <HASH>..<HASH> 100644
--- a/src/IsoCodes/Iban.php
+++ b/src/IsoCodes/Iban.php
@@ -103,7 +103,7 @@ class Iban implements IsoCodeInterface
/*On récupère la règle de validation en fonction du pays*/
$check = substr($iban, 4);
/*Si la règle n'est pas bonne l'IBAN n'est pas valide*/
- if (preg_match('~' . $rules[$ctr] . '~', $check) !== 1) {
+ if (preg_match('~^ . $rules[$ctr] . '$~', $check) !== 1) {
return false;
}
/*On récupère la chaine qui permet de calculer la validation*/
|
Make sure that IBAN length is correctly checked
|
ronanguilloux_IsoCodes
|
train
|
e076e6abf0268d07e4c40b9062a4610428da3c22
|
diff --git a/js/forms.js b/js/forms.js
index <HASH>..<HASH> 100644
--- a/js/forms.js
+++ b/js/forms.js
@@ -560,7 +560,9 @@
collection.find('li.selected').removeClass('selected');
var option = $(newOption);
option.addClass('selected');
- options.scrollTo(option);
+ if (!multiple) {
+ options.scrollTo(option);
+ }
}
};
|
Remove scrollTo selected element in multiple select
|
Dogfalo_materialize
|
train
|
50874b2f1801b6ad2884803e98bbd220ef4af1bd
|
diff --git a/test/ral/manager/type.rb b/test/ral/manager/type.rb
index <HASH>..<HASH> 100755
--- a/test/ral/manager/type.rb
+++ b/test/ral/manager/type.rb
@@ -758,7 +758,7 @@ class TestType < Test::Unit::TestCase
exec = mk.call(4, :parent => comp)
assert_equal("/server/Exec[exec4]", exec.path)
- comp = Puppet::Type.newcomponent :type => "whatever", :name => "main[top]"
+ comp = Puppet::Type.newcomponent :type => "whatever", :name => "class[main]"
exec = mk.call(5, :parent => comp)
assert_equal("//Exec[exec5]", exec.path)
|
Fixing a path test. I have now made the path stuff a lot cleaner, but it apparently broke this test.
|
puppetlabs_puppet
|
train
|
4339863844f8fccfaa8a5c66567bee7f0a531425
|
diff --git a/lib/locomotive/steam/decorators/i18n_decorator.rb b/lib/locomotive/steam/decorators/i18n_decorator.rb
index <HASH>..<HASH> 100644
--- a/lib/locomotive/steam/decorators/i18n_decorator.rb
+++ b/lib/locomotive/steam/decorators/i18n_decorator.rb
@@ -51,6 +51,10 @@ module Locomotive
end
end
+ def __with_default_locale__(&block)
+ __with_locale__(self.__default_locale__, &block)
+ end
+
def __freeze_locale__
@__frozen_locale__ = true
end
diff --git a/lib/locomotive/steam/decorators/template_decorator.rb b/lib/locomotive/steam/decorators/template_decorator.rb
index <HASH>..<HASH> 100644
--- a/lib/locomotive/steam/decorators/template_decorator.rb
+++ b/lib/locomotive/steam/decorators/template_decorator.rb
@@ -11,12 +11,16 @@ module Locomotive
if respond_to?(:template_path) && template_path
source_from_template_file
else
- self.source
+ self.source.blank? ? source_in_default_locale : self.source
end
end
private
+ def source_in_default_locale
+ self.__with_default_locale__ { self.source }
+ end
+
def source_from_template_file
source = File.read(template_path).force_encoding('utf-8')
diff --git a/spec/unit/decorators/i18n_decorator_spec.rb b/spec/unit/decorators/i18n_decorator_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/decorators/i18n_decorator_spec.rb
+++ b/spec/unit/decorators/i18n_decorator_spec.rb
@@ -46,9 +46,28 @@ describe Locomotive::Steam::Decorators::I18nDecorator do
describe 'using the default locale' do
- let(:locale) { 'de' }
- let(:default_locale) { 'en' }
- it { expect(decorated.title).to eq 'Hello world!' }
+ let(:default_locale) { 'en' }
+
+ context 'unknown locale' do
+
+ let(:locale) { 'de' }
+
+ it { expect(decorated.title).to eq 'Hello world!' }
+
+ end
+
+ context 'existing locale' do
+
+ let(:locale) { 'fr' }
+
+ it 'uses the default locale and get back to the previous one' do
+ decorated.__with_default_locale__ do
+ expect(decorated.title).to eq 'Hello world!'
+ end
+ expect(decorated.__locale__).to eq :fr
+ end
+
+ end
end
diff --git a/spec/unit/decorators/template_decorator_spec.rb b/spec/unit/decorators/template_decorator_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/decorators/template_decorator_spec.rb
+++ b/spec/unit/decorators/template_decorator_spec.rb
@@ -5,7 +5,7 @@ describe Locomotive::Steam::Decorators::TemplateDecorator do
let(:template_path) { 'template.liquid' }
let(:page) { instance_double('Page', localized_attributes: [], template_path: template_path) }
let(:locale) { 'fr' }
- let(:default_locale) { nil }
+ let(:default_locale) { 'en' }
let(:decorated) { described_class.new(page, locale, default_locale) }
describe '#liquid_source' do
@@ -18,6 +18,14 @@ describe Locomotive::Steam::Decorators::TemplateDecorator do
it { is_expected.to eq 'Lorem ipsum' }
+ context 'Raw template' do
+
+ let(:page) { instance_double('Page', localized_attributes: [:source], source: { en: 'Lorem ipsum [EN]', fr: '' }) }
+
+ it { is_expected.to eq 'Lorem ipsum [EN]' }
+
+ end
+
context 'HAML file' do
let(:template_path) { 'template.liquid.haml' }
|
if no liquid template in the current locale, take the one in the default locale
|
locomotivecms_steam
|
train
|
c3199367adcfc5720859c6d73a3d3aa3549899e4
|
diff --git a/pelix/services/configadmin.py b/pelix/services/configadmin.py
index <HASH>..<HASH> 100644
--- a/pelix/services/configadmin.py
+++ b/pelix/services/configadmin.py
@@ -296,6 +296,10 @@ class Configuration(object):
:param ldap_filter: A parsed LDAP filter object
:return: True if the properties of this configuration matches the filter
"""
+ if not self.is_valid():
+ # Do not test invalid configurations
+ return False
+
return ldap_filter.matches(self.__properties)
#-------------------------------------------------------------------------------
|
Invalid configuration can't match a filter
|
tcalmant_ipopo
|
train
|
ef36e732d29d0a2dd43247e623fa0baff3b2efcb
|
diff --git a/satpy/readers/clavrx.py b/satpy/readers/clavrx.py
index <HASH>..<HASH> 100644
--- a/satpy/readers/clavrx.py
+++ b/satpy/readers/clavrx.py
@@ -90,7 +90,7 @@ class CLAVRXFileHandler(HDF4FileHandler):
@property
def end_time(self):
- return self.filename_info['end_time']
+ return self.filename_info.get('end_time', self.start_time)
def available_dataset_ids(self):
"""Automatically determine datasets provided by this file"""
|
Fix clavrx reader when filenames don't have end_time
|
pytroll_satpy
|
train
|
f9fa8245986c71854ede58476a401da87605a908
|
diff --git a/src/arcrest/manageags/_services.py b/src/arcrest/manageags/_services.py
index <HASH>..<HASH> 100644
--- a/src/arcrest/manageags/_services.py
+++ b/src/arcrest/manageags/_services.py
@@ -230,6 +230,23 @@ class Services(BaseAGSServer):
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port)
+ #----------------------------------------------------------------------
+ def listFolderPermissions(self,folderName):
+ """
+ Lists principals which have permissions for the folder.
+ Input:
+ folderName - name of the folder to list permissions for
+ Output:
+ JSON Message as Dictionary
+ """
+ uURL = self._url + "/%s/permissions" % folderName
+ params = {
+ "f" : "json",
+ }
+ return self._do_post(url=uURL, param_dict=params,
+ securityHandler=self._securityHandler,
+ proxy_url=self._proxy_url,
+ proxy_port=self._proxy_port)
#----------------------------------------------------------------------
def cleanPermsissions(self, principal):
"""
|
Added listFolderPermissions() in _services.py
New function that lists principals which have permissions for the folder (goes into arcrest\manageags).
|
Esri_ArcREST
|
train
|
faef9725797d37b2525c17c43305fd36668f0bf6
|
diff --git a/src/voku/cache/Cache.php b/src/voku/cache/Cache.php
index <HASH>..<HASH> 100644
--- a/src/voku/cache/Cache.php
+++ b/src/voku/cache/Cache.php
@@ -363,9 +363,14 @@ class Cache implements iCache
public function setItem($key, $value, $ttl = 0)
{
$storeKey = $this->calculateStoreKey($key);
- $serialized = $this->serializer->serialize($value);
- if ($this->adapter instanceof iAdapter) {
+ if (
+ $this->adapter instanceof iAdapter
+ &&
+ $this->serializer instanceof iSerializer
+ ) {
+ $serialized = $this->serializer->serialize($value);
+
if ($ttl) {
return $this->adapter->setExpired($storeKey, $serialized, $ttl);
} else {
@@ -427,7 +432,7 @@ class Cache implements iCache
// for testing with dev-address
$noDev = isset($_GET['noDev']) ? (int)$_GET['noDev'] : 0;
- $remoteAddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : false;
+ $remoteAddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'NO_REMOTE_ADDR';
if
(
|
[+]: fixed some more php-warnings v3
|
voku_simple-cache
|
train
|
d9f5e86a2098ce49b85fae6b60e1fc088181f2a6
|
diff --git a/src/Mutator/Unwrap/UnwrapArrayChunk.php b/src/Mutator/Unwrap/UnwrapArrayChunk.php
index <HASH>..<HASH> 100644
--- a/src/Mutator/Unwrap/UnwrapArrayChunk.php
+++ b/src/Mutator/Unwrap/UnwrapArrayChunk.php
@@ -47,10 +47,10 @@ final class UnwrapArrayChunk extends AbstractUnwrapMutator
{
return new Definition(
<<<'TXT'
-Replaces an `array_column` function call with its first operand. For example:
+Replaces an `array_chunk` function call with its first operand. For example:
```php
-$x = array_column($array, 'id');
+$x = array_chunk($array, 2);
```
Will be mutated to:
@@ -58,7 +58,6 @@ Will be mutated to:
```php
$x = $array;
```
-
TXT
,
MutatorCategory::SEMANTIC_REDUCTION,
diff --git a/src/Mutator/Unwrap/UnwrapArrayColumn.php b/src/Mutator/Unwrap/UnwrapArrayColumn.php
index <HASH>..<HASH> 100644
--- a/src/Mutator/Unwrap/UnwrapArrayColumn.php
+++ b/src/Mutator/Unwrap/UnwrapArrayColumn.php
@@ -47,10 +47,10 @@ final class UnwrapArrayColumn extends AbstractUnwrapMutator
{
return new Definition(
<<<'TXT'
-Replaces an `array_chunk` function call with its first operand. For example:
+Replaces an `array_column` function call with its first operand. For example:
```php
-$x = array_chunk($array, 2);
+$x = array_column($array, 'id');
```
Will be mutated to:
|
Fix ArrayChunk and ArrayColumn mutator definitions (#<I>)
|
infection_infection
|
train
|
77f61a98a61719ceaf9507723a3fe84a7e0dc925
|
diff --git a/lib/overwrite.rb b/lib/overwrite.rb
index <HASH>..<HASH> 100644
--- a/lib/overwrite.rb
+++ b/lib/overwrite.rb
@@ -128,7 +128,7 @@ end
class File
# @return [String] mime_type including charset using linux cmd command
def mime_type
- `file -ib #{self.path}`.chomp
+ `file -ib '#{self.path}'`.chomp
end
end
|
fix mime_type for files with spaces
|
opentox_lazar
|
train
|
7b0e9c1bebc675a25f78cd9315e01b0b97c506f2
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -187,13 +187,12 @@ module.exports = function (opts) {
function setupRPC (stream, manf, isClient) {
var rpc = Muxrpc(create.manifest, manf || create.manifest)(api, stream.auth)
var rpcStream = rpc.createStream()
- if(timeout_inactivity > 0) rpcStream = Inactive(rpcStream, timeout_inactivity)
+ var id = rpc.id = '@'+u.toId(stream.remote)
+ if(timeout_inactivity > 0 && id !== rpc.id) rpcStream = Inactive(rpcStream, timeout_inactivity)
rpc.meta = stream.meta
pull(stream, rpcStream, stream)
- var id = rpc.id = '@'+u.toId(stream.remote)
-
//keep track of current connections.
if(!peers[id]) peers[id] = []
peers[id].push(rpc)
|
Don't timeout RPC from self for inactivity
|
ssbc_secret-stack
|
train
|
c39da6598358f3e88176b1e61324e42e041848f5
|
diff --git a/lib/listen/adapter/bsd.rb b/lib/listen/adapter/bsd.rb
index <HASH>..<HASH> 100644
--- a/lib/listen/adapter/bsd.rb
+++ b/lib/listen/adapter/bsd.rb
@@ -58,6 +58,7 @@ module Listen
def _configure(directory, &_callback)
@worker ||= KQueue::Queue.new
+ @callback = _callback
# use Record to make a snapshot of dir, so we
# can detect new files
_find(directory.to_s) { |path| _watch_file(path, @worker) }
@@ -109,7 +110,7 @@ module Listen
end
def _watch_file(path, queue)
- queue.watch_file(path, *options.events, &_worker_callback)
+ queue.watch_file(path, *options.events, &@callback)
end
# Quick rubocop workaround
|
Use the provided event callback.
We have no _worker_callback() defined, so save the _callback passed to
_configure() and use it when an event occurs.
|
guard_listen
|
train
|
d4a3ba4da1e563d4e049ab48b9750cab8b99f010
|
diff --git a/h2o-core/src/main/java/hex/Model.java b/h2o-core/src/main/java/hex/Model.java
index <HASH>..<HASH> 100755
--- a/h2o-core/src/main/java/hex/Model.java
+++ b/h2o-core/src/main/java/hex/Model.java
@@ -265,7 +265,7 @@ public abstract class Model<M extends Model<M,P,O>, P extends Model.Parameters,
}
count++;
}
- xs ^= (train() == null ? 43 : train().checksum()) * (_valid == null ? 17 : valid().checksum());
+ xs ^= (train() == null ? 43 : train().checksum()) * (valid() == null ? 17 : valid().checksum());
return xs;
}
}
|
Fix NPE in model checksum.
|
h2oai_h2o-3
|
train
|
2b81fb8424eb4ba8c815c856075509d686c383a0
|
diff --git a/pkg/dockerscript/scanner/extra.go b/pkg/dockerscript/scanner/extra.go
index <HASH>..<HASH> 100644
--- a/pkg/dockerscript/scanner/extra.go
+++ b/pkg/dockerscript/scanner/extra.go
@@ -14,7 +14,7 @@ func detectIdent(ch rune) bool {
if unicode.IsDigit(ch) {
return true
}
- if strings.ContainsRune("_:/+-@%^.!", ch) {
+ if strings.ContainsRune("_:/+-@%^.!=", ch) {
return true
}
return false
|
dockerscript: '=' is not a special character
Docker-DCO-<I>-
|
containers_storage
|
train
|
f268ee20fd914f23288dfea8e94d8de69ee391b4
|
diff --git a/news-bundle/src/Resources/contao/modules/ModuleNews.php b/news-bundle/src/Resources/contao/modules/ModuleNews.php
index <HASH>..<HASH> 100644
--- a/news-bundle/src/Resources/contao/modules/ModuleNews.php
+++ b/news-bundle/src/Resources/contao/modules/ModuleNews.php
@@ -406,7 +406,7 @@ abstract class ModuleNews extends Module
return sprintf('<a href="%s" title="%s"%s>%s</a>',
$objArticle->url,
specialchars(sprintf($GLOBALS['TL_LANG']['MSC']['open'], $objArticle->url)),
- ($objArticle->target ? (($objPage->outputFormat == 'xhtml') ? ' onclick="window.open(this.href);return false"' : ' target="_blank"') : ''),
+ ($objArticle->target ? (($objPage->outputFormat == 'xhtml') ? ' onclick="return !window.open(this.href)"' : ' target="_blank"') : ''),
$strLink);
}
}
|
[News] Open popup windows so they are not blocked (see #<I>)
|
contao_contao
|
train
|
b2b35baf26e360cb001ceee1d4e93c9bc1a35310
|
diff --git a/test/issue-13.js b/test/issue-13.js
index <HASH>..<HASH> 100644
--- a/test/issue-13.js
+++ b/test/issue-13.js
@@ -16,4 +16,26 @@ describe( 'Issues', function() {
})
+ context( '#22', function() {
+
+ specify( 'should parse the "Subject" header correctly', function() {
+ var header = `Subject: =?utf-8?B?QVc6IEdyb8OfZSBHZWJ1cnRzdGFncy1QYXJ0eSBpbSBN?=\r\n\t=?utf-8?B?YWkgKGljaCBmZWllcmUgbmFjaHRyw6RnbGljaCkh?=\r\n\r\n`
+ var mail = new Envelope( header )
+ assert.strictEqual( mail.header.get( 'subject' ), 'AW: Große Geburtstags-Party im Mai (ich feiere nachträglich)!' )
+ })
+
+ })
+
+ context( '#23', function() {
+
+ specify( 'should parse the "From" header correctly', function() {
+ var header = 'From: "Almaifd, Tim" <T.Almaifd@redacted.com>\r\n\r\n'
+ var mail = new Envelope( header )
+ assert.deepEqual( mail.header.get( 'from' ), [
+ { name: 'Almaifd, Tim', address: 'T.Almaifd@redacted.com' },
+ ])
+ })
+
+ })
+
})
|
test: Add tests for issues #<I>, and #<I>
|
jhermsmeier_node-envelope
|
train
|
b72c13bd5084c0d23e29a250afa243b9dac4d9fa
|
diff --git a/src/Discord/Parts/WebSockets/MessageReaction.php b/src/Discord/Parts/WebSockets/MessageReaction.php
index <HASH>..<HASH> 100644
--- a/src/Discord/Parts/WebSockets/MessageReaction.php
+++ b/src/Discord/Parts/WebSockets/MessageReaction.php
@@ -211,4 +211,42 @@ class MessageReaction extends Part
return null;
}
+
+ /**
+ * Delete this reaction
+ *
+ * @param int|null $type The type of deletion to perform.
+ *
+ * @return ExtendedPromiseInterface
+ */
+ public function delete(?int $type = null): ExtendedPromiseInterface
+ {
+ if (is_null($type)) {
+ if ($this->user_id == $this->discord->id) {
+ $type = Message::REACT_DELETE_ME;
+ } else {
+ $type = Message::REACT_DELETE_ID;
+ }
+ }
+
+ $emoticon = $this->emoji->toReactionString();
+
+ switch ($type) {
+ case Message::REACT_DELETE_ALL:
+ $url = Endpoint::bind(Endpoint::MESSAGE_REACTION_ALL, $this->channel_id, $this->message_id);
+ break;
+ case Message::REACT_DELETE_ME:
+ $url = Endpoint::bind(Endpoint::OWN_MESSAGE_REACTION, $this->channel_id, $this->message_id, $emoticon);
+ break;
+ case Message::REACT_DELETE_EMOJI:
+ $url = Endpoint::bind(Endpoint::MESSAGE_REACTION_EMOJI, $this->channel_id, $this->message_id, $emoticon);
+ break;
+ case Message::REACT_DELETE_ID:
+ default:
+ $url = Endpoint::bind(Endpoint::USER_MESSAGE_REACTION, $this->channel_id, $this->message_id, $emoticon, $this->user_id);
+ break;
+ }
+
+ return $this->http->delete($url);
+ }
}
|
Add delete method in MessageReaction (#<I>)
* Add delete method in MessageReaction
Useful to delete reaction on message reaction events that might have partial data
* Remove type checking, default to this reaction id
|
teamreflex_DiscordPHP
|
train
|
b27e726043f0c7b822ebcb7c3124c5751e2e2b28
|
diff --git a/src/Spekkionu/Assetcachebuster/Console/GenerateCommand.php b/src/Spekkionu/Assetcachebuster/Console/GenerateCommand.php
index <HASH>..<HASH> 100644
--- a/src/Spekkionu/Assetcachebuster/Console/GenerateCommand.php
+++ b/src/Spekkionu/Assetcachebuster/Console/GenerateCommand.php
@@ -52,9 +52,9 @@ class GenerateCommand extends Command
*
* @return void
*/
- public function fire()
+ public function handle()
{
- $this->line('Generating new asset hash. Environment: <comment>'.$this->laravel->make('env').'</comment>');
+ $this->line('Generating new asset hash. Environment: <comment>' . $this->laravel->make('env') . '</comment>');
$hash = $this->hashReplacer->replaceHash();
@@ -63,4 +63,5 @@ class GenerateCommand extends Command
$msg = "New hash {$hash} generated.";
$this->info($msg);
}
+
}
|
Renamed the fire function to handle
|
spekkionu_laravel-assetcachebuster
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.