hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
6da1410bc26944551672d19808e424c686198f2d | diff --git a/Source/com/drew/metadata/Directory.java b/Source/com/drew/metadata/Directory.java
index <HASH>..<HASH> 100644
--- a/Source/com/drew/metadata/Directory.java
+++ b/Source/com/drew/metadata/Directory.java
@@ -896,7 +896,7 @@ public abstract class Directory
}
// if the date string has time zone information, it supersedes the timeZone parameter
- Pattern timeZonePattern = Pattern.compile("(Z|[+-]\\d\\d:\\d\\d)$");
+ Pattern timeZonePattern = Pattern.compile("(Z|[+-]\\d\\d:\\d\\d|[+-]\\d\\d\\d\\d)$");
Matcher timeZoneMatcher = timeZonePattern.matcher(dateString);
if (timeZoneMatcher.find()) {
timeZone = TimeZone.getTimeZone("GMT" + timeZoneMatcher.group().replaceAll("Z", "")); | Improve parsing of timezones in date strings | drewnoakes_metadata-extractor | train |
326d62aea46960597603bce0a1c6dd007310f3a6 | diff --git a/cmd/camput/files.go b/cmd/camput/files.go
index <HASH>..<HASH> 100644
--- a/cmd/camput/files.go
+++ b/cmd/camput/files.go
@@ -156,7 +156,11 @@ func (c *fileCmd) RunCommand(up *Uploader, args []string) error {
}
for _, filename := range args {
- if fi, err := os.Stat(filename); err == nil && fi.IsDir() {
+ fi, err := os.Stat(filename)
+ if err != nil {
+ return err
+ }
+ if fi.IsDir() {
t := up.NewTreeUpload(filename)
t.Start()
lastPut, err = t.Wait()
diff --git a/pkg/blobserver/remote/remote.go b/pkg/blobserver/remote/remote.go
index <HASH>..<HASH> 100644
--- a/pkg/blobserver/remote/remote.go
+++ b/pkg/blobserver/remote/remote.go
@@ -55,7 +55,14 @@ func newFromConfig(_ blobserver.Loader, config jsonconfig.Obj) (storage blobserv
client: client,
}
if !skipStartupCheck {
- // TODO: do a server stat or something to check password
+ // Do a quick dummy operation to check that our credentials are
+ // correct.
+ // TODO(bradfitz,mpl): skip this operation smartly if it turns out this is annoying/slow for whatever reason.
+ c := make(chan blobref.SizedBlobRef, 1)
+ err = sto.EnumerateBlobs(c, "", 1, 0)
+ if err != nil {
+ return nil, err
+ }
}
return sto, nil
}
@@ -94,9 +101,9 @@ func (sto *remoteStorage) MaxEnumerate() int { return 1000 }
func (sto *remoteStorage) EnumerateBlobs(dest chan<- blobref.SizedBlobRef, after string, limit int, wait time.Duration) error {
return sto.client.EnumerateBlobsOpts(dest, client.EnumerateOpts{
- After: after,
- MaxWait: wait,
- Limit: limit,
+ After: after,
+ MaxWait: wait,
+ Limit: limit,
})
} | camput: actually catch errors when trying to upload,
also added startupcheck for remote blobserver
Change-Id: Id9f<I>c6fd3fdf<I>f2b<I>f3e<I>b<I>d | perkeep_perkeep | train |
41d809a81d1c6ee406806b8a43f4a8b948884fd2 | diff --git a/py/selenium/webdriver/remote/webdriver.py b/py/selenium/webdriver/remote/webdriver.py
index <HASH>..<HASH> 100644
--- a/py/selenium/webdriver/remote/webdriver.py
+++ b/py/selenium/webdriver/remote/webdriver.py
@@ -130,16 +130,18 @@ class WebDriver(object):
then default LocalFileDetector() will be used.
- options - instance of a driver options.Options class
"""
- if desired_capabilities is None:
- raise WebDriverException("Desired Capabilities can't be None")
- if not isinstance(desired_capabilities, dict):
- raise WebDriverException("Desired Capabilities must be a dictionary")
+ capabilities = {}
+ if options is not None:
+ capabilities = options.to_capabilities()
+ if desired_capabilities is not None:
+ if not isinstance(desired_capabilities, dict):
+ raise WebDriverException("Desired Capabilities must be a dictionary")
+ else:
+ capabilities.update(desired_capabilities)
if proxy is not None:
warnings.warn("Please use FirefoxOptions to set proxy",
DeprecationWarning)
- proxy.add_to_capabilities(desired_capabilities)
- if options is not None:
- desired_capabilities.update(options.to_capabilities())
+ proxy.add_to_capabilities(capabilities)
self.command_executor = command_executor
if type(self.command_executor) is bytes or isinstance(self.command_executor, str):
self.command_executor = RemoteConnection(command_executor, keep_alive=keep_alive)
@@ -151,7 +153,7 @@ class WebDriver(object):
if browser_profile is not None:
warnings.warn("Please use FirefoxOptions to set browser profile",
DeprecationWarning)
- self.start_session(desired_capabilities, browser_profile)
+ self.start_session(capabilities, browser_profile)
self._switch_to = SwitchTo(self)
self._mobile = Mobile(self)
self.file_detector = file_detector or LocalFileDetector() | [py] allow Remote webdriver when only given Options class
also, use Options.to_capabilties as base caps | SeleniumHQ_selenium | train |
1b501cd8d4eb5b47210853f926ef0ceb79bbca48 | diff --git a/pyimgur/__init__.py b/pyimgur/__init__.py
index <HASH>..<HASH> 100644
--- a/pyimgur/__init__.py
+++ b/pyimgur/__init__.py
@@ -30,6 +30,10 @@ def get_album_or_image(json, imgur):
class Basic_object(object):
"""Contains the basic functionality shared by a lot of PyImgurs classes."""
+ def __init__(self, json_dict, imgur):
+ self.imgur = imgur
+ self.populate(json_dict)
+
def __repr__(self):
return "<%s %s>" % (type(self).__name__, self.id)
@@ -40,8 +44,7 @@ class Basic_object(object):
class Account(Basic_object):
def __init__(self, json_dict, imgur):
- self.imgur = imgur
- self.populate(json_dict)
+ super(Account, self).__init__(json_dict, imgur)
# Overrides __repr__ method in Basic_object
def __repr__(self):
@@ -163,10 +166,9 @@ class Account(Basic_object):
class Album(Basic_object):
def __init__(self, json_dict, imgur):
+ super(Album, self).__init__(json_dict, imgur)
self.deletehash = None
self.images = []
- self.imgur = imgur
- self.populate(json_dict)
def add_images(self, ids):
"""Add images to the album."""
@@ -222,9 +224,8 @@ class Album(Basic_object):
class Comment(Basic_object):
def __init__(self, json_dict, imgur):
+ super(Comment, self).__init__(json_dict, imgur)
self.deletehash = None
- self.imgur = imgur
- self.populate(json_dict)
# Possible via webend, not exposed via json
# self.permalink == ?!??!
@@ -293,9 +294,8 @@ class Gallery_item(object):
class Image(Basic_object):
def __init__(self, json_dict, imgur):
+ super(Image, self).__init__(json_dict, imgur)
self.deletehash = None
- self.imgur = imgur
- self.populate(json_dict)
def delete(self):
"""Delete the image."""
@@ -457,12 +457,14 @@ class Imgur:
class Message(object):
# Requires login to test
- pass
+ def __init__(self, json_dict, imgur):
+ super(Message, self).__init__(json_dict, imgur)
class Notification(object):
# Requires login to test
- pass
+ def __init__(self, json_dict, imgur):
+ super(Notification, self).__init__(json_dict, imgur)
# Gallery_album and Gallery_image are placed at the end as they need to inherit
diff --git a/pyimgur/test/init_test.py b/pyimgur/test/init_test.py
index <HASH>..<HASH> 100644
--- a/pyimgur/test/init_test.py
+++ b/pyimgur/test/init_test.py
@@ -43,8 +43,7 @@ class Empty(pyimgur.Basic_object):
def test_populate():
info = {'score': 1, 'hello': 'world'}
- inst = Empty()
- inst.populate(info)
+ inst = Empty(info, None)
assert 'score' in vars(inst)
assert 'hello' in vars(inst)
assert inst.score == 1 | Move attr population into Base_object | Damgaard_PyImgur | train |
07af2b0324aaee78a2c7df65e22e89644f0659ec | diff --git a/hawkular-alerts-engine/src/main/java/org/hawkular/alerts/engine/impl/CassCluster.java b/hawkular-alerts-engine/src/main/java/org/hawkular/alerts/engine/impl/CassCluster.java
index <HASH>..<HASH> 100644
--- a/hawkular-alerts-engine/src/main/java/org/hawkular/alerts/engine/impl/CassCluster.java
+++ b/hawkular-alerts-engine/src/main/java/org/hawkular/alerts/engine/impl/CassCluster.java
@@ -23,6 +23,7 @@ import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
+import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@@ -35,6 +36,7 @@ import javax.ejb.AccessTimeout;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.inject.Produces;
+import javax.net.ssl.SSLContext;
import org.cassalog.core.Cassalog;
import org.cassalog.core.CassalogBuilder;
@@ -44,10 +46,12 @@ import org.infinispan.manager.EmbeddedCacheManager;
import org.jboss.logging.Logger;
import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.JdkSSLOptions;
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.ProtocolVersion;
import com.datastax.driver.core.QueryOptions;
import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.SSLOptions;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.SocketOptions;
import com.google.common.collect.ImmutableMap;
@@ -108,7 +112,12 @@ public class CassCluster {
private static final String ALERTS_CASSANDRA_OVERWRITE = "hawkular-alerts.cassandra-overwrite";
private static final String ALERTS_CASSANDRA_OVERWRITE_ENV = "CASSANDRA_OVERWRITE";
- private String keyspace;
+ /*
+ True/false flag to use SSL communication with Cassandra cluster
+ */
+ private static final String ALERTS_CASSANDRA_USESSL = "hawkular-alerts.cassandra-use-ssl";
+ private static final String ALERTS_CASSANDRA_USESSL_ENV = "CASSANDRA_USESSL";
+
private int attempts;
private int timeout;
private String cqlPort;
@@ -116,6 +125,8 @@ public class CassCluster {
private int connTimeout;
private int readTimeout;
private boolean overwrite = false;
+ private String keyspace;
+ private boolean cassandraUseSSL;
private Cluster cluster = null;
@@ -151,6 +162,8 @@ public class CassCluster {
overwrite = Boolean.parseBoolean(AlertProperties.getProperty(ALERTS_CASSANDRA_OVERWRITE,
ALERTS_CASSANDRA_OVERWRITE_ENV, "false"));
keyspace = AlertProperties.getProperty(ALERTS_CASSANDRA_KEYSPACE, "hawkular_alerts");
+ cassandraUseSSL = Boolean.parseBoolean(AlertProperties.getProperty(ALERTS_CASSANDRA_USESSL,
+ ALERTS_CASSANDRA_USESSL_ENV, "false"));
}
@PostConstruct
@@ -185,6 +198,18 @@ public class CassCluster {
clusterBuilder.withSocketOptions(socketOptions);
}
+ if (cassandraUseSSL) {
+ SSLOptions sslOptions = null;
+ try {
+ String[] defaultCipherSuites = { "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA" };
+ sslOptions = JdkSSLOptions.builder().withSSLContext(SSLContext.getDefault())
+ .withCipherSuites(defaultCipherSuites).build();
+ clusterBuilder.withSSL(sslOptions);
+ } catch (NoSuchAlgorithmException e) {
+ throw new RuntimeException("SSL support is required but is not available in the JVM.", e);
+ }
+ }
+
/*
It might happen that alerts component is faster than embedded cassandra deployed in hawkular.
We will provide a simple attempt/retry loop to avoid issues at initialization. | HWKALERTS-<I> Support SSL on Cassandra connections (#<I>) | hawkular_hawkular-alerts | train |
fe846ae19c2420c6fc95f525f90143d3083d24a9 | diff --git a/src/python/twitter/pants/tasks/jvm_compile/analysis_tools.py b/src/python/twitter/pants/tasks/jvm_compile/analysis_tools.py
index <HASH>..<HASH> 100644
--- a/src/python/twitter/pants/tasks/jvm_compile/analysis_tools.py
+++ b/src/python/twitter/pants/tasks/jvm_compile/analysis_tools.py
@@ -30,7 +30,7 @@ class AnalysisTools(object):
splits, output_paths = zip(*split_path_pairs)
split_analyses = analysis.split(splits, catchall_path is not None)
if catchall_path is not None:
- output_paths.append(catchall_path)
+ output_paths = output_paths + (catchall_path, )
for analysis, path in zip(split_analyses, output_paths):
analysis.write_to_path(path) | Fix a minor bug.
You can't append to a tuple...
Auditors: pl
(sapling split of <I>b<I>e<I>d2c<I>d<I>f<I>e3b<I>f<I>ae<I>eb3) | pantsbuild_pants | train |
b151a49266e29ffc30ed42ef8b05af82a0fbed2a | diff --git a/salesforce/backend/introspection.py b/salesforce/backend/introspection.py
index <HASH>..<HASH> 100644
--- a/salesforce/backend/introspection.py
+++ b/salesforce/backend/introspection.py
@@ -192,6 +192,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
def get_indexes(self, cursor, table_name):
"""
+ DEPRECATED
Returns a dictionary of fieldname -> infodict for the given table,
where each infodict is in the format:
{'primary_key': boolean representing whether it's the primary key,
@@ -206,6 +207,34 @@ class DatabaseIntrospection(BaseDatabaseIntrospection):
)
return result
+ def get_constraints(self, cursor, table_name):
+ """
+ Retrieves any constraints or keys (unique, pk, fk, check, index)
+ across one or more columns.
+
+ Returns a dict mapping constraint names to their attributes,
+ where attributes is a dict with keys:
+ * columns: List of columns this covers
+ * primary_key: True if primary key, False otherwise
+ * unique: True if this is a unique constraint, False otherwise
+ * foreign_key: (table, column) of target, or None
+ * check: True if check constraint, False otherwise
+ * index: True if index, False otherwise.
+ * orders: The order (ASC/DESC) defined for the columns of indexes
+ * type: The type of the index (btree, hash, etc.)
+ """
+ result = {}
+ for field in self.table_description_cache(table_name)['fields']:
+ if field['type'] in ('id', 'reference') or field['unique']:
+ result[field['name']] = dict(
+ columns=field['name'],
+ primary_key=(field['type'] == 'id'),
+ unique=field['unique'],
+ foreign_key=(field['referenceTo'], 'id'),
+ check=False,
+ )
+ return result
+
def get_additional_meta(self, table_name):
item = [x for x in self.table_list_cache['sobjects'] if x['name'] == table_name][0]
return ["verbose_name = '%s'" % item['label'],
diff --git a/tests/inspectdb/slow_test.py b/tests/inspectdb/slow_test.py
index <HASH>..<HASH> 100644
--- a/tests/inspectdb/slow_test.py
+++ b/tests/inspectdb/slow_test.py
@@ -16,16 +16,16 @@ import os
import sys
import django
-from salesforce.backend.base import SalesforceError
-
-from tests.inspectdb import models as mdl
-
sys.path.insert(0, '.')
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.inspectdb.settings'
-from django.db import connections # NOQA
-# The same "django.setup()" is used by manage.py subcommands in Django
django.setup()
+# there 3 lines- must be imported after: path, environ, django.setup()
+from django.db import connections # NOQA
+from tests.inspectdb import models as mdl # NOQA
+from salesforce.backend.base import SalesforceError # NOQA
+
+
sf = connections['salesforce']
@@ -72,6 +72,8 @@ def run():
'StaticResource', 'WebLink',
# This is not writable due to 'NamespacePrefix' field
'ApexPage',
+ # It does not update the 'last_modified_date' field
+ 'AppMenuItem',
# Some Leads are not writable becase they are coverted to Contact
'Lead',
# Insufficient access rights on cross-reference id | Fixed introspection and slow_test.py for inspectdb | django-salesforce_django-salesforce | train |
ee8f9f5331c917e43ec3998b5d7233b9c3475aee | diff --git a/pyoko/db/queryset.py b/pyoko/db/queryset.py
index <HASH>..<HASH> 100644
--- a/pyoko/db/queryset.py
+++ b/pyoko/db/queryset.py
@@ -281,7 +281,7 @@ class QuerySet(object):
"""
try:
return self.get(**kwargs), False
- except (ObjectDoesNotExist, IndexError):
+ except ObjectDoesNotExist:
pass
data = defaults or {}
@@ -289,12 +289,32 @@ class QuerySet(object):
return self._model_class(**data).blocking_save(), True
def get_or_none(self, **kwargs):
+ """
+ Gets an object if it exists in database according to
+ given query parameters otherwise returns None.
+
+ Args:
+ **kwargs: query parameters
+
+ Returns: object or None
+
+ """
try:
return self.get(**kwargs)
except ObjectDoesNotExist:
return None
def delete_if_exists(self, **kwargs):
+ """
+ Deletes an object if it exists in database according to given query
+ parameters and returns True otherwise does nothing and returns False.
+
+ Args:
+ **kwargs: query parameters
+
+ Returns(bool): True or False
+
+ """
try:
self.get(**kwargs).blocking_delete()
return True | ADD, Documentation is added for get_or_none and delete_if_exists methods. | zetaops_pyoko | train |
affbd3ea7d1a0fb7880f31286778ae300f50f719 | diff --git a/pydoop/app/submit.py b/pydoop/app/submit.py
index <HASH>..<HASH> 100644
--- a/pydoop/app/submit.py
+++ b/pydoop/app/submit.py
@@ -203,13 +203,7 @@ class PydoopSubmitter(object):
lines.append('export HOME="%s"' % os.environ['HOME'])
lines.append('exec "%s" -u "$0" "$@"' % executable)
lines.append('":"""')
- lines.append('import importlib')
- lines.append('try:')
- lines.append(' module = importlib.import_module("%s")'
- % self.args.module)
- lines.append('except ImportError as e:')
- lines.append(' import sys')
- lines.append(' raise ImportError("%s in %s" % (e, sys.path))')
+ lines.append('import %s as module' % self.args.module)
lines.append('module.%s()' % self.args.entry_point)
return os.linesep.join(lines) + os.linesep | Changed module invocation in submit driver. | crs4_pydoop | train |
f212dd60b3d47b21ff40ad2f53bb817e656ab91c | diff --git a/src/rules/no-duplicates.js b/src/rules/no-duplicates.js
index <HASH>..<HASH> 100644
--- a/src/rules/no-duplicates.js
+++ b/src/rules/no-duplicates.js
@@ -5,7 +5,7 @@ module.exports = function (context) {
return {
"ImportDeclaration": function (n) {
// resolved path will cover aliased duplicates
- let resolvedPath = resolve(n.source.value, context)
+ let resolvedPath = resolve(n.source.value, context) || n.source.value
if (imported.has(resolvedPath)) {
imported.get(resolvedPath).add(n.source)
diff --git a/tests/src/rules/no-duplicates.js b/tests/src/rules/no-duplicates.js
index <HASH>..<HASH> 100644
--- a/tests/src/rules/no-duplicates.js
+++ b/tests/src/rules/no-duplicates.js
@@ -1,33 +1,50 @@
import * as path from 'path'
import { test } from '../utils'
-import { linter, RuleTester } from 'eslint'
+import { RuleTester } from 'eslint'
const ruleTester = new RuleTester()
, rule = require('../../../lib/rules/no-duplicates')
ruleTester.run('no-duplicates', rule, {
valid: [
- test({ code: "import { x } from './foo'; import { y } from './bar'" })
+ test({ code: "import { x } from './foo'; import { y } from './bar'" }),
+
+ // #86: every unresolved module should not show up as 'null' and duplicate
+ test({ code: 'import foo from "234artaf";' +
+ 'import { shoop } from "234q25ad"' }),
],
invalid: [
- test({ code: "import { x } from './foo'; import { y } from './foo'"
- , errors: 2
- })
- , test({ code: "import { x } from './foo';\
- import { y } from './foo';\
- import { z } from './foo'"
- , errors: 3
- })
+ test({
+ code: "import { x } from './foo'; import { y } from './foo'",
+ errors: 2,
+ }),
+
+ test({
+ code: "import { x } from './foo';\
+ import { y } from './foo';\
+ import { z } from './foo'",
+ errors: 3,
+ }),
- // ensure resolved path results in warnings
- , test({ code: "import { x } from './bar';\
- import { y } from 'bar';"
- , settings: { 'import/resolve': {
- paths: [path.join( process.cwd()
- , 'tests', 'files'
- )] }}
- , errors: 2
- })
- ]
+ // ensure resolved path results in warnings
+ test({
+ code: "import { x } from './bar';\
+ import { y } from 'bar';",
+ settings: { 'import/resolve': {
+ paths: [path.join( process.cwd()
+ , 'tests', 'files'
+ )] }},
+ errors: 2,
+ }),
+
+ // #86: duplicate unresolved modules should be flagged
+ test({
+ code: "import foo from 'non-existent'; import bar from 'non-existent';",
+ errors: [
+ "Module 'non-existent' imported multiple times.",
+ "Module 'non-existent' imported multiple times.",
+ ],
+ }),
+ ],
}) | fix for #<I>.
technically a little loose, but practically speaking, should be effective | benmosher_eslint-plugin-import | train |
af2f92d0887507b92fc4dffd3f8e7b6abfcca614 | diff --git a/admin/health.php b/admin/health.php
index <HASH>..<HASH> 100644
--- a/admin/health.php
+++ b/admin/health.php
@@ -645,13 +645,9 @@ class problem_000015 extends problem_base {
ORDER BY numquestions DESC, qc.name");
$table = '<table><thead><tr><th>Cat id</th><th>Category name</th>' .
"<th>Context id</th><th>Num Questions</th></tr></thead><tbody>\n";
- $maxnumquestions = 0;
foreach ($problemcategories as $cat) {
- $table .= "<tr><td>$cat->id/td><td>" . s($cat->name) . "</td><td>" .
+ $table .= "<tr><td>$cat->id</td><td>" . s($cat->name) . "</td><td>" .
$cat->contextid ."</td><td>$cat->numquestions</td></tr>\n";
- if ($maxnumquestions < $cat->numquestions) {
- $maxnumquestions = $cat->numquestions;
- }
}
$table .= '</tbody></table>';
return '<p>All question categories are linked to a context id, and, ' .
@@ -663,10 +659,10 @@ class problem_000015 extends problem_base {
function solution() {
global $CFG;
return '<p>You can delete the empty categories by executing the following SQL:</p><pre>
-DELETE FROM ' . $CFG->prefix . 'question_categories
+DELETE FROM ' . $CFG->prefix . 'question_categories qc
WHERE
- NOT EXIST (SELECT * FROM ' . $CFG->prefix . 'question q WHERE q.category = qc.id)
-AND NOT EXIST (SELECT * FROM ' . $CFG->prefix . 'context context WHERE qc.contextid = con.id)
+ NOT EXISTS (SELECT * FROM ' . $CFG->prefix . 'question q WHERE q.category = qc.id)
+AND NOT EXISTS (SELECT * FROM ' . $CFG->prefix . 'context con WHERE qc.contextid = con.id)
</pre><p>Any remaining categories that contain questions will require more thought. ' .
'People in the <a href="http://moodle.org/mod/forum/view.php?f=121">Quiz forum</a> may be able to help.</p>';
}
@@ -701,8 +697,8 @@ class problem_000016 extends problem_base {
'<th>Id</th><th>Name</th><th>Context id</th>' .
"</tr></thead><tbody>\n";
foreach ($problemcategories as $cat) {
- $table .= "<tr><td>$cat->childid/td><td>" . s($cat->childname) .
- "</td><td>$cat->childcon</td><td>$cat->parentid/td><td>" . s($cat->parentname) .
+ $table .= "<tr><td>$cat->childid</td><td>" . s($cat->childname) .
+ "</td><td>$cat->childcon</td><td>$cat->parentid</td><td>" . s($cat->parentname) .
"</td><td>$cat->parentcon</td></tr>\n";
}
$table .= '</tbody></table>'; | MDL-<I> - Fix solution SQL syntax for the "question categories must belong to a context that exists" check. | moodle_moodle | train |
bfb7924ccb967dfef05df78e416412dee9b8794a | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -1,6 +1,9 @@
var split = require('browser-split')
var ClassList = require('class-list')
-require('html-element/global-shim')
+var htmlElement = require('html-element');
+
+var document = htmlElement.document;
+var Text = htmlElement.Text;
function context () { | don't use global shims from html-element | hyperhype_hyperscript | train |
8a14daaf34542ed0de22bbbbdbb8ddc444a1d549 | diff --git a/src/mixins/data-iterable.js b/src/mixins/data-iterable.js
index <HASH>..<HASH> 100644
--- a/src/mixins/data-iterable.js
+++ b/src/mixins/data-iterable.js
@@ -169,7 +169,7 @@ export default {
return this.selectAll !== undefined && this.selectAll !== false
},
itemsLength () {
- if (this.search) return this.searchLength
+ if (this.hasSearch) return this.searchLength
return this.totalItems || this.items.length
},
indeterminate () {
@@ -209,6 +209,9 @@ export default {
selected[key] = true
}
return selected
+ },
+ hasSearch () {
+ return this.search != null
}
},
@@ -257,10 +260,8 @@ export default {
if (this.totalItems) return this.items
let items = this.items.slice()
- const hasSearch = typeof this.search !== 'undefined' &&
- this.search !== null
- if (hasSearch) {
+ if (this.hasSearch) {
items = this.customFilter(items, this.search, this.filter, ...additionalFilterArgs)
this.searchLength = items.length
} | fix: data-table pagination did not update when using custom-filter (#<I>)
* fix: data-table pagination did not update when using custom-filter
specifically when using a custom-filter but not using search prop
closes #<I>
* fix: added unit test
* fix: changed hasSearch logic according to feedback
* test: fix failing test
* test: removed test as it was unreliable | vuetifyjs_vuetify | train |
875862f8d6d94fc64bd5e2b17828d58cb00277ac | diff --git a/opal/browser/dom/document.rb b/opal/browser/dom/document.rb
index <HASH>..<HASH> 100644
--- a/opal/browser/dom/document.rb
+++ b/opal/browser/dom/document.rb
@@ -55,10 +55,6 @@ class Document < Element
"#<DOM::Document: #{children.inspect}>"
end
- def location
- Location.new(`#@native.location`) if `#@native.location`
- end
-
def title
`#@native.title`
end
diff --git a/opal/browser/location.rb b/opal/browser/location.rb
index <HASH>..<HASH> 100644
--- a/opal/browser/location.rb
+++ b/opal/browser/location.rb
@@ -76,4 +76,12 @@ class Window
end
end
+class DOM::Document
+ # @!attribute [r] location
+ # @return [Location] the location for the document
+ def location
+ Location.new(`#@native.location`) if `#@native.location`
+ end
+end
+
end | location: move #location in document to the right place | opal_opal-browser | train |
f71c0414c2b42148ca17570f52fe19d050abfd16 | diff --git a/job.go b/job.go
index <HASH>..<HASH> 100644
--- a/job.go
+++ b/job.go
@@ -1,5 +1,7 @@
package gojenkins
+import "encoding/xml"
+
type Build struct {
Id string `json:"id"`
Number int `json:"number"`
@@ -63,6 +65,7 @@ type MavenJobItem struct {
Settings JobSettings `xml:"settings"`
GlobalSettings JobSettings `xml:"globalSettings"`
RunPostStepsIfResult RunPostStepsIfResult `xml:"runPostStepsIfResult"`
+ Postbuilders PostBuilders `xml:"postbuilders"`
}
type Scm struct {
@@ -94,6 +97,20 @@ type ScmSvnLocation struct {
DepthOption string `xml:"depthOption"`
IgnoreExternalsOption string `xml:"ignoreExternalsOption"`
}
+
+type PostBuilders struct {
+ XMLName xml.Name `xml:"postbuilders"`
+ PostBuilder []PostBuilder
+}
+
+type PostBuilder interface {
+}
+
+type ShellBuilder struct {
+ XMLName xml.Name `xml:"hudson.tasks.Shell"`
+ Command string `xml:"command"`
+}
+
type JobSettings struct {
Class string `xml:"class,attr"`
JobSetting []JobSetting | Add postbuilder tag when creating a new job | yosida95_golang-jenkins | train |
c6a056de414e4b900db6f1fa9aea29e5c4728e35 | diff --git a/Collection.php b/Collection.php
index <HASH>..<HASH> 100755
--- a/Collection.php
+++ b/Collection.php
@@ -591,7 +591,7 @@ class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate
{
$items = $this->items;
- array_shuffle($items);
+ shuffle($items);
return new static($items);
} | Fixed typo in the shuffle method | illuminate_support | train |
ec7dd091bb6cf22ef87f2c66420238e1a838c2e0 | diff --git a/Controller/UserController.php b/Controller/UserController.php
index <HASH>..<HASH> 100644
--- a/Controller/UserController.php
+++ b/Controller/UserController.php
@@ -122,11 +122,7 @@ class UserController extends Controller
$preUserRegisterEvent = new PreRegisterEvent( $data->payload );
$this->eventDispatcher->dispatch( MVCEvents::USER_PRE_REGISTER, $preUserRegisterEvent );
-
- if ( $data->payload !== $preUserRegisterEvent->getUserCreateStruct() )
- {
- $data->payload = $preUserRegisterEvent->getUserCreateStruct();
- }
+ $data->payload = $preUserRegisterEvent->getUserCreateStruct();
// @TODO: There is a known issue in eZ Publish kernel where signal slot repository
// is NOT used in sudo calls, preventing the "auto enable" functionality from working
@@ -253,11 +249,7 @@ class UserController extends Controller
$preActivateEvent = new PreActivateEvent( $user );
$this->eventDispatcher->dispatch( MVCEvents::USER_PRE_ACTIVATE, $preActivateEvent );
-
- if ( $user !== $preActivateEvent->getUser() )
- {
- $user = $preActivateEvent->getUser();
- }
+ $user = $preActivateEvent->getUser();
$user = $this->enableUser( $user );
@@ -373,11 +365,7 @@ class UserController extends Controller
$prePasswordResetEvent = new PrePasswordResetEvent( $userUpdateStruct );
$this->eventDispatcher->dispatch( MVCEvents::USER_PRE_PASSWORD_RESET, $prePasswordResetEvent );
-
- if ( $userUpdateStruct !== $prePasswordResetEvent->getUserUpdateStruct() )
- {
- $userUpdateStruct = $prePasswordResetEvent->getUserUpdateStruct();
- }
+ $userUpdateStruct = $prePasswordResetEvent->getUserUpdateStruct();
$user = $this->getRepository()->sudo(
function( Repository $repository ) use ( $user, $userUpdateStruct ) | Removed unnecessary if checks in user controller | netgen_site-bundle | train |
233a6a606c383927d2ef333f78da6a9417341a7e | diff --git a/lib/figleaf/load_settings.rb b/lib/figleaf/load_settings.rb
index <HASH>..<HASH> 100644
--- a/lib/figleaf/load_settings.rb
+++ b/lib/figleaf/load_settings.rb
@@ -14,6 +14,7 @@ module Figleaf
Dir.glob(root.join('config', 'settings', '*.yml')).each do |file|
property_name = File.basename(file, '.yml')
property = YAML.load_file(file)[env]
+ property = define_first_level_methods(property)
self.configure_with_auto_define do |s|
s.send("#{property_name}=", property)
end
@@ -30,6 +31,18 @@ module Figleaf
ENV['ENVIRONMENT']
end
+ def define_first_level_methods(property)
+ if property.class == Hash
+ property = HashWithIndifferentAccess.new(property)
+
+ property.each do |key, value|
+ method_name = !!value == value ? :"#{key}?" : key.to_sym
+ property.define_singleton_method(method_name) { value }
+ end
+ end
+
+ property
+ end
end
end
end
diff --git a/spec/settings_spec.rb b/spec/settings_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/settings_spec.rb
+++ b/spec/settings_spec.rb
@@ -102,6 +102,23 @@ describe Figleaf::Settings do
described_class.some_service["foo"].should == "bar"
end
+ it "should load indifferently the key names" do
+ described_class.some_service["foo"].should == "bar"
+ described_class.some_service[:foo].should == "bar"
+ end
+
+ it "should create foo as a method" do
+ described_class.some_service.foo.should == "bar"
+ end
+
+ it "should create bool_true? and return true" do
+ described_class.some_service.bool_true?.should be_true
+ end
+
+ it "should create bool_false? and return false" do
+ described_class.some_service.bool_false?.should be_false
+ end
+
end
end | Create a method for each property key, with the added bonus of booleans ending in '?' | jcmuller_figleaf | train |
4a111010e7dba9948f04c45008e276321977b8d1 | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -47,6 +47,11 @@ function hijack(options, callback) {
if (skipExternal && link.getAttribute('rel') === 'external') return;
if (skipTargetBlank && link.getAttribute('target') === '_blank') return;
if (skipMailTo && /mailto:/.test(link.getAttribute('href'))) return;
+ // IE doesn't populate all link properties when setting href with a
+ // relative URL. However, href will return an absolute URL which then can
+ // be used on itself to populate these additional fields.
+ // https://stackoverflow.com/a/13405933/2284669
+ if (!link.host) link.href = link.href;
if (
skipOtherOrigin &&
/:\/\//.test(link.href) && | Fix missing link properties in IE<I> (#5) | mapbox_link-hijacker | train |
bd74759fda8775e0f8e8d12bd9195ddf0bdf0a04 | diff --git a/data/linux/index.js b/data/linux/index.js
index <HASH>..<HASH> 100644
--- a/data/linux/index.js
+++ b/data/linux/index.js
@@ -3,7 +3,7 @@ var path = require('path');
module.exports = require('./build/Release/appjs.node');
module.exports.initConfig = {
- localsPakPath: path.resolve(__dirname, 'data/pak/locales'),
+ localesPakPath: path.resolve(__dirname, 'data/pak/locales'),
chromePakPath: path.resolve(__dirname, 'data/pak/chrome.pak'),
jsFlags: ' --harmony_proxies --harmony_collections --harmony_scoping'
};
diff --git a/data/mac/index.js b/data/mac/index.js
index <HASH>..<HASH> 100644
--- a/data/mac/index.js
+++ b/data/mac/index.js
@@ -3,7 +3,7 @@ var path = require('path');
module.exports = require('./build/Release/appjs.node');
module.exports.initConfig = {
- localsPakPath: path.resolve(__dirname, 'data/pak/locales'),
+ localesPakPath: path.resolve(__dirname, 'data/pak/locales'),
chromePakPath: path.resolve(__dirname, 'data/pak/chrome.pak'),
jsFlags: ' --harmony_proxies --harmony_collections --harmony_scoping'
};
diff --git a/data/win/index.js b/data/win/index.js
index <HASH>..<HASH> 100644
--- a/data/win/index.js
+++ b/data/win/index.js
@@ -6,7 +6,7 @@ process.env.PATH += ';' + binaryPath;
module.exports = require(binaryPath);
module.exports.initConfig = {
- localsPakPath: path.resolve(__dirname, 'data/pak/locales'),
+ localesPakPath: path.resolve(__dirname, 'data/pak/locales'),
chromePakPath: path.resolve(__dirname, 'data/pak/chrome.pak'),
jsFlags: ' --harmony_proxies --harmony_collections --harmony_scoping'
};
diff --git a/src/includes/cef.cpp b/src/includes/cef.cpp
index <HASH>..<HASH> 100644
--- a/src/includes/cef.cpp
+++ b/src/includes/cef.cpp
@@ -16,7 +16,7 @@ void Cef::Init(Settings* initSettings) {
CefSettings settings;
CefString(&settings.pack_file_path) = initSettings->getString("chromePakPath", "");
- CefString(&settings.locales_dir_path) = initSettings->getString("localsPakPath", "");
+ CefString(&settings.locales_dir_path) = initSettings->getString("localesPakPath", "");
CefString(&settings.javascript_flags) = initSettings->getString("jsFlags", "");
settings.log_severity = (cef_log_severity_t)initSettings->getInteger("logLevel", LOGSEVERITY_DISABLE);
settings.multi_threaded_message_loop = false; | Fix typo locals -> locales | appjs_appjs | train |
f24aadfdee086ecbc385f9ecd2b5547fdbdb8fe9 | diff --git a/examples/autoreset_demo.py b/examples/autoreset_demo.py
index <HASH>..<HASH> 100644
--- a/examples/autoreset_demo.py
+++ b/examples/autoreset_demo.py
@@ -1,11 +1,11 @@
-#!/usr/bin/python
+#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Demonstration of colorise's autoreset future when exceptions are thrown."""
from __future__ import print_function
-__date__ = "2014-05-17" # YYYY-MM-DD
+__date__ = "2014-05-21" # YYYY-MM-DD
import colorise
diff --git a/examples/highlight_differences.py b/examples/highlight_differences.py
index <HASH>..<HASH> 100644
--- a/examples/highlight_differences.py
+++ b/examples/highlight_differences.py
@@ -1,11 +1,11 @@
-#!/usr/bin/python
+#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""A simple function that illustrates how to use colorise.highlight."""
from __future__ import print_function
-__date__ = "2014-05-17" # YYYY-MM-DD
+__date__ = "2014-05-21" # YYYY-MM-DD
import colorise
diff --git a/examples/lorem.py b/examples/lorem.py
index <HASH>..<HASH> 100644
--- a/examples/lorem.py
+++ b/examples/lorem.py
@@ -1,9 +1,9 @@
-#!/usr/bin/python
+#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Demonstrates how colorise automatically reset colors when quit."""
-__date__ = "2014-05-17" # YYYY-MM-DD
+__date__ = "2014-05-21" # YYYY-MM-DD
import colorise
diff --git a/examples/nested_format.py b/examples/nested_format.py
index <HASH>..<HASH> 100644
--- a/examples/nested_format.py
+++ b/examples/nested_format.py
@@ -1,9 +1,9 @@
-#!/usr/bin/python
+#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Demonstrates how colorise's color format syntax can be endlessly nested."""
-__date__ = "2014-05-17" # YYYY-MM-DD
+__date__ = "2014-05-21" # YYYY-MM-DD
import colorise
import random
diff --git a/examples/simple_demo.py b/examples/simple_demo.py
index <HASH>..<HASH> 100644
--- a/examples/simple_demo.py
+++ b/examples/simple_demo.py
@@ -1,11 +1,11 @@
-#!/usr/bin/python
+#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Demonstration of the various ways of coloring text."""
from __future__ import print_function
-__date__ = "2014-05-17" # YYYY-MM-DD
+__date__ = "2014-05-21" # YYYY-MM-DD
import random
import colorise
diff --git a/tests/test_functions.py b/tests/test_functions.py
index <HASH>..<HASH> 100644
--- a/tests/test_functions.py
+++ b/tests/test_functions.py
@@ -1,8 +1,9 @@
+#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""py.test file for testing the colorise's testable public functions."""
-__date__ = "2014-05-17" # YYYY-MM-DD
+__date__ = "2014-05-21" # YYYY-MM-DD
import sys
sys.path.append('.')
diff --git a/tests/test_parser.py b/tests/test_parser.py
index <HASH>..<HASH> 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -1,8 +1,9 @@
+#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""py.test file for testing the ColorFormatParser class."""
-__date__ = "2014-05-17" # YYYY-MM-DD
+__date__ = "2014-05-21" # YYYY-MM-DD
import pytest
import sys | Changed she-bang of example files to env-style and added it to test files | MisanthropicBit_colorise | train |
eaf0e56115a5988ddd2b0a30b120c5bf61828220 | diff --git a/src/Console/Command/ProfileInfoCommand.php b/src/Console/Command/ProfileInfoCommand.php
index <HASH>..<HASH> 100644
--- a/src/Console/Command/ProfileInfoCommand.php
+++ b/src/Console/Command/ProfileInfoCommand.php
@@ -59,7 +59,7 @@ class ProfileInfoCommand extends Command
$render->title($profile->title);
- $render->block($profile->description);
+ $render->block($profile->description ?? '');
$render->section('Usage');
$render->block('drutiny profile:run ' . $profile->name . ' <target>'); | Fix fatal when profile description is null. | drutiny_drutiny | train |
29eeffb0b24ca0a05503f63df2cb88f3c9c4f0b7 | diff --git a/LiSE/LiSE/node.py b/LiSE/LiSE/node.py
index <HASH>..<HASH> 100644
--- a/LiSE/LiSE/node.py
+++ b/LiSE/LiSE/node.py
@@ -145,6 +145,76 @@ class NodeContent(Mapping):
return NodeContentValues(self)
+class DestsValues(ValuesView):
+ def __contains__(self, item):
+ return item.origin == self._mapping.node
+
+
+class Dests(Mapping):
+ __slots__ = ('node',)
+
+ def __init__(self, node):
+ self.node = node
+
+ def __iter__(self):
+ yield from self.node.engine._edges_cache.iter_successors(
+ self.node.character.name, self.node.name, *self.node.engine.btt()
+ )
+
+ def __len__(self):
+ return self.node.engine._edges_cache.count_successors(
+ self.node.character.name, self.node.name, *self.node.engine.btt()
+ )
+
+ def __contains__(self, item):
+ return self.node.engine._edges_cache.has_successor(
+ self.node.character.name, self.node.name, item, *self.node.engine.btt()
+ )
+
+ def __getitem__(self, item):
+ if item not in self:
+ raise KeyError
+ return self.node.character.portal[self.node.name][item]
+
+ def values(self):
+ return DestsValues(self)
+
+
+class OrigsValues(ValuesView):
+ def __contains__(self, item):
+ return item.destination == self._mapping.node
+
+
+class Origs(Mapping):
+ __slots__ = ('node',)
+
+ def __init__(self, node):
+ self.node = node
+
+ def __iter__(self):
+ return self.node.engine._edges_cache.iter_predecessors(
+ self.node.character.name, self.node.name, *self.node.engine.btt()
+ )
+
+ def __contains__(self, item):
+ return self.node.engine._edges_cache.has_predecessor(
+ self.node.character.name, self.node.name, item, *self.node.engine.btt()
+ )
+
+ def __len__(self):
+ return self.node.engine._edges_cache.count_predecessors(
+ self.node.character.name, self.node.name, *self.node.engine.btt()
+ )
+
+ def __getitem__(self, item):
+ if item not in self:
+ raise KeyError
+ return self.node.character.portal[item][self.node.name]
+
+ def values(self):
+ return OrigsValues(self)
+
+
class Node(allegedb.graph.Node, rule.RuleFollower):
"""The fundamental graph component, which edges (in LiSE, "portals")
go between.
@@ -202,7 +272,13 @@ class Node(allegedb.graph.Node, rule.RuleFollower):
@property
def portal(self):
"""Return a mapping of portals connecting this node to its neighbors."""
- return self.character.portal[self.name]
+ return Dests(self)
+ successor = adj = edge = portal
+
+ @property
+ def preportal(self):
+ return Origs(self)
+ predecessor = pred = preportal
def __init__(self, character, name):
"""Store character and name, and initialize caches"""
@@ -233,47 +309,23 @@ class Node(allegedb.graph.Node, rule.RuleFollower):
super().__delitem__(k)
self.send(self, key=k, val=None)
- def _portal_dests(self):
- """Iterate over names of nodes you can get to from here"""
- yield from self.db._edges_cache.iter_entities(
- self.character.name, self.name, *self.engine.btt()
- )
-
- def _portal_origs(self):
- """Iterate over names of nodes you can get here from"""
- cache = self.engine._edges_cache.predecessors[
- self.character.name][self.name]
- for nodeB in cache:
- for (b, trn, tck) in self.engine._iter_parent_btt():
- if b in cache[nodeB][0]:
- if b != self.engine.branch:
- self.engine._edges_cache.store(
- self.character.name, self.name, nodeB, 0,
- *self.engine.btt()
- )
- if cache[nodeB][0][b][trn][tck]:
- yield nodeB
- break
-
def portals(self):
"""Iterate over :class:`Portal` objects that lead away from me"""
- for destn in self._portal_dests():
- yield self.character.portal[self.name][destn]
+ yield from self.portal.values()
def successors(self):
"""Iterate over nodes with edges leading from here to there."""
- for destn in self._portal_dests():
- yield self.character.node[destn]
+ for port in self.portal.values():
+ yield port.destination
def preportals(self):
"""Iterate over :class:`Portal` objects that lead to me"""
- for orign in self._portal_origs():
- yield self.character.preportal[self.name][orign]
+ yield from self.preportal.values()
def predecessors(self):
"""Iterate over nodes with edges leading here from there."""
- for orign in self._portal_origs():
- yield self.character.node[orign]
+ for port in self.preportal.values():
+ yield port.origin
def _sane_dest_name(self, dest):
if isinstance(dest, Node): | Make it easier to check if a node connects to another | LogicalDash_LiSE | train |
2c1065bd434034076f9f91f576ac14c0bafb06bf | diff --git a/lib/Widget/Validator.php b/lib/Widget/Validator.php
index <HASH>..<HASH> 100644
--- a/lib/Widget/Validator.php
+++ b/lib/Widget/Validator.php
@@ -604,7 +604,7 @@ class Validator extends AbstractWidget
}
/**
- * Returns the joined message
+ * Returns error message string
*
* @return srring
*/
diff --git a/lib/Widget/Validator/AbstractValidator.php b/lib/Widget/Validator/AbstractValidator.php
index <HASH>..<HASH> 100644
--- a/lib/Widget/Validator/AbstractValidator.php
+++ b/lib/Widget/Validator/AbstractValidator.php
@@ -204,6 +204,16 @@ abstract class AbstractValidator extends AbstractWidget implements ValidatorInte
}
/**
+ * Returns error message string
+ *
+ * @return srring
+ */
+ public function getJoinedMessage($separator = "\n")
+ {
+ return implode($separator, $this->getMessages());
+ }
+
+ /**
* Loads the validator translation messages
*
* @todo better way? | added getJoinedMessage for validator, close #<I> | twinh_wei | train |
b2d18b20e9a38d9310626480d9313acb0cf775ee | diff --git a/example_project/settings.py b/example_project/settings.py
index <HASH>..<HASH> 100644
--- a/example_project/settings.py
+++ b/example_project/settings.py
@@ -119,6 +119,7 @@ ABSOLUTE_URL_OVERRIDES = {
ACCOUNT_ACTIVATION_DAYS = 7
ACTSTREAM_SETTINGS = {
+ 'MODELS': ('auth.user', 'auth.group', 'sites.site', 'comments.comment'),
'MANAGER': 'testapp.streams.MyActionManager',
'FETCH_RELATIONS': True,
'USE_PREFETCH': True, | Fixed mixing MODELS from ACTSTREAM_SETTING in example project | justquick_django-activity-stream | train |
19c6d0024e526d5b35fff70a50ee6cc7f3088438 | diff --git a/ccmlib/cluster.py b/ccmlib/cluster.py
index <HASH>..<HASH> 100644
--- a/ccmlib/cluster.py
+++ b/ccmlib/cluster.py
@@ -173,8 +173,8 @@ class Cluster():
def balanced_tokens(self, node_count):
if self.version() >= '1.2' and not self.partitioner:
ptokens = [(i*(2**64//node_count)) for i in xrange(0, node_count)]
- return [t - 2**63 for t in ptokens]
- return [ (i*(2**127//node_count)) for i in range(0, node_count) ]
+ return [int(t - 2**63) for t in ptokens]
+ return [ int(i*(2**127//node_count)) for i in range(0, node_count) ]
def remove(self, node=None):
if node is not None: | Ensure generated tokens are integers | riptano_ccm | train |
ef03d9fbb9f0e3dd30786617479aa4701641c11b | diff --git a/packages/pancake-sass/src/sass.js b/packages/pancake-sass/src/sass.js
index <HASH>..<HASH> 100644
--- a/packages/pancake-sass/src/sass.js
+++ b/packages/pancake-sass/src/sass.js
@@ -44,7 +44,10 @@ export const GetPath = ( module, modules, baseLocation, npmOrg ) => {
const npmOrgs = npmOrg.split( ' ' );
let location;
npmOrgs.forEach( org => {
- if( baseLocation.includes( org ) ){
+ if( baseLocation.includes( org ) && process.platform === 'win32' ){
+ location = baseLocation.replace( `${ org }\\`, '' );
+ }
+ else if( baseLocation.includes( org ) ){
location = baseLocation.replace( `${ org }/`, '' );
}
}); | Added check for win<I> platform and org replace | govau_pancake | train |
22fa3672bf57ea66194d557bcc9b81d87b1f7fbe | diff --git a/lib/vagrant-hiera/middleware/setup.rb b/lib/vagrant-hiera/middleware/setup.rb
index <HASH>..<HASH> 100644
--- a/lib/vagrant-hiera/middleware/setup.rb
+++ b/lib/vagrant-hiera/middleware/setup.rb
@@ -6,7 +6,7 @@ module VagrantHiera
@app = app
@env = env
@puppet_repo = 'deb http://apt.puppetlabs.com/ lucid devel main'
- @puppet_version = '3.0.0-0.1rc3puppetlabs1'
+ @puppet_version = '3.0.0-0.1rc4puppetlabs1'
@hiera_puppet_version = '1.0.0-0.1rc1-1-g3e68ff0'
@hiera_version = '1.0.0-0.1rc3'
@apt_opts = "-y --force-yes -o Dpkg::Options::=\"--force-confdef\" -o Dpkg::Options::=\"--force-confold\""
diff --git a/lib/vagrant-hiera/version.rb b/lib/vagrant-hiera/version.rb
index <HASH>..<HASH> 100644
--- a/lib/vagrant-hiera/version.rb
+++ b/lib/vagrant-hiera/version.rb
@@ -1,5 +1,5 @@
module Vagrant
module Hiera
- VERSION = "0.3.3"
+ VERSION = "0.3.4"
end
end | support for puppet 3 rc4 | gposton_vagrant-hiera | train |
95e6e384aca902897cef4903efcf7b8d7e3cd73e | diff --git a/src/Symfony/Bridge/Twig/Tests/Mime/TemplatedEmailTest.php b/src/Symfony/Bridge/Twig/Tests/Mime/TemplatedEmailTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Bridge/Twig/Tests/Mime/TemplatedEmailTest.php
+++ b/src/Symfony/Bridge/Twig/Tests/Mime/TemplatedEmailTest.php
@@ -110,11 +110,11 @@ EOF;
$propertyNormalizer,
], [new JsonEncoder()]);
- $serialized = $serializer->serialize($e, 'json');
+ $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
$this->assertSame($expectedJson, json_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
$n = $serializer->deserialize($serialized, TemplatedEmail::class, 'json');
- $serialized = $serializer->serialize($e, 'json');
+ $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
$this->assertSame($expectedJson, json_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
$n->from('[email protected]');
diff --git a/src/Symfony/Component/Mime/Tests/EmailTest.php b/src/Symfony/Component/Mime/Tests/EmailTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Mime/Tests/EmailTest.php
+++ b/src/Symfony/Component/Mime/Tests/EmailTest.php
@@ -448,11 +448,11 @@ EOF;
$propertyNormalizer,
], [new JsonEncoder()]);
- $serialized = $serializer->serialize($e, 'json');
+ $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
$this->assertSame($expectedJson, json_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
$n = $serializer->deserialize($serialized, Email::class, 'json');
- $serialized = $serializer->serialize($e, 'json');
+ $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
$this->assertSame($expectedJson, json_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
$n->from('[email protected]'); | [Mime][TwigBridge] Fix tests | symfony_symfony | train |
667c947956281c0d23cdfbcb7cf8178e9ad5adaf | diff --git a/pandas/core/generic.py b/pandas/core/generic.py
index <HASH>..<HASH> 100644
--- a/pandas/core/generic.py
+++ b/pandas/core/generic.py
@@ -5772,7 +5772,7 @@ class NDFrame(PandasObject, SelectionMixin):
for k, v, in self._data.to_dict(copy=copy).items()
}
- def astype(self, dtype, copy=True, errors="raise", **kwargs):
+ def astype(self, dtype, copy=True, errors="raise"):
"""
Cast a pandas object to a specified dtype ``dtype``.
@@ -5795,8 +5795,6 @@ class NDFrame(PandasObject, SelectionMixin):
.. versionadded:: 0.20.0
- **kwargs : keyword arguments to pass on to the constructor
-
Returns
-------
casted : same type as caller
@@ -5882,7 +5880,7 @@ class NDFrame(PandasObject, SelectionMixin):
"the key in Series dtype mappings."
)
new_type = dtype[self.name]
- return self.astype(new_type, copy, errors, **kwargs)
+ return self.astype(new_type, copy, errors)
for col_name in dtype.keys():
if col_name not in self:
@@ -5894,9 +5892,7 @@ class NDFrame(PandasObject, SelectionMixin):
for col_name, col in self.items():
if col_name in dtype:
results.append(
- col.astype(
- dtype=dtype[col_name], copy=copy, errors=errors, **kwargs
- )
+ col.astype(dtype=dtype[col_name], copy=copy, errors=errors)
)
else:
results.append(results.append(col.copy() if copy else col))
@@ -5911,9 +5907,7 @@ class NDFrame(PandasObject, SelectionMixin):
else:
# else, only a single dtype is given
- new_data = self._data.astype(
- dtype=dtype, copy=copy, errors=errors, **kwargs
- )
+ new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors)
return self._constructor(new_data).__finalize__(self)
# GH 19920: retain column metadata after concat
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py
index <HASH>..<HASH> 100644
--- a/pandas/core/internals/blocks.py
+++ b/pandas/core/internals/blocks.py
@@ -574,18 +574,6 @@ class Block(PandasObject):
# may need to convert to categorical
if self.is_categorical_astype(dtype):
- # deprecated 17636
- for deprecated_arg in ("categories", "ordered"):
- if deprecated_arg in kwargs:
- raise ValueError(
- "Got an unexpected argument: {}".format(deprecated_arg)
- )
-
- categories = kwargs.get("categories", None)
- ordered = kwargs.get("ordered", None)
- if com.any_not_none(categories, ordered):
- dtype = CategoricalDtype(categories, ordered)
-
if is_categorical_dtype(self.values):
# GH 10696/18593: update an existing categorical efficiently
return self.make_block(self.values.astype(dtype, copy=copy))
@@ -621,7 +609,7 @@ class Block(PandasObject):
# _astype_nansafe works fine with 1-d only
vals1d = values.ravel()
try:
- values = astype_nansafe(vals1d, dtype, copy=True, **kwargs)
+ values = astype_nansafe(vals1d, dtype, copy=True)
except (ValueError, TypeError):
# e.g. astype_nansafe can fail on object-dtype of strings
# trying to convert to float
diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/series/test_dtypes.py
+++ b/pandas/tests/series/test_dtypes.py
@@ -228,11 +228,10 @@ class TestSeriesDtypes:
with pytest.raises(KeyError, match=msg):
s.astype(dt5)
- def test_astype_categories_deprecation_raises(self):
-
- # deprecated 17636
+ def test_astype_categories_raises(self):
+ # deprecated 17636, removed in GH-27141
s = Series(["a", "b", "a"])
- with pytest.raises(ValueError, match="Got an unexpected"):
+ with pytest.raises(TypeError, match="got an unexpected"):
s.astype("category", categories=["a", "b"], ordered=True)
@pytest.mark.parametrize( | CLN: remove unused categories/ordered handling in astype (#<I>) | pandas-dev_pandas | train |
a5a81a3fd3c4a6df1c77ec5380b7f04d854ff529 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -14,9 +14,9 @@ setup(
long_description=open(join(here, 'README.md')).read(),
url='https://github.com/LedgerHQ/btchip-python',
packages=find_packages(),
- install_requires=['hidapi>=0.7.99'],
+ install_requires=['hidapi>=0.7.99', 'ecdsa>=0.9'],
extras_require = {
- 'smartcard': [ 'python-pyscard>=1.6.12-4build1', 'ecdsa>=0.9' ]
+ 'smartcard': [ 'python-pyscard>=1.6.12-4build1' ]
},
include_package_data=True,
zip_safe=False, | Move ecdsa from extras_require to install_requires | LedgerHQ_btchip-python | train |
0fccd0a852cf02c01042d721da1390da7f6a42cf | diff --git a/src/Ractive/prototype/shared/fireEvent.js b/src/Ractive/prototype/shared/fireEvent.js
index <HASH>..<HASH> 100644
--- a/src/Ractive/prototype/shared/fireEvent.js
+++ b/src/Ractive/prototype/shared/fireEvent.js
@@ -3,7 +3,18 @@ import getPotentialWildcardMatches from 'utils/getPotentialWildcardMatches';
export default function fireEvent ( ractive, eventName, options = {} ) {
if ( !eventName ) { return; }
- if ( options.event ) {
+ if ( !options.event ) {
+
+ options.event = {
+ name: eventName,
+ context: ractive.data,
+ keypath: '',
+ // until event not included as argument default
+ _noArg: true
+ };
+
+ }
+ else {
options.event.name = eventName;
}
@@ -50,7 +61,7 @@ function notifySubscribers ( ractive, subscribers, event, args ) {
var originalEvent = null, stopEvent = false;
- if ( event ) {
+ if ( event && !event._noArg ) {
args = [ event ].concat( args );
}
@@ -60,7 +71,7 @@ function notifySubscribers ( ractive, subscribers, event, args ) {
}
}
- if ( event && stopEvent && ( originalEvent = event.original ) ) {
+ if ( event && !event._noArg && stopEvent && ( originalEvent = event.original ) ) {
originalEvent.preventDefault && originalEvent.preventDefault();
originalEvent.stopPropagation && originalEvent.stopPropagation();
}
diff --git a/test/modules/events.js b/test/modules/events.js
index <HASH>..<HASH> 100644
--- a/test/modules/events.js
+++ b/test/modules/events.js
@@ -1150,12 +1150,34 @@ define([ 'ractive' ], function ( Ractive ) {
});
ractive.on( 'foo', function ( event ) {
- t.equal( this.event, event )
+ t.equal( this.event, event );
})
simulant.fire( ractive.nodes.test, 'click' );
});
+
+ test( 'exists on ractive.fire()', t => {
+ var ractive, data = { foo: 'bar' };
+
+ expect( 4 );
+
+ ractive = new Ractive({
+ el: fixture,
+ template: '<span id="test" on-click="foo"/>',
+ data: data
+ });
+
+ ractive.on( 'foo', function () {
+ var e;
+ t.ok( e = this.event );
+ t.equal( e.name, 'foo' );
+ t.equal( e.keypath, '' );
+ t.equal( e.context, data );
+ })
+
+ ractive.fire( 'foo' );
+ });
};
}); | add this.event when no event arg | ractivejs_ractive | train |
c35f4f9f1ae34b080a5ef0f0310ca892b83abe27 | diff --git a/wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/attribute/core/AbstractAttribute.java b/wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/attribute/core/AbstractAttribute.java
index <HASH>..<HASH> 100644
--- a/wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/attribute/core/AbstractAttribute.java
+++ b/wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/attribute/core/AbstractAttribute.java
@@ -79,13 +79,12 @@ public abstract class AbstractAttribute extends AbstractTagBase {
private volatile byte[] compressedBytes;
- private static transient final AtomicLong OBJECT_ID_GENERATOR = new AtomicLong(0);
/**
* NB: do not generate equals and hashcode base on this as the deserialized
* object can lead to bug.
*/
- private final long objectId;
+ private final String objectId;
// for security purpose, the class name should not be modified
private static final class Security implements Serializable {
@@ -156,7 +155,7 @@ public abstract class AbstractAttribute extends AbstractTagBase {
public AbstractAttribute() {
nullableAttrValueMapValue = false;
- objectId = OBJECT_ID_GENERATOR.incrementAndGet();
+ objectId = AttributeIdGenerator.nextId();
}
/**
@@ -167,7 +166,7 @@ public abstract class AbstractAttribute extends AbstractTagBase {
*/
protected AbstractAttribute(final boolean nullableAttrValueMapValue) {
this.nullableAttrValueMapValue = nullableAttrValueMapValue;
- objectId = OBJECT_ID_GENERATOR.incrementAndGet();
+ objectId = AttributeIdGenerator.nextId();
}
/**
@@ -1900,7 +1899,7 @@ public abstract class AbstractAttribute extends AbstractTagBase {
* @return the objectId
* @since 3.0.15
*/
- final long objectId() {
+ final String objectId() {
return objectId;
}
diff --git a/wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/attribute/core/AttributeUtil.java b/wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/attribute/core/AttributeUtil.java
index <HASH>..<HASH> 100644
--- a/wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/attribute/core/AttributeUtil.java
+++ b/wffweb/src/main/java/com/webfirmframework/wffweb/tag/html/attribute/core/AttributeUtil.java
@@ -353,7 +353,7 @@ public final class AttributeUtil {
// lock should be called on the order of objectId otherwise there will be
// deadlock
- attributesList.sort(Comparator.comparingLong(AbstractAttribute::objectId));
+ attributesList.sort(Comparator.comparing(AbstractAttribute::objectId));
final List<Lock> attrLocks = new ArrayList<Lock>(attributesList.size());
@@ -387,7 +387,7 @@ public final class AttributeUtil {
// lock should be called on the order of objectId otherwise there will be
// deadlock
- attributesList.sort(Comparator.comparingLong(AbstractAttribute::objectId));
+ attributesList.sort(Comparator.comparing(AbstractAttribute::objectId));
final List<Lock> attrLocks = new ArrayList<Lock>(attributesList.size()); | Multi-threading improvements
-- Efficient way to generate unique objectId for attribute in
multi-threading env | webfirmframework_wff | train |
290621e9e2912d36cc3a7a5a5a2f9be036fa0696 | diff --git a/src/Defer/Defer.php b/src/Defer/Defer.php
index <HASH>..<HASH> 100644
--- a/src/Defer/Defer.php
+++ b/src/Defer/Defer.php
@@ -8,7 +8,6 @@ use Nuwave\Lighthouse\GraphQL;
use Nuwave\Lighthouse\Schema\AST\ASTHelper;
use Nuwave\Lighthouse\Events\ManipulatingAST;
use Symfony\Component\HttpFoundation\Response;
-use Nuwave\Lighthouse\Execution\GraphQLRequest;
use Nuwave\Lighthouse\Schema\AST\PartialParser;
use Nuwave\Lighthouse\Support\Contracts\GraphQLResponse;
use Nuwave\Lighthouse\Support\Contracts\CanStreamResponse;
@@ -26,11 +25,6 @@ class Defer implements GraphQLResponse
protected $graphQL;
/**
- * @var \Nuwave\Lighthouse\Execution\GraphQLRequest
- */
- protected $request;
-
- /**
* @var mixed[]
*/
protected $result = [];
@@ -68,14 +62,12 @@ class Defer implements GraphQLResponse
/**
* @param \Nuwave\Lighthouse\Support\Contracts\CanStreamResponse $stream
* @param \Nuwave\Lighthouse\GraphQL $graphQL
- * @param \Nuwave\Lighthouse\Execution\GraphQLRequest $request
* @return void
*/
- public function __construct(CanStreamResponse $stream, GraphQL $graphQL, GraphQLRequest $request)
+ public function __construct(CanStreamResponse $stream, GraphQL $graphQL)
{
$this->stream = $stream;
$this->graphQL = $graphQL;
- $this->request = $request;
$this->maxNestedFields = config('lighthouse.defer.max_nested_fields', 0);
}
@@ -290,8 +282,8 @@ class Defer implements GraphQLResponse
*/
protected function executeDeferred(): void
{
- $this->result = $this->graphQL->executeRequest(
- $this->request
+ $this->result = app()->call(
+ [$this->graphQL, 'executeRequest']
);
$this->stream->stream(
diff --git a/tests/Integration/Defer/DeferTest.php b/tests/Integration/Defer/DeferTest.php
index <HASH>..<HASH> 100644
--- a/tests/Integration/Defer/DeferTest.php
+++ b/tests/Integration/Defer/DeferTest.php
@@ -2,11 +2,11 @@
namespace Tests\Integration\Defer;
-use Nuwave\Lighthouse\Defer\DeferServiceProvider;
use Tests\TestCase;
use GraphQL\Error\Error;
use Illuminate\Support\Arr;
use Nuwave\Lighthouse\Defer\Defer;
+use Nuwave\Lighthouse\Defer\DeferServiceProvider;
class DeferTest extends TestCase
{ | Use the container for calling executeRequest from Defer | nuwave_lighthouse | train |
d9f956507489356891e79bd888e17c8f78c052b8 | diff --git a/tests/src/Map/NamedParameterMapTest.php b/tests/src/Map/NamedParameterMapTest.php
index <HASH>..<HASH> 100644
--- a/tests/src/Map/NamedParameterMapTest.php
+++ b/tests/src/Map/NamedParameterMapTest.php
@@ -100,4 +100,14 @@ class NamedParameterMapTest extends TestCase
$namedParameterMap = new NamedParameterMap(['foo' => 'int']);
$namedParameterMap['foo'] = $this->faker->text();
}
+
+ /**
+ * @expectedException \InvalidArgumentException
+ * @expectedExceptionMessage Value for 'foo' must be of type int
+ */
+ public function testNamedParameterWithNoStringValue()
+ {
+ $namedParameterMap = new NamedParameterMap(['foo' => 'int']);
+ $namedParameterMap['foo'] = new \DateTime();
+ }
} | Include test to produce error (object could not be converted to string) when inserting an invalid type on NamedParameterMap | ramsey_collection | train |
783858c8e150eb0f98d7e5d893e492ee08998662 | diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/core_ext/string/output_safety.rb
+++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb
@@ -171,7 +171,7 @@ module ActiveSupport #:nodoc:
original_concat(value)
end
- def initialize(*)
+ def initialize(str = '')
@html_safe = true
super
end | drop array allocations on `html_safe`
For better or worse, anonymous `*` args will allocate arrays. Ideally,
the interpreter would optimize away this allocation. However, given the
number of times we call `html_safe` it seems worth the shedding idealism
and going for performance. This line was the top allocation spot for a
scaffold (and presumably worse on real applications). | rails_rails | train |
2fe083fd6158391bdb021b0bac9b3ea10fc0c513 | diff --git a/lib/virtualfs/dalli_cache.rb b/lib/virtualfs/dalli_cache.rb
index <HASH>..<HASH> 100644
--- a/lib/virtualfs/dalli_cache.rb
+++ b/lib/virtualfs/dalli_cache.rb
@@ -14,8 +14,12 @@ module VirtualFS
end
def cache(key, &proc)
- value = yield
- return @client.get(key) unless @client.add(key, value)
+ value = @client.get(key)
+
+ unless value
+ value = yield
+ @client.set(key, value)
+ end
value
end | Fixed stupid Dalli-based cache implementation. | evoL_virtualfs | train |
191128a8d4dba97408a7c8781abe8ce5575d7875 | diff --git a/src/Time/TimeRangeOfDay.php b/src/Time/TimeRangeOfDay.php
index <HASH>..<HASH> 100644
--- a/src/Time/TimeRangeOfDay.php
+++ b/src/Time/TimeRangeOfDay.php
@@ -106,6 +106,6 @@ class TimeRangeOfDay
*/
public static function allDay(): self
{
- return new self(new TimeOfDay(0), new TimeOfDay(23, 59, 0));
+ return new self(new TimeOfDay(0), new TimeOfDay(23, 59, 59));
}
} | TimeRangeOfDay all day factory | tanigami_value-objects-php | train |
26df37d162f29c338f9fa1f9151bf0e6d73f62c5 | diff --git a/lib/ellen/robot.rb b/lib/ellen/robot.rb
index <HASH>..<HASH> 100644
--- a/lib/ellen/robot.rb
+++ b/lib/ellen/robot.rb
@@ -17,6 +17,7 @@ module Ellen
bundle
setup
remember
+ handle
adapt
end
@@ -67,5 +68,9 @@ module Ellen
def remember
brain
end
+
+ def handle
+ handlers
+ end
end
end | Initialize handlers at booting robot | r7kamura_ruboty | train |
d9d2623e9bb5d9a246678039be8689a0565ed2d2 | diff --git a/source/core/oxsystemeventhandler.php b/source/core/oxsystemeventhandler.php
index <HASH>..<HASH> 100644
--- a/source/core/oxsystemeventhandler.php
+++ b/source/core/oxsystemeventhandler.php
@@ -47,7 +47,7 @@ class OxSystemEventHandler
*
* @param string $sActiveShop Active shop
*/
- public function onAdminLogin($sActiveShop)
+ public function onAdminLogin( $sActiveShop )
{
//perform online module version check | ESDEV-<I> Module version notification implementation Exception handler added. (cherry picked from commit 6f<I>aa7) | OXID-eSales_oxideshop_ce | train |
df72d99a4f692b39d5d559fc2c4ad584437cd2d0 | diff --git a/Python/lipd/pkg_resources/excel/excel_main.py b/Python/lipd/pkg_resources/excel/excel_main.py
index <HASH>..<HASH> 100644
--- a/Python/lipd/pkg_resources/excel/excel_main.py
+++ b/Python/lipd/pkg_resources/excel/excel_main.py
@@ -1019,7 +1019,7 @@ def _compile_column_metadata(row, keys, number):
_calibration[_key] = row[idx].value
# Special case: PhysicalSample data
- if re.match(re_physical, _key_low):
+ elif re.match(re_physical, _key_low):
m = re.match(re_physical, _key_low)
if m:
_key = m.group(1)
@@ -1044,7 +1044,7 @@ def _compile_column_metadata(row, keys, number):
if _calibration:
_column["calibration"] = _calibration
if _physical:
- _column["physicalSample"] = _calibration
+ _column["physicalSample"] = _physical
if _interpretation:
_interpretation_data = _compile_interpretation(_interpretation)
_column["interpretation"] = _interpretation_data
diff --git a/Python/setup.py b/Python/setup.py
index <HASH>..<HASH> 100644
--- a/Python/setup.py
+++ b/Python/setup.py
@@ -19,7 +19,7 @@ class PostInstall(install):
install.run(self)
here = path.abspath(path.dirname(__file__))
-version = '0.1.9.1'
+version = '0.1.9.3'
# Read the readme file contents into variable
if sys.argv[-1] == 'publish' or sys.argv[-1] == 'publishtest': | Bugs: physicalSample and callibration
Two small fixes. | nickmckay_LiPD-utilities | train |
138b035a63cd0f5273eac2cabdb1b35598cc7494 | diff --git a/perceval/_version.py b/perceval/_version.py
index <HASH>..<HASH> 100644
--- a/perceval/_version.py
+++ b/perceval/_version.py
@@ -1,2 +1,2 @@
# Versions compliant with PEP 440 https://www.python.org/dev/peps/pep-0440
-__version__ = "0.9.2"
+__version__ = "0.9.3" | Update version number to <I> | chaoss_grimoirelab-perceval | train |
a9da8c173dbde2da194a127c2ed83ba37e268f26 | diff --git a/src/feat/database/client.py b/src/feat/database/client.py
index <HASH>..<HASH> 100644
--- a/src/feat/database/client.py
+++ b/src/feat/database/client.py
@@ -26,6 +26,7 @@ import uuid
import urllib
from twisted.internet import reactor
+from twisted.python import failure
from zope.interface import implements
from feat.common import log, defer, time, journal, serialization, error
@@ -569,18 +570,25 @@ class Connection(log.Logger, log.LogProxy):
return doc
def handle_immediate_failure(self, fail, hook, context):
- error.handle_failure(self, 'Failed calling %r with context %r. '
- 'This will result in NotMigratable error',
+ error.handle_failure(self, fail,
+ 'Failed calling %r with context %r. ',
hook, context)
return fail
def handle_unserialize_failure(self, fail, raw):
- # the failure has been already logged with more
- # detail from handle_immediate_failure()
- # handler, here we just repack the error
type_name = raw.get('.type')
version = raw.get('.version')
- raise NotMigratable((type_name, version, ))
+
+ if fail.check(ConflictError):
+ self.debug('Got conflict error when trying the upgrade the '
+ 'document: %s version: %s. Refetching it.',
+ type_name, version)
+ # probably we've already upgraded it concurrently
+ return self.get_document(raw['_id'])
+
+ error.handle_failure(self, fail, 'Asynchronous hooks of '
+ 'the upgrade failed. Raising NotMigratable')
+ return failure.Failure(NotMigratable((type_name, version, )))
def unserialize_list_of_documents(self, list_of_raw):
result = list() | Mind that upgrading a document might fail because of the conflict. | f3at_feat | train |
d24e533d8aa643972b01d2e275283381eb254298 | diff --git a/lib/src/main/java/com/rey/material/widget/SnackBar.java b/lib/src/main/java/com/rey/material/widget/SnackBar.java
index <HASH>..<HASH> 100644
--- a/lib/src/main/java/com/rey/material/widget/SnackBar.java
+++ b/lib/src/main/java/com/rey/material/widget/SnackBar.java
@@ -64,6 +64,8 @@ public class SnackBar extends FrameLayout {
public static final int STATE_SHOWED = 1;
public static final int STATE_SHOWING = 2;
public static final int STATE_DISMISSING = 3;
+
+ private boolean mIsRtl = false;
public interface OnActionClickListener{
@@ -138,19 +140,36 @@ public class SnackBar extends FrameLayout {
applyStyle(context, attrs, defStyleAttr, defStyleRes);
}
+ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
+ @Override
+ public void onRtlPropertiesChanged(int layoutDirection) {
+ boolean rtl = layoutDirection == LAYOUT_DIRECTION_RTL;
+ if(mIsRtl != rtl) {
+ mIsRtl = rtl;
+
+ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
+ mText.setTextDirection((mIsRtl ? TEXT_DIRECTION_RTL : TEXT_DIRECTION_LTR));
+ mAction.setTextDirection((mIsRtl ? TEXT_DIRECTION_RTL : TEXT_DIRECTION_LTR));
+ }
+
+ requestLayout();
+ }
+ }
+
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
- int width = 0;
- int height = 0;
+ int width;
+ int height;
if(mAction.getVisibility() == View.VISIBLE){
mAction.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), heightMeasureSpec);
- mText.measure(MeasureSpec.makeMeasureSpec(widthSize - (mAction.getMeasuredWidth() - mText.getPaddingRight()), widthMode), heightMeasureSpec);
- width = mText.getMeasuredWidth() + mAction.getMeasuredWidth() - mText.getPaddingRight();
+ int padding = mIsRtl ? mText.getPaddingLeft() : mText.getPaddingRight();
+ mText.measure(MeasureSpec.makeMeasureSpec(widthSize - (mAction.getMeasuredWidth() - padding), widthMode), heightMeasureSpec);
+ width = mText.getMeasuredWidth() + mAction.getMeasuredWidth() - padding;
}
else{
mText.measure(MeasureSpec.makeMeasureSpec(widthSize, widthMode), heightMeasureSpec);
@@ -194,11 +213,17 @@ public class SnackBar extends FrameLayout {
int childBottom = b - t - getPaddingBottom();
if(mAction.getVisibility() == View.VISIBLE){
- mAction.layout(childRight - mAction.getMeasuredWidth(), childTop, childRight, childBottom);
- mText.layout(childLeft, childTop, childRight - mAction.getMeasuredWidth() + mText.getPaddingRight(), childBottom);
+ if(mIsRtl) {
+ mAction.layout(childLeft, childTop, childLeft + mAction.getMeasuredWidth(), childBottom);
+ childLeft += mAction.getMeasuredWidth() - mText.getPaddingLeft();
+ }
+ else {
+ mAction.layout(childRight - mAction.getMeasuredWidth(), childTop, childRight, childBottom);
+ childRight -= mAction.getMeasuredWidth() - mText.getPaddingRight();
+ }
}
- else
- mText.layout(childLeft, childTop, childRight, childBottom);
+
+ mText.layout(childLeft, childTop, childRight, childBottom);
}
@SuppressWarnings("deprecation") | Add support RTL to SnackBar class. | rey5137_material | train |
e813c80409728c94fb44dcad3e496815c669e3a2 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -45,6 +45,7 @@ setup(
],
install_requires=install_requires,
tests_require=tests_require,
+ python_requires='>=3.0',
entry_points={
'console_scripts': [
'fierce = fierce.fierce:main', | Add Python 3 requirement to setup.py | mschwager_fierce | train |
0e238374cb5261b2d959930136587e6d92891e58 | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -10,10 +10,10 @@ module.exports = {
Store config from `ember-cli-build.js`
*/
included: function(app, parentAddon) {
- this.options = app.options.newVersion || {};
+ this._options = app.options.newVersion || {};
- if (this.options === true) {
- this.options = { fileName: 'VERSION.txt' };
+ if (this._options === true) {
+ this._options = { fileName: 'VERSION.txt' };
}
},
@@ -22,8 +22,8 @@ module.exports = {
be accessed via `import config from '../config/environment';`
*/
config: function(env, baseConfig) {
- if (this.options && this.options.fileName) {
- return { newVersion: this.options };
+ if (this._options && this._options.fileName) {
+ return { newVersion: this._options };
}
},
@@ -33,9 +33,9 @@ module.exports = {
*/
treeForPublic: function() {
var content = this.parent.pkg.version || '';
- var fileName = this.options.fileName;
+ var fileName = this._options.fileName;
- if (this.options.fileName) {
+ if (this._options.fileName) {
this.ui.writeLine('Created ' + fileName);
return writeFile(fileName, content);
} | fix: this.options is used be ember-cli, use an alternate name
Resolves #<I> | sethwebster_ember-cli-new-version | train |
ddf07c0dbe0401a562f00b120634aa6a861b41e2 | diff --git a/lib/elasticsearch/client/hits.rb b/lib/elasticsearch/client/hits.rb
index <HASH>..<HASH> 100644
--- a/lib/elasticsearch/client/hits.rb
+++ b/lib/elasticsearch/client/hits.rb
@@ -52,7 +52,7 @@ module ElasticSearch
@total_entries = response["hits"]["total"]
@_shards = response["_shards"]
@facets = response["facets"]
- @scroll_id = response["_scrollId"]
+ @scroll_id = response["_scroll_id"] || response["_scrollId"]
populate(@options[:ids_only])
end
diff --git a/lib/elasticsearch/client/index.rb b/lib/elasticsearch/client/index.rb
index <HASH>..<HASH> 100644
--- a/lib/elasticsearch/client/index.rb
+++ b/lib/elasticsearch/client/index.rb
@@ -82,9 +82,18 @@ module ElasticSearch
end
#ids_only Return ids instead of hits
- def scroll(scroll_id, options={})
- response = execute(:scroll, scroll_id)
- Hits.new(response, { :ids_only => options[:ids_only] }).freeze
+ #pass a block to execute the block for each batch of hits
+ def scroll(scroll_id, options={}, &block)
+ begin
+ search_options = options.reject { |k, v| [:page, :per_page, :ids_only, :limit, :offset].include?(k) }
+ response = execute(:scroll, scroll_id, options)
+ hits = Hits.new(response, { :ids_only => options[:ids_only] }).freeze
+ if block_given? && !hits.empty?
+ yield hits
+ scroll_id = hits.scroll_id
+ end
+ end until !block_given? || hits.empty?
+ hits
end
#df The default field to use when no field prefix is defined within the query.
diff --git a/lib/elasticsearch/transport/base_protocol.rb b/lib/elasticsearch/transport/base_protocol.rb
index <HASH>..<HASH> 100644
--- a/lib/elasticsearch/transport/base_protocol.rb
+++ b/lib/elasticsearch/transport/base_protocol.rb
@@ -46,8 +46,9 @@ module ElasticSearch
results # {"hits"=>{"hits"=>[{"_id", "_type", "_source", "_index", "_score"}], "total"}, "_shards"=>{"failed", "total", "successful"}}
end
- def scroll(scroll_id)
- response = request(:get, {:op => "_search/scroll"}, {:scroll_id => scroll_id })
+ def scroll(scroll_id, options={})
+ # patron cannot submit get requests with content, so we pass the scroll_id in the parameters
+ response = request(:get, {:op => "_search/scroll"}, options.merge(:scroll_id => scroll_id))
handle_error(response) unless response.status == 200
results = encoder.decode(response.body)
# unescape ids | fix scroll support and add ability to scroll using a block | grantr_rubberband | train |
4333ea73cde16e9b0451f1df84f35711a700368b | diff --git a/test/src/packageJSONExists.test.js b/test/src/packageJSONExists.test.js
index <HASH>..<HASH> 100644
--- a/test/src/packageJSONExists.test.js
+++ b/test/src/packageJSONExists.test.js
@@ -1,6 +1,6 @@
require('chai').should();
const helpers = require('../../lib/helpers');
-const syncExec = require('sync-exec');
+const {execSync} = require('child_process');
describe('packageJSONExists', () => {
it('should return true', () => {
@@ -8,9 +8,9 @@ describe('packageJSONExists', () => {
});
it('should return false', () => {
- syncExec('mv package.json package.json.disappeared');
+ execSync('mv package.json package.json.disappeared');
helpers.packageJSONExists().should.equal(false);
- syncExec('mv package.json.disappeared package.json');
+ execSync('mv package.json.disappeared package.json');
});
}); | remove exec sync from test | siddharthkp_auto-install | train |
7096c818f40df493842c1e0f0ef31008080d11ca | diff --git a/yotta/test_subcommand.py b/yotta/test_subcommand.py
index <HASH>..<HASH> 100644
--- a/yotta/test_subcommand.py
+++ b/yotta/test_subcommand.py
@@ -47,7 +47,7 @@ def findCTests(builddir, recurse_yotta_modules=False):
# seems to be to parse the CTestTestfile.cmake files, which kinda sucks,
# but works... Patches welcome.
tests = []
- add_test_re = re.compile('add_test\\([^" ]*\s*"(.*)"\\)')
+ add_test_re = re.compile('add_test\\([^" ]*\s*"(.*)"\\)', flags=re.IGNORECASE)
for root, dirs, files in os.walk(builddir, topdown=True):
if not recurse_yotta_modules:
dirs = [d for d in dirs if d != 'ym']
@@ -55,7 +55,7 @@ def findCTests(builddir, recurse_yotta_modules=False):
with open(os.path.join(root, 'CTestTestfile.cmake'), 'r') as ctestf:
dir_tests = []
for line in ctestf:
- if line.startswith('add_test'):
+ if line.lower().startswith('add_test'):
match = add_test_re.search(line)
if match:
dir_tests.append(match.group(1)) | Case-insensitive parsing of CMake add_test() commands from CMakeTest files | ARMmbed_yotta | train |
20fb8ca2774d56f1eb26c70221f859a5aad48932 | diff --git a/tchannel-core/src/main/java/com/uber/tchannel/api/TChannel.java b/tchannel-core/src/main/java/com/uber/tchannel/api/TChannel.java
index <HASH>..<HASH> 100644
--- a/tchannel-core/src/main/java/com/uber/tchannel/api/TChannel.java
+++ b/tchannel-core/src/main/java/com/uber/tchannel/api/TChannel.java
@@ -56,6 +56,7 @@ import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.HashedWheelTimer;
+import io.netty.util.concurrent.DefaultThreadFactory;
import io.opentracing.Tracer;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
@@ -232,6 +233,9 @@ public final class TChannel {
public static class Builder {
+ private int bossGroupThreads = 1;
+ private int childGroupThreads = 0; // 0 (zero) defaults to NettyRuntime.availableProcessors()
+
private final @NotNull HashedWheelTimer timer;
private static ExecutorService defaultExecutorService = null;
private @NotNull EventLoopGroup bossGroup;
@@ -265,8 +269,6 @@ public final class TChannel {
}
timer = new HashedWheelTimer(10, TimeUnit.MILLISECONDS); // FIXME this is premature and may leak timer
- bossGroup = useEpoll ? new EpollEventLoopGroup(1) : new NioEventLoopGroup(1);
- childGroup = useEpoll ? new EpollEventLoopGroup() : new NioEventLoopGroup();
}
/** This provides legacy behavior of globally shared {@link ForkJoinPool} as the default executor. */
@@ -302,6 +304,17 @@ public final class TChannel {
return this;
}
+ public @NotNull Builder setBossGroupThreads(int bossGroupThreads) {
+ this.bossGroupThreads = bossGroupThreads;
+ return this;
+ }
+
+ /** Set to 0 (zero) to default to environment-based count. */
+ public @NotNull Builder setChildGroupThreads(int childGroupThreads) {
+ this.childGroupThreads = childGroupThreads;
+ return this;
+ }
+
public @NotNull Builder setBossGroup(@NotNull EventLoopGroup bossGroup) {
this.bossGroup = bossGroup;
return this;
@@ -339,6 +352,12 @@ public final class TChannel {
public @NotNull TChannel build() {
logger.debug(useEpoll ? "Using native epoll transport" : "Using NIO transport");
+ bossGroup = useEpoll
+ ? new EpollEventLoopGroup(bossGroupThreads, new DefaultThreadFactory("epoll-boss-group"))
+ : new NioEventLoopGroup(bossGroupThreads, new DefaultThreadFactory("nio-boss-group"));
+ childGroup = useEpoll
+ ? new EpollEventLoopGroup(childGroupThreads, new DefaultThreadFactory("epoll-child-group"))
+ : new NioEventLoopGroup(childGroupThreads, new DefaultThreadFactory("nio-child-group"));
return new TChannel(this);
} | Allow customizing child group thread pool size | uber_tchannel-java | train |
a350a72e1a604d9edafefe20e056e42655a25dd8 | diff --git a/katcp/__init__.py b/katcp/__init__.py
index <HASH>..<HASH> 100644
--- a/katcp/__init__.py
+++ b/katcp/__init__.py
@@ -14,4 +14,4 @@ except ImportError:
from katcp import Message, KatcpSyntaxError, MessageParser, DeviceClient, \
BlockingClient, DeviceMetaclass, DeviceServerBase, \
- DeviceServer, Sensor, DeviceLogger, FailReply
+ DeviceServer, Sensor, DeviceLogger, FailReply, AsyncReply
diff --git a/katcp/katcp.py b/katcp/katcp.py
index <HASH>..<HASH> 100644
--- a/katcp/katcp.py
+++ b/katcp/katcp.py
@@ -117,6 +117,10 @@ class Message(object):
" alphabetic character (got %r)."
% (name,))
+ def copy(self):
+ """Return a shallow copy of the message object and its arguments."""
+ return Message(self.mtype, self.name, self.arguments)
+
def __str__(self):
"""Return Message serialized for transmission.
@@ -687,6 +691,14 @@ class FailReply(Exception):
"""
pass
+class AsyncReply(Exception):
+ """A custom exception which, when thrown in a request handler,
+ indicates to DeviceServerBase that no reply has been returned
+ by the handler but that the handler has arranged for a reply
+ message to be sent at a later time.
+ """
+ pass
+
class DeviceServerBase(object):
"""Base class for device servers.
@@ -813,12 +825,16 @@ class DeviceServerBase(object):
def handle_request(self, sock, msg):
"""Dispatch a request message to the appropriate method."""
+ send_reply = True
if msg.name in self._request_handlers:
try:
reply = self._request_handlers[msg.name](self, sock, msg)
assert (reply.mtype == Message.REPLY)
assert (reply.name == msg.name)
self._logger.info("%s OK" % (msg.name,))
+ except AsyncReply, e:
+ self._logger.info("%s ASYNC OK" % (msg.name,))
+ send_reply = False
except FailReply, e:
reason = str(e)
self._logger.error("Request %s FAIL: %s" % (msg.name, reason))
@@ -835,7 +851,8 @@ class DeviceServerBase(object):
else:
self._logger.error("%s INVALID: Unknown request." % (msg.name,))
reply = Message.reply(msg.name, "invalid", "Unknown request.")
- sock.send(str(reply) + "\n")
+ if send_reply:
+ sock.send(str(reply) + "\n")
def handle_inform(self, sock, msg):
"""Dispatch an inform message to the appropriate method.""" | Add copy method for copying a message. Add AsyncReply exception to allow reply handlers to declare they will reply later (being tried out by proxy implementation).
git-svn-id: <URL> | ska-sa_katcp-python | train |
912e6b127a65ca5ddcffb7eb839b069268a674f1 | diff --git a/lib/bud/joins.rb b/lib/bud/joins.rb
index <HASH>..<HASH> 100644
--- a/lib/bud/joins.rb
+++ b/lib/bud/joins.rb
@@ -167,24 +167,22 @@ module Bud
# that satisfy the predicates +preds+, and project only onto the attributes
# of the first collection
public
- def lefts(*preds)
- unless preds.empty?
- @localpreds ||= []
- @localpreds += disambiguate_preds(preds)
- end
- map{ |l,r| l }
+ def lefts(*preds, &blk)
+ setup_preds(preds) unless preds.empty?
+ # given new preds, the state for the join will be different. set it up again.
+ setup_state if self.class <= Bud::BudJoin
+ map{ |l,r| blk.nil? ? l : blk.call(l) }
end
# given a * expression over 2 collections, form all combinations of items
# that satisfy the predicates +preds+, and project only onto the attributes
# of the second item
public
- def rights(*preds)
- unless preds.empty?
- @localpreds ||= []
- @localpreds += disambiguate_preds(preds)
- end
- map{ |l,r| r }
+ def rights(*preds, &blk)
+ setup_preds(preds) unless preds.empty?
+ # given new preds, the state for the join will be different. set it up again.
+ setup_state if self.class <= Bud::BudJoin
+ map{ |l,r| blk.nil? ? r : blk.call(r) }
end
# given a * expression over 2 collections, form all combos of items that
diff --git a/test/tc_aggs.rb b/test/tc_aggs.rb
index <HASH>..<HASH> 100644
--- a/test/tc_aggs.rb
+++ b/test/tc_aggs.rb
@@ -132,14 +132,12 @@ class JoinAgg < RenameGroup
state do
scratch :richsal, [:sal]
scratch :rich, emp.key_cols => emp.val_cols
- scratch :rich_empty, emp.key_cols => emp.val_cols
scratch :argrich, emp.key_cols => emp.val_cols
end
bloom do
richsal <= emp.group([], max(:sal))
rich <= (richsal * emp).matches.rights
- rich_empty <= (richsal * emp).matches.rights(emp.ename => emp.dname)
argrich <= emp.argmax([], emp.sal)
end
end
@@ -181,19 +179,19 @@ end
class ChainAgg
include Bud
-
+
state do
table :t1
table :t2
table :t3
table :r
end
-
+
bootstrap do
t1 <= [[1,1],[2,1]]
r <= [['a', 'b']]
end
-
+
bloom do
t2 <= (t1 * r * r).combos {|a,b,c| a}
t3 <= t2.argmax([], :key)
@@ -257,7 +255,6 @@ class TestAggs < Test::Unit::TestCase
program = JoinAgg.new
program.tick
assert_equal([['bob', 'shoe', 11]], program.rich.to_a)
- assert_equal([], program.rich_empty.to_a)
assert_equal([['bob', 'shoe', 11]], program.argrich.to_a)
end
@@ -272,27 +269,26 @@ class TestAggs < Test::Unit::TestCase
p.tick
assert(([[1,1]]) == p.t2.to_a || ([[2,1]]) == p.t2.to_a)
end
-
+
def test_chain_agg
p = ChainAgg.new
q = Queue.new
-
+
p.register_callback(:t3) { q.push(true) }
p.run_bg
q.pop
- assert_equal([[2,1]], p.t3.to_a)
+ assert_equal([[2,1]], p.t3.to_a)
end
-
+
class SimpleAgg
include Bud
state {table :t1}
bootstrap {t1 << [[1,1]]}
bloom {temp :t2 <= t1.group([:key])}
end
-
+
def test_simple_agg
p = SimpleAgg.new
p.tick
end
-
end
diff --git a/test/tc_joins.rb b/test/tc_joins.rb
index <HASH>..<HASH> 100644
--- a/test/tc_joins.rb
+++ b/test/tc_joins.rb
@@ -465,4 +465,39 @@ class TestJoins < Test::Unit::TestCase
assert_equal(p.outleft.to_a, p.outlpairs.to_a)
assert_equal(p.outright.to_a, p.outrpairs.to_a)
end
+
+ class TestBug179
+ include Bud
+
+ state do
+ table :node, [:uid] => [:addr]
+ scratch :node_cnt, [] => [:num]
+ scratch :node_ready, [] => [:ready]
+ table :result, [:r]
+ end
+
+ bootstrap do
+ node <= [[0, "abc1"],
+ [1, "abc2"],
+ [2, "abc3"]]
+ end
+
+ bloom do
+ node_cnt <= node.group(nil, count)
+ node_ready <= node_cnt {|c| [true] if c.num == 3}
+
+ result <= (node_ready * node).rights do |n|
+ ["#1: #{n.addr}"] if n.uid == 0
+ end
+ result <= (node * node_ready).lefts do |n|
+ ["#2: #{n.addr}"] if n.uid == 0
+ end
+ end
+ end
+
+ def test_bug_179
+ b = TestBug179.new
+ b.tick
+ assert_equal([["#1: abc1"], ["#1: abc1"]], b.result.to_a.sort)
+ end
end | Fix bug in BudJoin#lefts and BudJoin#rights.
Closes #<I>. This commit temporarily removes a test case from tc_aggs, because
it caused it to fail; I believe it just exposes brokenness that always existed,
however -- following up on that now. | bloom-lang_bud | train |
9fc4a976a1865005e0e9cd6e950dda7e9c0eff49 | diff --git a/src/Mapper/DefaultMapper.php b/src/Mapper/DefaultMapper.php
index <HASH>..<HASH> 100644
--- a/src/Mapper/DefaultMapper.php
+++ b/src/Mapper/DefaultMapper.php
@@ -124,7 +124,11 @@ class DefaultMapper implements MapperInterface
}
/**
+ * Updates an entity's row by a certain ID
*
+ * @param int $id The ID of the row being updated
+ * @param \p810\MySQL\Mapper\EntityInterface The entity from which to source data for the update
+ * @return bool
*/
public function updateById(int $id, EntityInterface $entity): bool
{
@@ -150,7 +154,10 @@ class DefaultMapper implements MapperInterface
}
/**
+ * Deletes an entity's row by a certain ID
*
+ * @param int $id The ID of the row being deleted
+ * @return bool
*/
public function deleteById(int $id): bool
{ | Adds docblocks for two DefaultMapper methods | p810_mysql-helper | train |
6f8a333353d9d9bfe6d5b8a9710581af46bd7e25 | diff --git a/lfs/client.go b/lfs/client.go
index <HASH>..<HASH> 100644
--- a/lfs/client.go
+++ b/lfs/client.go
@@ -581,10 +581,8 @@ func newClientRequest(method, rawurl string, header map[string]string) (*http.Re
return nil, nil, err
}
- if header != nil {
- for key, value := range header {
- req.Header.Set(key, value)
- }
+ for key, value := range header {
+ req.Header.Set(key, value)
}
req.Header.Set("User-Agent", UserAgent) | Remove redundant nil check for a map
Go will treat it as an empty map and range through all 0 elements just fine. | git-lfs_git-lfs | train |
e59c7831a801ac2a8d6f02d3042bb56eb7289908 | diff --git a/packages/run-v5/lib/colorize.js b/packages/run-v5/lib/colorize.js
index <HASH>..<HASH> 100644
--- a/packages/run-v5/lib/colorize.js
+++ b/packages/run-v5/lib/colorize.js
@@ -33,7 +33,7 @@ let lineRegex = /^(.*?\[([\w-]+)([\d.]+)?]:)(.*)?$/
const red = c.red
const dim = i => c.dim(i)
const other = dim
-const path = i => c.blue(i)
+const path = i => c.green(i)
const method = i => c.bold.magenta(i)
const status = code => {
if (code < 200) return code | fix: Change path color in request log from blue to green for better visibility on both dark and light terminal backgrounds (#<I>) | heroku_cli | train |
1e0ad5c5b115035e85856037a2f65a6f518234ba | diff --git a/docs/router.rst b/docs/router.rst
index <HASH>..<HASH> 100644
--- a/docs/router.rst
+++ b/docs/router.rst
@@ -42,6 +42,7 @@ is an example using all configuration options.
'decorators': [admin_required],
'logic': create_note,
'response': 'note',
+ 'schema': 'special_note.yaml',
'title': 'Create Note',
}
}
@@ -182,6 +183,10 @@ additional configuration:
- `response` should be a key from the definitions section of the schema that
identifies which definition should be used to validate the response returned
by the logic function.
+- `schema` is an alternative schema file that should be used for the endpoint.
+ This is useful for grouping related endpoints together that use different
+ schemas. This argument should be the name of the schema within the schema
+ directory. e.g. `'user.yaml'`.
- `title` is a custom title to use as the header for the route/method. If a
title is not provided, one will be generated based on the http method. The
automatic title will be one of `Retrieve`, `Delete`, `Create`, or `Update`.
@@ -200,6 +205,7 @@ additional configuration:
'decorators': [admin_required],
'logic': create_note,
'response': 'note',
+ 'schema': 'special_note.yaml',
'title': 'Create Note',
}
}
diff --git a/doctor/router.py b/doctor/router.py
index <HASH>..<HASH> 100644
--- a/doctor/router.py
+++ b/doctor/router.py
@@ -157,7 +157,13 @@ class Router(object):
params.extend(additional_args.get('required', []))
required.extend(additional_args.get('required', []))
- http_func = getattr(schema, 'http_' + method)
+ # Check if the schema was overridden for the method.
+ if opts.get('schema'):
+ method_schema = self.get_schema(opts['schema'])
+ else:
+ method_schema = schema
+
+ http_func = getattr(method_schema, 'http_' + method)
func = http_func(
opts['logic'], params=params, required=required,
response=opts.get('response'), title=opts.get('title'),
diff --git a/test/test_router.py b/test/test_router.py
index <HASH>..<HASH> 100644
--- a/test/test_router.py
+++ b/test/test_router.py
@@ -150,6 +150,12 @@ class RouterTestCase(TestCase):
'get': {
'logic': logic_get,
+ # Specifying a different schema file that contains `someid`
+ # for the response. An example of overriding the schema
+ # at the http method level. This would fail without the
+ # schema key since someid is not defined in annotation.yaml
+ 'schema': 'common.yaml',
+ 'response': 'someid',
},
'post': {
'additional_args': { | Adds ability to override schema for an endpoint. | upsight_doctor | train |
ac962754bbfe640d641c05d8e8ed51f73379b084 | diff --git a/lib/filters/global/web.js b/lib/filters/global/web.js
index <HASH>..<HASH> 100644
--- a/lib/filters/global/web.js
+++ b/lib/filters/global/web.js
@@ -6,9 +6,12 @@ var preq = require('preq');
function handleAll (restbase, req) {
// some tests use a fake en.wikipedia.test.local domain, which will confuse
- // external services such as parsoid and api.php -- if found here, replace
+ // external services such as parsoid and api.php -- if found here, replace
// with en.wikipedia.org
- req.uri = req.uri.replace(/\/en.wikipedia.test.local\//, '/en.wikipedia.org/');
+ req.uri = req.uri.replace(/^http:\/\/en\.wikipedia\.test\.local\//,
+ 'http://en.wikipedia.org/')
+ .replace(/^http:\/\/parsoid-lb\.eqiad\.wikimedia\.org\/v2\/en\.wikipedia\.test\.local\//,
+ 'http://parsoid-lb.eqiad.wikimedia.org/v2/en.wikipedia.org/');
if (restbase._options.conf.offline) {
throw new Error("We are offline, you are tring to fallback to dynamic api"); | More thorough anchoring for test domain replacements in web.js | wikimedia_restbase | train |
47d55ce96112e1d4412cb7aa1a6dee0f36397ab7 | diff --git a/packages/reactstrap-validation-select/AvResourceSelect.js b/packages/reactstrap-validation-select/AvResourceSelect.js
index <HASH>..<HASH> 100644
--- a/packages/reactstrap-validation-select/AvResourceSelect.js
+++ b/packages/reactstrap-validation-select/AvResourceSelect.js
@@ -47,16 +47,15 @@ class AvResourceSelect extends Component {
},
};
- if (typeof this.props.parameters === 'function') {
- data = {
- ...data,
- ...this.props.parameters(data),
- };
- } else {
- data = {
- ...data,
- ...this.props.parameters,
- };
+ if (args.length !== 3) {
+ if (typeof this.props.parameters === 'function') {
+ data = this.props.parameters(data);
+ } else {
+ data = {
+ ...data,
+ ...this.props.parameters,
+ };
+ }
}
if (this.props.graphqlConfig.query) {
@@ -67,38 +66,30 @@ class AvResourceSelect extends Component {
q: encodeURIComponent(inputValue),
limit: this.props.itemsPerPage,
customerId: this.props.customerId,
- ...this.props.parameters,
};
}
- if (typeof this.props.parameters === 'function') {
- params = {
- ...params,
- ...this.props.parameters(params),
- };
- } else {
- params = {
- ...params,
- ...this.props.parameters,
- };
+ if (args.length !== 3) {
+ if (typeof this.props.parameters === 'function') {
+ params = this.props.parameters(params);
+ } else {
+ params = {
+ ...params,
+ ...this.props.parameters,
+ };
+ }
}
if (args.length === 3) {
if (this.props.graphqlConfig) {
data.variables.page = page;
if (typeof this.props.parameters === 'function') {
- data = {
- ...data,
- ...this.props.parameters(data),
- };
+ data = this.props.parameters(data);
}
} else {
params.offset = (page - 1) * this.props.itemsPerPage;
if (typeof this.props.parameters === 'function') {
- params = {
- ...params,
- ...this.props.parameters(params),
- };
+ params = this.props.parameters(params);
}
}
} else {
@@ -259,6 +250,7 @@ AvResourceSelect.create = defaults => {
AvResourceSelect.propTypes = {
requestConfig: PropTypes.object,
+ method: PropTypes.string,
resource: PropTypes.shape({
postGet: PropTypes.func,
post: PropTypes.func,
diff --git a/packages/reactstrap-validation-select/tests/AvResourceSelect.test.js b/packages/reactstrap-validation-select/tests/AvResourceSelect.test.js
index <HASH>..<HASH> 100644
--- a/packages/reactstrap-validation-select/tests/AvResourceSelect.test.js
+++ b/packages/reactstrap-validation-select/tests/AvResourceSelect.test.js
@@ -348,9 +348,13 @@ const renderResourceSelect = props =>
<AvForm>
<AvResourceSelect
name="region-form-input"
- parameters={({ q, limit, offset }) => ({
+ parameters={({ q, limit, offset, ...rest }) => ({
+ ...rest,
+ q,
+ limit,
testq: q,
testPage: offset / limit + 1,
+ offset,
})}
{...props}
/> | refactor(reactstrap-validation-select): method overrides and param function overrides | Availity_availity-react | train |
ae3d879bb4d34a0087718c5d653d5c25ca05ca7e | diff --git a/lib/iban-check/iban.rb b/lib/iban-check/iban.rb
index <HASH>..<HASH> 100644
--- a/lib/iban-check/iban.rb
+++ b/lib/iban-check/iban.rb
@@ -1,4 +1,7 @@
module Iban
+ class MissingCountryException < StandardError
+ end
+
class IbanCheck
BRANCH_WEIGHT = [7,1,3,9,7,1,3]
@@ -85,7 +88,7 @@ module Iban
result
else
- raise "No country specified"
+ raise MissingCountryException
end
end
diff --git a/spec/iban-check_spec.rb b/spec/iban-check_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/iban-check_spec.rb
+++ b/spec/iban-check_spec.rb
@@ -18,7 +18,7 @@ describe "IbanCheck" do
end
it "should raise error -- no country" do
- lambda {Iban::IbanCheck.new(:iban => "27 1140 2004 0010 3002 0135 5387")}.should raise_error
+ lambda {Iban::IbanCheck.new(:iban => "27 1140 2004 0010 3002 0135 5387")}.should raise_error(Iban::MissingCountryException)
end
it "should recognize country" do | Raise MissingCountryException for easier catching by the caller | LTe_iban-check | train |
e017c35a64893f05e1274b60b43977df7d5a79ef | diff --git a/text/src/test/java/eu/interedition/text/token/TokenizerTest.java b/text/src/test/java/eu/interedition/text/token/TokenizerTest.java
index <HASH>..<HASH> 100644
--- a/text/src/test/java/eu/interedition/text/token/TokenizerTest.java
+++ b/text/src/test/java/eu/interedition/text/token/TokenizerTest.java
@@ -41,6 +41,7 @@ import org.annolab.tt4j.TreeTaggerException;
import org.annolab.tt4j.TreeTaggerWrapper;
import org.hibernate.SessionFactory;
import org.junit.Before;
+import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
@@ -69,6 +70,7 @@ public class TokenizerTest extends AbstractTestResourceTest {
private SessionFactory sessionFactory;
@Test
+ @Ignore
public void printTokenization() throws IOException, TreeTaggerException {
final Text text = tokenize();
printTokenizedWitness(text, annotationName(SENTENCE_NAME));
@@ -84,6 +86,7 @@ public class TokenizerTest extends AbstractTestResourceTest {
treeTagger.setPerformanceMode(true);
treeTagger.setHandler(new TokenHandler<String>() {
public void token(String token, String pos, String lemma) {
+ System.out.printf("%s; %s; %s\n", token, pos, lemma);
posStatistics.put(pos, Objects.firstNonNull(posStatistics.get(pos), 0) + 1);
}
}); | ignore tokenizer test with POS tagger | interedition_collatex | train |
9721bc852fc58f64df2d7fa15d5a3a99cea0936c | diff --git a/tests/test_50_sample_data.py b/tests/test_50_sample_data.py
index <HASH>..<HASH> 100644
--- a/tests/test_50_sample_data.py
+++ b/tests/test_50_sample_data.py
@@ -49,7 +49,7 @@ def test_open_dataset_fail(grib_name):
'reduced_gg',
'regular_gg_sfc',
'regular_gg_pl',
- pytest.param('regular_gg_ml', marks=pytest.mark.xfail),
+ 'regular_gg_ml',
pytest.param('regular_gg_ml_g2', marks=pytest.mark.xfail),
'regular_ll_sfc',
'regular_ll_msl', | Enable testing of model level GRIB1 file. | ecmwf_cfgrib | train |
b0b92bebea96a8c7e8ed6933d94aa14b8e26f871 | diff --git a/projects/l2_pooling/capacity_test.py b/projects/l2_pooling/capacity_test.py
index <HASH>..<HASH> 100644
--- a/projects/l2_pooling/capacity_test.py
+++ b/projects/l2_pooling/capacity_test.py
@@ -271,6 +271,7 @@ def testOnSingleRandomSDR(objects, exp, numRepeats=100):
def plotResults(result, ax=None, xaxis="numPointsPerObject",
filename=None, marker='-bo'):
+
if xaxis == "numPointsPerObject":
x = result.numPointsPerObject
xlabel = "# Pts / Obj"
@@ -470,7 +471,13 @@ def runExperiment1(numObjects=2,
markers = ("-bo", "-ro", "-co", "-go")
ploti = 0
fig, ax = plt.subplots(2, 2)
+ st = fig.suptitle(
+ "Varying points per object x 2 objects ({} cortical column{})"
+ .format(numCorticalColumns, "s" if numCorticalColumns > 1 else ""
+ ), fontsize="x-large")
+
legendEntries = []
+
for maxNewSynapseCount in maxNewSynapseCountRange:
activationThreshold = int(maxNewSynapseCount) - 1
@@ -487,6 +494,11 @@ def runExperiment1(numObjects=2,
legendEntries.append("# syn {}".format(maxNewSynapseCount))
plt.legend(legendEntries, loc=2)
+ fig.tight_layout()
+
+ # shift subplots down:
+ st.set_y(0.95)
+ fig.subplots_adjust(top=0.85)
plt.savefig(
os.path.join(
@@ -521,6 +533,11 @@ def runExperiment2(numCorticalColumns=DEFAULT_NUM_CORTICAL_COLUMNS,
markers = ("-bo", "-ro", "-co", "-go")
ploti = 0
fig, ax = plt.subplots(2, 2)
+ st = fig.suptitle(
+ "Varying number of objects ({} cortical column{})"
+ .format(numCorticalColumns, "s" if numCorticalColumns > 1 else ""
+ ), fontsize="x-large"
+ )
legendEntries = []
for maxNewSynapseCount in maxNewSynapseCountRange:
activationThreshold = int(maxNewSynapseCount) - 1
@@ -537,6 +554,12 @@ def runExperiment2(numCorticalColumns=DEFAULT_NUM_CORTICAL_COLUMNS,
ploti += 1
legendEntries.append("# syn {}".format(maxNewSynapseCount))
plt.legend(legendEntries, loc=2)
+ fig.tight_layout()
+
+ # shift subplots down:
+ st.set_y(0.95)
+ fig.subplots_adjust(top=0.85)
+
plt.savefig(
os.path.join(
plotDirName, | RES-<I> Improve labeling of charts | numenta_htmresearch | train |
13117c728cb7e0032b444f6746c621db6ffa59a2 | diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -187,6 +187,7 @@ describe( 'gulp-develop-server', function() {
should( app.options.killSignal ).eql( opt.killSignal );
app.kill( function( error ) {
+ if( error ) console.log( error );
should.not.exist( error );
should( app.child ).eql( null );
should( gutil.log.lastCall.args[ 0 ] ).match( /server was stopped/ ); | show error messages in some test faild | narirou_gulp-develop-server | train |
133a448f2c407acf1319bbfbaf77f5e91ce5a323 | diff --git a/misc/log-analytics/import_logs.py b/misc/log-analytics/import_logs.py
index <HASH>..<HASH> 100755
--- a/misc/log-analytics/import_logs.py
+++ b/misc/log-analytics/import_logs.py
@@ -1606,13 +1606,14 @@ class Parser(object):
try:
hit.query_string = format.get('query_string')
- # IIS detaults to - when there is no query string, but we want empty string
- if hit.query_string == '-':
- hit.query_string = ''
hit.path = hit.full_path
except BaseFormatException:
hit.path, _, hit.query_string = hit.full_path.partition(config.options.query_string_delimiter)
+ # IIS detaults to - when there is no query string, but we want empty string
+ if hit.query_string == '-':
+ hit.query_string = ''
+
hit.extension = hit.path.rsplit('.')[-1].lower()
try: | refs #<I> on IIS when no query string it shows as '-' so we assume '' instead. | matomo-org_matomo | train |
36f26d988f4946806649681c211948269105f0b5 | diff --git a/scripts/get-next-version.js b/scripts/get-next-version.js
index <HASH>..<HASH> 100644
--- a/scripts/get-next-version.js
+++ b/scripts/get-next-version.js
@@ -8,10 +8,14 @@ const currentVersion = require('../package.json').version
const bump = Bluebird.promisify(bumpCb)
const paths = ['packages', 'cli']
-// allow the semantic next version to be overridden by environment
-let nextVersion = process.env.NEXT_VERSION
+let nextVersion
const getNextVersionForPath = async (path) => {
+ // allow the semantic next version to be overridden by environment
+ if (process.env.NEXT_VERSION) {
+ return process.env.NEXT_VERSION
+ }
+
const { releaseType } = await bump({ preset: 'angular', path })
return semver.inc(currentVersion, releaseType || 'patch') | chore: fix NEXT_VERSION override (#<I>) | cypress-io_cypress | train |
6671ee242c3f8166dfef586ccb94e294e48ddc1e | diff --git a/test/test_transactions.py b/test/test_transactions.py
index <HASH>..<HASH> 100644
--- a/test/test_transactions.py
+++ b/test/test_transactions.py
@@ -258,7 +258,7 @@ def create_test(scenario_def, test):
for i in range(2):
session_name = 'session%d' % i
s = client.start_session(
- **camel_to_snake_args(test['transactionOptions'][session_name]))
+ **camel_to_snake_args(test['sessionOptions'][session_name]))
sessions[session_name] = s
# Store lsid so we can access it after end_session, in check_events. | Parse sessionOptions from tests, not transactionOptions | mongodb_mongo-python-driver | train |
e909ea2f6b031d6425f530aa66b948fde303e1d7 | diff --git a/src/Provider/CrudGeneratorServiceProvider.php b/src/Provider/CrudGeneratorServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/Provider/CrudGeneratorServiceProvider.php
+++ b/src/Provider/CrudGeneratorServiceProvider.php
@@ -34,7 +34,7 @@ class CrudGeneratorServiceProvider extends ServiceProvider
public function register()
{
include __DIR__.'/../routes.php';
- require __DIR__.'/../breadcrumbs.php';
+ // require __DIR__.'/../breadcrumbs.php';
require_once(__DIR__.'/../helpers.php');
$this->app->make('Bvipul\Generator\Module');
$this->app->make('Bvipul\Generator\Controllers\Generator'); | Breadcrumb problem resolved for now | bvipul_generator | train |
876ac6f3a2529af36c5e9bc8a2a6acb135116609 | diff --git a/services/managers/teamspeak3_manager.py b/services/managers/teamspeak3_manager.py
index <HASH>..<HASH> 100755
--- a/services/managers/teamspeak3_manager.py
+++ b/services/managers/teamspeak3_manager.py
@@ -117,6 +117,8 @@ class Teamspeak3Manager:
def _sync_ts_group_db():
remote_groups = Teamspeak3Manager._group_list()
local_groups = TSgroup.objects.all()
+ remote_groups = [ int(id) for id in remote_groups ]
+
print("--Doing group sync--")
print("Remote groups {0}").format(remote_groups.values())
for group in local_groups: | Strings and ints
I was comparing them. That was dumb | allianceauth_allianceauth | train |
00d8ce4fca3ecb9f5889755387e2e487caf046e7 | diff --git a/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceService.java b/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceService.java
index <HASH>..<HASH> 100644
--- a/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceService.java
+++ b/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceService.java
@@ -14,7 +14,10 @@ import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
+import android.os.Build;
import android.os.IBinder;
+import android.support.v4.app.NotificationCompat;
+
import com.octo.android.robospice.networkstate.DefaultNetworkStateChecker;
import com.octo.android.robospice.networkstate.NetworkStateChecker;
import com.octo.android.robospice.persistence.CacheManager;
@@ -190,17 +193,30 @@ public abstract class SpiceService extends Service {
}
/**
- * This method can be overrided in order to create a foreground
- * SpiceService. By default, it will create a notification that can't be
- * used to set a spiceService to foreground. It can work on some versions of
- * Android but it should be overriden for more safety.
+ * This method can be overriden in order to create a foreground
+ * SpiceService. By default, it will create a notification that can be
+ * used to set a spiceService to foreground (depending on the versions of Android, the behavior is different :
+ * before ICS, no notification is shown, on ICS+, a notification is shown with app icon). On Jelly Bean+,
+ * the notifiation only appears when notification bar is expanded / pulled down.
* @return a notification used to tell user that the SpiceService is still
* running and processing requests.
*/
public Notification createDefaultNotification() {
- return null;
+ NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
+ if( android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && android.os.Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
+ builder.setSmallIcon(getApplicationInfo().icon);
+ } else {
+ builder.setSmallIcon(0);
+ }
+ builder.setTicker(null);
+ builder.setWhen(System.currentTimeMillis());
+ final Notification note = builder.getNotification();
+ if( android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN ) {
+ note.priority = Notification.PRIORITY_MIN;
+ }
+ return note;
}
-
+
protected int getNotificationId() {
return DEFAULT_NOTIFICATION_ID;
} | Correct Javadoc and icon on ICS. | stephanenicolas_robospice | train |
bbba7d4625d4476f7972de6f269d231768645065 | diff --git a/server/src/main/java/org/jboss/as/server/deployment/SubDeploymentProcessor.java b/server/src/main/java/org/jboss/as/server/deployment/SubDeploymentProcessor.java
index <HASH>..<HASH> 100644
--- a/server/src/main/java/org/jboss/as/server/deployment/SubDeploymentProcessor.java
+++ b/server/src/main/java/org/jboss/as/server/deployment/SubDeploymentProcessor.java
@@ -47,8 +47,10 @@ public class SubDeploymentProcessor implements DeploymentUnitProcessor {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ResourceRoot deploymentResourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
- if(deploymentResourceRoot.getRoot().isDirectory()) {
- ExplodedDeploymentMarker.markAsExplodedDeployment(deploymentUnit);
+ if(deploymentUnit.getParent() != null && ExplodedDeploymentMarker.isExplodedDeployment(deploymentUnit.getParent())) {
+ if (deploymentResourceRoot.getRoot().isDirectory()) {
+ ExplodedDeploymentMarker.markAsExplodedDeployment(deploymentUnit);
+ }
}
final ServiceTarget serviceTarget = phaseContext.getServiceTarget(); | WFCORE-<I> non exploded deployments incorrectly marked as exploded | wildfly_wildfly-core | train |
76872992754500b27413b88f28b5dad866f1d12f | diff --git a/bin/express b/bin/express
index <HASH>..<HASH> 100755
--- a/bin/express
+++ b/bin/express
@@ -341,7 +341,7 @@ function createApplicationAt(path) {
// Session support
app = app.replace('{sess}', sessions
- ? '\n app.use(express.cookieDecoder());\n app.use(express.session());'
+ ? '\n app.use(express.cookieDecoder());\n app.use(express.session({ secret: \'your secret here\'}));'
: '');
// Template support
diff --git a/examples/auth/app.js b/examples/auth/app.js
index <HASH>..<HASH> 100644
--- a/examples/auth/app.js
+++ b/examples/auth/app.js
@@ -16,7 +16,7 @@ app.set('view engine', 'ejs');
app.use(express.bodyDecoder());
app.use(express.cookieDecoder());
-app.use(express.session());
+app.use(express.session({ secret: 'keyboard cat' }));
// Message helper, ideally we would use req.flash()
// however this is more light-weight for an example
diff --git a/examples/blog/app.js b/examples/blog/app.js
index <HASH>..<HASH> 100644
--- a/examples/blog/app.js
+++ b/examples/blog/app.js
@@ -28,7 +28,7 @@ app.configure(function(){
app.use(express.bodyDecoder());
app.use(express.methodOverride());
app.use(express.cookieDecoder());
- app.use(express.session());
+ app.use(express.session({ secret: 'keyboard cat' }));
app.use(app.router);
app.use(express.staticProvider(__dirname + '/public'));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
diff --git a/examples/flash/app.js b/examples/flash/app.js
index <HASH>..<HASH> 100644
--- a/examples/flash/app.js
+++ b/examples/flash/app.js
@@ -12,7 +12,7 @@ var express = require('../../lib/express');
var app = express.createServer(
express.cookieDecoder()
- , express.session()
+ , express.session({ secret: 'keyboard cat' })
);
// View settings
diff --git a/examples/form/app.js b/examples/form/app.js
index <HASH>..<HASH> 100644
--- a/examples/form/app.js
+++ b/examples/form/app.js
@@ -23,7 +23,7 @@ app.use(express.cookieDecoder());
// Required by req.flash() for persistent
// notifications
-app.use(express.session());
+app.use(express.session({ secret: 'keyboard cat' }));
app.get('/', function(req, res){
// get ?name=foo
diff --git a/examples/mvc/mvc.js b/examples/mvc/mvc.js
index <HASH>..<HASH> 100644
--- a/examples/mvc/mvc.js
+++ b/examples/mvc/mvc.js
@@ -18,7 +18,7 @@ function bootApplication(app) {
app.use(express.bodyDecoder());
app.use(express.methodOverride());
app.use(express.cookieDecoder());
- app.use(express.session());
+ app.use(express.session({ secret: 'keyboard cat' }));
app.use(app.router);
app.use(express.staticProvider(__dirname + '/public')); | Added secret to session middleware used in examples and generated app | expressjs_express | train |
4c71959919a78c0614f346d8c698980afb18ca3d | diff --git a/src/server/views/api/jobRetry.js b/src/server/views/api/jobRetry.js
index <HASH>..<HASH> 100644
--- a/src/server/views/api/jobRetry.js
+++ b/src/server/views/api/jobRetry.js
@@ -15,7 +15,7 @@ async function handler(req, res) {
if (jobState === 'failed' && typeof job.retry === 'function') {
await job.retry();
} else {
- await Queues.set(queue, job);
+ await Queues.set(queue, job.data);
}
return res.sendStatus(200); | fix: fix job retry (#<I>) | bee-queue_arena | train |
27aeb9291fef0cdf9a7e06194403a091ad6b64d7 | diff --git a/carbonserver/carbonserver.go b/carbonserver/carbonserver.go
index <HASH>..<HASH> 100644
--- a/carbonserver/carbonserver.go
+++ b/carbonserver/carbonserver.go
@@ -698,6 +698,10 @@ uloop:
continue uloop
case m := <-listener.newMetricsChan:
+ // listener.newMetricsChan might have high traffic, but
+ // in theory, there should be no starvation on other channels:
+ // https://groups.google.com/g/golang-nuts/c/4BR2Sdb6Zzk (2015)
+
fidx := listener.CurrentFileIndex()
if listener.trieIndex && listener.concurrentIndex && fidx != nil && fidx.trieIdx != nil {
metric := "/" + filepath.Clean(strings.ReplaceAll(m, ".", "/")+".wsp")
@@ -717,12 +721,10 @@ uloop:
cacheMetricNames = splitAndInsert(cacheMetricNames, newCacheMetricNames)
}
- if listener.updateFileList(dir, cacheMetricNames) {
+ if listener.updateFileList(dir, cacheMetricNames, quotaAndUsageStatTicker) {
listener.logger.Info("file list updated with cache, starting a new scan immediately")
- listener.updateFileList(dir, cacheMetricNames)
+ listener.updateFileList(dir, cacheMetricNames, quotaAndUsageStatTicker)
}
-
- listener.refreshQuotaAndUsage(quotaAndUsageStatTicker)
}
}
@@ -783,7 +785,7 @@ func (listener *CarbonserverListener) refreshQuotaAndUsage(quotaAndUsageStatTick
}
quotaStart := time.Now()
- throughputs, err := fidx.trieIdx.applyQuotas(listener.quotas...)
+ throughputs, err := fidx.trieIdx.applyQuotas(listener.quotaUsageReportFrequency, listener.quotas...)
if err != nil {
listener.logger.Error(
"refreshQuotaAndUsage",
@@ -822,7 +824,7 @@ func (listener *CarbonserverListener) refreshQuotaAndUsage(quotaAndUsageStatTick
)
}
-func (listener *CarbonserverListener) updateFileList(dir string, cacheMetricNames map[string]struct{}) (readFromCache bool) {
+func (listener *CarbonserverListener) updateFileList(dir string, cacheMetricNames map[string]struct{}, quotaAndUsageStatTicker <-chan time.Time) (readFromCache bool) {
logger := listener.logger.With(zap.String("handler", "fileListUpdated"))
defer func() {
if r := recover(); r != nil {
@@ -927,10 +929,6 @@ func (listener *CarbonserverListener) updateFileList(dir string, cacheMetricName
logger.Error("can't index symlink data dir", zap.String("path", dir))
}
- var usageRefreshTimeout = struct {
- refreshedAt time.Time
- count int
- }{time.Now(), 0}
err := filepath.Walk(dir, func(p string, info os.FileInfo, err error) error {
if err != nil {
logger.Info("error processing", zap.String("path", p), zap.Error(err))
@@ -943,9 +941,12 @@ func (listener *CarbonserverListener) updateFileList(dir string, cacheMetricName
// have consistent quota and usage metrics produced as
// regularly as possible according to the
// quotaUsageReportFrequency specified in the config.
- if usageRefreshTimeout.count++; listener.isQuotaEnabled() && usageRefreshTimeout.count > 10_000 && time.Since(usageRefreshTimeout.refreshedAt) >= listener.quotaUsageReportFrequency {
- listener.refreshQuotaAndUsage(nil)
- usageRefreshTimeout.refreshedAt = time.Now()
+ if listener.isQuotaEnabled() {
+ select {
+ case <-quotaAndUsageStatTicker:
+ listener.refreshQuotaAndUsage(quotaAndUsageStatTicker)
+ default:
+ }
}
// WHY: as filepath.walk could potentially taking a long | carbonserver: fix broken/untimely quota usage report/reset logics
The usageRefreshTimeout implementation in updateFileList is quite broken as it produces
report metric gaps from time to time.
And the listener.refreshQuotaAndUsage call after updateFileList in fileListUpdater loop
also causes incorrect quota usage report. | lomik_go-carbon | train |
b6960f8a5d5c1d9b8ae6ffadbb413af4c59243bf | diff --git a/src/selector_manager/view/ClassTagsView.js b/src/selector_manager/view/ClassTagsView.js
index <HASH>..<HASH> 100644
--- a/src/selector_manager/view/ClassTagsView.js
+++ b/src/selector_manager/view/ClassTagsView.js
@@ -82,9 +82,10 @@ export default Backbone.View.extend({
const selectors = target.get('classes');
const state = target.get('state');
// const device = em.getCurrentMedia();
- const rule = cssC.get(selectors, state);
const ruleComponent = cssC.getIdRule(target.getId(), { state });
const style = ruleComponent.getStyle();
+ const rule =
+ cssC.get(selectors, state) || cssC.add(selectors.models, state);
rule.addStyle(style);
ruleComponent.setStyle({});
em.trigger('component:toggle'); | Create CSS rule if doesn't exist | artf_grapesjs | train |
62515edb19e82de6a333f6d2099a5aeb03e68d40 | diff --git a/right_scraper_s3/lib/right_scraper_s3/scanners/s3.rb b/right_scraper_s3/lib/right_scraper_s3/scanners/s3.rb
index <HASH>..<HASH> 100644
--- a/right_scraper_s3/lib/right_scraper_s3/scanners/s3.rb
+++ b/right_scraper_s3/lib/right_scraper_s3/scanners/s3.rb
@@ -47,6 +47,7 @@ module RightScale
aws_secret_access_key=s3_secret,
:logger => Logger.new)
@bucket = s3.bucket(options.fetch(:s3_bucket))
+ raise "Need an actual, existing S3 bucket!" if @bucket.nil?
end
# Upon ending a scan for a cookbook, upload the cookbook
diff --git a/right_scraper_s3/spec/s3_upload_spec.rb b/right_scraper_s3/spec/s3_upload_spec.rb
index <HASH>..<HASH> 100644
--- a/right_scraper_s3/spec/s3_upload_spec.rb
+++ b/right_scraper_s3/spec/s3_upload_spec.rb
@@ -61,6 +61,42 @@ describe RightScale::Scanners::S3Upload do
ENV['AMAZON_ACCESS_KEY_ID'] && ENV['AMAZON_SECRET_ACCESS_KEY']
end
+ context "given a bucket that doesn't exist" do
+ before(:each) do
+ setup_download_repo
+ end
+
+ after(:each) do
+ delete_download_repo
+ end
+
+ before(:each) do
+ @repo = RightScale::Repository.from_hash(:display_name => 'test repo',
+ :repo_type => :download,
+ :url => "file:///#{@download_file}")
+ @s3 = RightAws::S3.new(aws_access_key_id=ENV['AMAZON_ACCESS_KEY_ID'],
+ aws_secret_access_key=ENV['AMAZON_SECRET_ACCESS_KEY'],
+ :logger => RightScale::Logger.new)
+ FileUtils.rm_rf(RightScale::Scrapers::ScraperBase.repo_dir(@repo_path, @repo))
+ end
+
+ it 'should raise an exception immediately' do
+ bucket_name = 'this-bucket-does-not-exist'
+ @s3.bucket(bucket_name).should be_nil
+ lambda {
+ @scraper = @scraperclass.new(@repo,
+ :scanners => [RightScale::Scanners::Metadata,
+ RightScale::Scanners::Manifest,
+ RightScale::Scanners::S3Upload],
+ :s3_key => ENV['AMAZON_ACCESS_KEY_ID'],
+ :s3_secret => ENV['AMAZON_SECRET_ACCESS_KEY'],
+ :s3_bucket => bucket_name,
+ :max_bytes => 1024**2,
+ :max_seconds => 20)
+ }.should raise_exception(/Need an actual, existing S3 bucket!/)
+ end
+ end
+
context 'given a download repository with the S3UploadScanner' do
before(:each) do
setup_download_repo
diff --git a/right_scraper_s3/spec/spec_helper.rb b/right_scraper_s3/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/right_scraper_s3/spec/spec_helper.rb
+++ b/right_scraper_s3/spec/spec_helper.rb
@@ -24,7 +24,7 @@
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib')))
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'right_scraper_base', 'spec', 'spec_helper'))
-require 'right_scraper_base'
+require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'right_scraper_base', 'lib', 'right_scraper_base'))
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'right_scraper_s3'))
# Massive hack to prevent "warning: peer certificate won't ..." blah | Make sure we warn when the bucket doesn't exist. | rightscale_right_scraper | train |
dfaa507699713e603255c31a0c860e6d1b855c37 | diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py
index <HASH>..<HASH> 100644
--- a/pandas/core/arrays/categorical.py
+++ b/pandas/core/arrays/categorical.py
@@ -26,11 +26,9 @@ from pandas.core.dtypes.common import (
is_dtype_equal,
is_extension_array_dtype,
is_integer_dtype,
- is_iterator,
is_list_like,
is_object_dtype,
is_scalar,
- is_sequence,
is_timedelta64_dtype,
needs_i8_conversion,
)
@@ -324,7 +322,7 @@ class Categorical(NDArrayBackedExtensionArray, PandasObject):
# of numpy
values = maybe_infer_to_datetimelike(values, convert_dates=True)
if not isinstance(values, np.ndarray):
- values = _convert_to_list_like(values)
+ values = com.convert_to_list_like(values)
# By convention, empty lists result in object dtype:
sanitize_dtype = np.dtype("O") if len(values) == 0 else None
@@ -2647,17 +2645,6 @@ def recode_for_categories(codes: np.ndarray, old_categories, new_categories):
return new_codes
-def _convert_to_list_like(list_like):
- if hasattr(list_like, "dtype"):
- return list_like
- if isinstance(list_like, list):
- return list_like
- if is_sequence(list_like) or isinstance(list_like, tuple) or is_iterator(list_like):
- return list(list_like)
-
- return [list_like]
-
-
def factorize_from_iterable(values):
"""
Factorize an input `values` into `categories` and `codes`. Preserves
diff --git a/pandas/core/common.py b/pandas/core/common.py
index <HASH>..<HASH> 100644
--- a/pandas/core/common.py
+++ b/pandas/core/common.py
@@ -4,17 +4,16 @@ Misc tools for implementing data structures
Note: pandas.core.common is *not* part of the public API.
"""
-import collections
-from collections import abc
+from collections import abc, defaultdict
from datetime import datetime, timedelta
from functools import partial
import inspect
-from typing import Any, Collection, Iterable, Union
+from typing import Any, Collection, Iterable, List, Union
import numpy as np
from pandas._libs import lib, tslibs
-from pandas._typing import T
+from pandas._typing import AnyArrayLike, Scalar, T
from pandas.compat.numpy import _np_version_under1p17
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
@@ -24,7 +23,12 @@ from pandas.core.dtypes.common import (
is_extension_array_dtype,
is_integer,
)
-from pandas.core.dtypes.generic import ABCIndex, ABCIndexClass, ABCSeries
+from pandas.core.dtypes.generic import (
+ ABCExtensionArray,
+ ABCIndex,
+ ABCIndexClass,
+ ABCSeries,
+)
from pandas.core.dtypes.inference import _iterable_not_string
from pandas.core.dtypes.missing import isna, isnull, notnull # noqa
@@ -367,12 +371,12 @@ def standardize_mapping(into):
Series.to_dict
"""
if not inspect.isclass(into):
- if isinstance(into, collections.defaultdict):
- return partial(collections.defaultdict, into.default_factory)
+ if isinstance(into, defaultdict):
+ return partial(defaultdict, into.default_factory)
into = type(into)
if not issubclass(into, abc.Mapping):
raise TypeError(f"unsupported type: {into}")
- elif into == collections.defaultdict:
+ elif into == defaultdict:
raise TypeError("to_dict() only accepts initialized defaultdicts")
return into
@@ -473,3 +477,18 @@ def get_rename_function(mapper):
f = mapper
return f
+
+
+def convert_to_list_like(
+ values: Union[Scalar, Iterable, AnyArrayLike]
+) -> Union[List, AnyArrayLike]:
+ """
+ Convert list-like or scalar input to list-like. List, numpy and pandas array-like
+ inputs are returned unmodified whereas others are converted to list.
+ """
+ if isinstance(values, (list, np.ndarray, ABCIndex, ABCSeries, ABCExtensionArray)):
+ return values
+ elif isinstance(values, abc.Iterable) and not isinstance(values, str):
+ return list(values)
+
+ return [values] | CLN: Move _convert_to_list_like to common (#<I>) | pandas-dev_pandas | train |
118c467c74e524e7c313db8ea82c3e6d212e4243 | diff --git a/bettercache/handlers.py b/bettercache/handlers.py
index <HASH>..<HASH> 100644
--- a/bettercache/handlers.py
+++ b/bettercache/handlers.py
@@ -12,6 +12,7 @@ class AsyncHandler(BaseHandler):
# async_middleware = smart_import(settings.ASYNC_MIDDLEWARE)
# middleware_blacklist = [smart_import(midd) for midd in settings.ASYNC_MIDDLEWARE_BLACKLIST]
# TODO: pull out the other middleware here
+ # TODO: Only pull out of process request except for ourself
def __call__(self, request):
self.load_middleware()
diff --git a/bettercache/middleware.py b/bettercache/middleware.py
index <HASH>..<HASH> 100644
--- a/bettercache/middleware.py
+++ b/bettercache/middleware.py
@@ -26,9 +26,9 @@ class BetterCacheMiddleware(CacheMixin):
return None # Don't bother checking the cache.
response, expired = self.get_cache(request)
+ request._cache_update_cache = True
if response is None:
- request._cache_update_cache = True
return None # No cache information available, need to rebuild.
# don't update right since we're just serving from cache
@@ -36,6 +36,9 @@ class BetterCacheMiddleware(CacheMixin):
# send off the task if we have to
if expired:
GeneratePage.apply_async(request)
+ else:
+ request._cache_update_cache = False
+
return response
def process_response(self, request, response):
@@ -46,7 +49,10 @@ class BetterCacheMiddleware(CacheMixin):
# We don't need to update the cache, just return.
return response
- response = patch_headers(response)
+ # TODO: now you can get here if you're serving from cache
+ response = self.patch_headers(response)
+ self.set_cache()#TODO
+
return response
diff --git a/bettercache/utils.py b/bettercache/utils.py
index <HASH>..<HASH> 100644
--- a/bettercache/utils.py
+++ b/bettercache/utils.py
@@ -6,6 +6,7 @@ from django.conf import settings
from django.utils.cache import get_cache_key, learn_cache_key, cc_delim_re, patch_cache_control, get_max_age
#TODO: what other codes can we cache redirects? 404s?
+# check httpspec
CACHABLE_STATUS = [200,]
class CachingMixin(object):
@@ -16,6 +17,7 @@ class CachingMixin(object):
vdict = get_header_dict(response, 'Vary')
try:
vdict.pop('Cookie')
+ # TODO: don't forget to set the cookie
except KeyError:
pass
@@ -57,15 +59,19 @@ class CachingMixin(object):
if get_max_age(response) == 0:
return False
#TODO: there are other conditions that should stop caching too
+ # check private, nocache look in the decorator
+ #TODO: check if this is from a cacheable place(in the request)
return True
def set_cache(self, request, response):
- # TODO: we need to use two timeouts here
+ # TODO: Do we want to honor timeouts set before here? NO WE SHOULDN"T
timeout = get_max_age(request)
- if not timeout < settings.CACHE_MIDDLEWARE_SECONDS:
+ if timeout >= settings.CACHE_MIDDLEWARE_SECONDS:
timeout = settings.BETTERCACHE_MAXAGE
+ # TODO: does this do the right thing with vary headers
cache_key = learn_cache_key(request, response, timeout, settings.CACHE_MIDDLEWARE_KEY_PREFIX)
#presumably this is to deal with requests with attr functions that won't pickle
+ # TODO: get now in here
if hasattr(response, 'render') and callable(response.render):
response.add_post_render_callback(lambda r: self.cache.set(cache_key, r, timeout))
else:
@@ -77,6 +83,7 @@ class CachingMixin(object):
if cache_key is None:
request._cache_update_cache = True
return None # No cache information available, need to rebuild.
+ # TODO: is a tuple
cached_response = self.cache.get(cache_key, None)
# if it wasn't found and we are looking for a HEAD, try looking just for that
if cached_response is None and request.method == 'HEAD': | [CMSPERF-<I>] TODOs from code review | ironfroggy_django-better-cache | train |
4c65ca1d157ca02c820b3cc987b17787bf9c4b7f | diff --git a/lib/App/index.js b/lib/App/index.js
index <HASH>..<HASH> 100644
--- a/lib/App/index.js
+++ b/lib/App/index.js
@@ -282,6 +282,10 @@ class App {
}
// validate `appJson.drivers[].platforms`
+ if (driver.platforms) {
+ console.warn(`Warning: drivers.${driver.id} doesn't have a 'platforms' property.`);
+ }
+
if (driver.platforms && appJson.platforms) {
if (driver.platforms.includes('local')) {
if (appJson.platforms.includes('local') === false) { | feat: warn if driver is missing platforms | athombv_node-homey-lib | train |
76196b44135b37a59fa76eabebbd1fd06dc2d4dd | diff --git a/README.rst b/README.rst
index <HASH>..<HASH> 100644
--- a/README.rst
+++ b/README.rst
@@ -285,7 +285,7 @@ HTTP endpoints:
Sets up an **HTTP endpoint for static content** available as ``GET`` / ``HEAD`` from the ``path`` on disk on the base regexp ``url``.
``@tomodachi.websocket(url)``
- Sets up a **websocket endpoint** on the regexp ``url``. The invoked function is called upon websocket connection and should return a two value tuple containing callables for a function receiving frames (first callable) and a function called on websocket close (second callable).
+ Sets up a **websocket endpoint** on the regexp ``url``. The invoked function is called upon websocket connection and should return a two value tuple containing callables for a function receiving frames (first callable) and a function called on websocket close (second callable). The passed arguments to the function beside the class object is first the ``websocket`` response connection which can be used to send frames to the client, and optionally also the ``request`` object.
``@tomodachi.http_error(status_code)``
A function which will be called if the **HTTP request would result in a 4XX** ``status_code``. You may use this for example to set up a custom handler on "404 Not Found" or "403 Forbidden" responses.
diff --git a/tests/services/http_service.py b/tests/services/http_service.py
index <HASH>..<HASH> 100644
--- a/tests/services/http_service.py
+++ b/tests/services/http_service.py
@@ -42,6 +42,7 @@ class HttpService(tomodachi.Service):
function_triggered = False
websocket_connected = False
websocket_received_data = None
+ websocket_header = None
@http('GET', r'/test/?')
async def test(self, request: web.Request) -> str:
@@ -166,6 +167,10 @@ class HttpService(tomodachi.Service):
async def websocket_simple(self, websocket: web.WebSocketResponse) -> None:
self.websocket_connected = True
+ @websocket(r'/websocket-header')
+ async def websocket_with_header(self, websocket: web.WebSocketResponse, request: web.Request) -> None:
+ self.websocket_header = request.headers.get('User-Agent')
+
@websocket(r'/websocket-data')
async def websocket_data(self, websocket: web.WebSocketResponse) -> Callable:
async def _receive(data: Union[str, bytes]) -> None:
diff --git a/tests/test_http_service.py b/tests/test_http_service.py
index <HASH>..<HASH> 100644
--- a/tests/test_http_service.py
+++ b/tests/test_http_service.py
@@ -281,6 +281,14 @@ def test_request_http_service(monkeypatch: Any, capsys: Any, loop: Any) -> None:
await ws.close()
assert instance.websocket_connected is True
+ assert instance.websocket_header is None
+ async with aiohttp.ClientSession(loop=loop) as client:
+ async with client.ws_connect('http://127.0.0.1:{}/websocket-header'.format(port)) as ws:
+ await ws.close()
+ assert instance.websocket_header is not None
+ assert 'Python' in instance.websocket_header
+ assert 'aiohttp' in instance.websocket_header
+
async with aiohttp.ClientSession(loop=loop) as client:
async with client.ws_connect('http://127.0.0.1:{}/websocket-data'.format(port)) as ws:
data = '9e2546ef-7fe1-4f94-a3fc-5dc85a771a17'
diff --git a/tomodachi/transport/http.py b/tomodachi/transport/http.py
index <HASH>..<HASH> 100644
--- a/tomodachi/transport/http.py
+++ b/tomodachi/transport/http.py
@@ -394,6 +394,13 @@ class HttpTransport(Invoker):
for k, v in result.groupdict().items():
kwargs[k] = v
+ if len(values.args) - (len(values.defaults) if values.defaults else 0) >= 3:
+ # If the function takes a third required argument the value will be filled with the request object
+ a = list(a)
+ a.append(request)
+ if 'request' in values.args and (len(values.args) - (len(values.defaults) if values.defaults else 0) < 3 or values.args[2] != 'request'):
+ kwargs['request'] = request
+
try:
routine = func(*(obj, websocket, *a), **merge_dicts(kwargs, kw))
callback_functions = (await routine) if isinstance(routine, Awaitable) else routine # type: Optional[Union[Tuple, Callable]] | Added optional third argument to websocket handler to pass on request object for headers parsing, etc. | kalaspuff_tomodachi | train |
5d73a75149ea4ae7ef4e358dce364ffb2c3e453a | diff --git a/bokeh/command/subcommand.py b/bokeh/command/subcommand.py
index <HASH>..<HASH> 100644
--- a/bokeh/command/subcommand.py
+++ b/bokeh/command/subcommand.py
@@ -2,7 +2,12 @@
line application.
'''
+from abc import ABCMeta, abstractmethod
+# TODO (bev) change this after bokeh.util.future is merged
+from six import add_metaclass
+
+@add_metaclass(ABCMeta)
class Subcommand(object):
''' Abstract base class for subcommands '''
@@ -14,11 +19,12 @@ class Subcommand(object):
'''
self.parser = parser
- def func(self, args):
+ @abstractmethod
+ def invoke(self, args):
''' Takes over main program flow to perform the subcommand.
Args:
args (seq) : command line arguments for the subcommand to parse
'''
- raise NotImplementedError("Implement func(args)")
\ No newline at end of file
+ pass
\ No newline at end of file | use abc module to make Subcommand a real abstract base class | bokeh_bokeh | train |
179252630d829e8d24d149db8fcc642309e5d987 | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -323,6 +323,7 @@ $A⋅B = $A->dotProduct($B); // same as innerProduct
$A⋅B = $A->innerProduct($B); // same as dotProduct
// Vector operations - return a Vector or Matrix
+$kA = $A->scalarMultiply(5);
$A⨂B = $A->outerProduct(new Vector([1, 2]));
$AxB = $A->crossProduct($B);
diff --git a/src/LinearAlgebra/Vector.php b/src/LinearAlgebra/Vector.php
index <HASH>..<HASH> 100644
--- a/src/LinearAlgebra/Vector.php
+++ b/src/LinearAlgebra/Vector.php
@@ -146,11 +146,25 @@ class Vector implements \Countable, \ArrayAccess, \JsonSerializable
/**************************************************************************
* VECTOR OPERATIONS - Return a Vector or Matrix
+ * - scalarMultiply
* - outerProduct
* - crossProduct
**************************************************************************/
/**
+ * Scalar multiplication (scale)
+ * kA = [k * A₀, k * A₁, k * A₂ ...]
+ *
+ * @param number $k Scale factor
+ *
+ * @return Vector
+ */
+ public function scalarMultiply($k)
+ {
+ return new Vector(Map\Single::multiply($this->A, $k));
+ }
+
+ /**
* Outer product (A⨂B)
* https://en.wikipedia.org/wiki/Outer_product
*
diff --git a/tests/LinearAlgebra/VectorTest.php b/tests/LinearAlgebra/VectorTest.php
index <HASH>..<HASH> 100644
--- a/tests/LinearAlgebra/VectorTest.php
+++ b/tests/LinearAlgebra/VectorTest.php
@@ -465,4 +465,63 @@ class VectorTest extends \PHPUnit_Framework_TestCase
$this->assertContains('ArrayAccess', $interfaces);
$this->assertContains('JsonSerializable', $interfaces);
}
+
+ /**
+ * @dataProvider dataProviderForScalarMultiply
+ */
+ public function testScalarMultiply(array $A, $k, array $R)
+ {
+ $A = new Vector($A);
+ $kA = $A->scalarMultiply($k);
+ $R = new Vector($R);
+
+ $this->assertEquals($R, $kA);
+ $this->assertEquals($R->getVector(), $kA->getVector());
+ }
+
+ public function dataProviderForScalarMultiply()
+ {
+ return [
+ [
+ [],
+ 2,
+ [],
+ ],
+ [
+ [1],
+ 2,
+ [2],
+ ],
+ [
+ [2, 3],
+ 2,
+ [4, 6],
+ ],
+ [
+ [1, 2, 3],
+ 2,
+ [2, 4, 6],
+ ],
+ [
+ [1, 2, 3, 4, 5],
+ 5,
+ [5, 10, 15, 20, 25],
+ ],
+ [
+ [1, 2, 3, 4, 5],
+ 0,
+ [0, 0, 0, 0, 0],
+ ],
+ [
+ [1, 2, 3, 4, 5],
+ -2,
+ [-2, -4, -6, -8, -10],
+ ],
+ [
+ [1, 2, 3, 4, 5],
+ 0.2,
+ [0.2, 0.4, 0.6, 0.8, 1],
+ ],
+ ];
+ }
} | Add Vector scalar multiplication. | markrogoyski_math-php | train |
763d1c2df5931bfe8f99cdb2367c20b6733036b0 | diff --git a/src/Event/DefaultEventTaggerService.php b/src/Event/DefaultEventTaggerService.php
index <HASH>..<HASH> 100644
--- a/src/Event/DefaultEventTaggerService.php
+++ b/src/Event/DefaultEventTaggerService.php
@@ -41,11 +41,11 @@ class DefaultEventTaggerService implements EventTaggerServiceInterface
public function tagEventsById($eventIds, $keyword)
{
if (!isset($keyword) || strlen($keyword) == 0) {
- throw new \Exception('invalid keyword');
+ throw new \InvalidArgumentException('invalid keyword');
}
if (!isset($eventIds) || count($eventIds) == 0) {
- throw new \Exception('no event Ids to tag');
+ throw new \InvalidArgumentException('no event Ids to tag');
}
$events = [];
diff --git a/test/Event/DefaultEventTaggerServiceTest.php b/test/Event/DefaultEventTaggerServiceTest.php
index <HASH>..<HASH> 100644
--- a/test/Event/DefaultEventTaggerServiceTest.php
+++ b/test/Event/DefaultEventTaggerServiceTest.php
@@ -93,7 +93,7 @@ class DefaultEventTaggerServiceTest extends \PHPUnit_Framework_TestCase
'event1'
];
- $this->setExpectedException('Exception', 'invalid keyword');
+ $this->setExpectedException('InvalidArgumentException', 'invalid keyword');
$this->commandBus->expects($this->never())
->method('dispatch');
@@ -129,7 +129,7 @@ class DefaultEventTaggerServiceTest extends \PHPUnit_Framework_TestCase
{
$eventIds = [];
- $this->setExpectedException('Exception', 'no event Ids to tag');
+ $this->setExpectedException('InvalidArgumentException', 'no event Ids to tag');
$this->commandBus->expects($this->never())
->method('dispatch'); | Throw a more precise type of Exception | cultuurnet_udb3-php | train |
4d3a7e194c09e77206c84aa407b3d9a1bb792326 | diff --git a/src/alternate-renderers.js b/src/alternate-renderers.js
index <HASH>..<HASH> 100644
--- a/src/alternate-renderers.js
+++ b/src/alternate-renderers.js
@@ -8,6 +8,7 @@ import { useSelector } from './hooks/useSelector'
import { useStore } from './hooks/useStore'
import { getBatch } from './utils/batch'
+import shallowEqual from './utils/shallowEqual'
// For other renderers besides ReactDOM and React Native, use the default noop batch function
const batch = getBatch()
@@ -20,5 +21,6 @@ export {
batch,
useDispatch,
useSelector,
- useStore
+ useStore,
+ shallowEqual
}
diff --git a/src/hooks/useSelector.js b/src/hooks/useSelector.js
index <HASH>..<HASH> 100644
--- a/src/hooks/useSelector.js
+++ b/src/hooks/useSelector.js
@@ -52,12 +52,20 @@ export function useSelector(selector, equalityFn = refEquality) {
])
const latestSubscriptionCallbackError = useRef()
- const latestSelector = useRef(selector)
+ const latestSelector = useRef()
+ const latestSelectedState = useRef()
- let selectedState = undefined
+ let selectedState
try {
- selectedState = selector(store.getState())
+ if (
+ selector !== latestSelector.current ||
+ latestSubscriptionCallbackError.current
+ ) {
+ selectedState = selector(store.getState())
+ } else {
+ selectedState = latestSelectedState.current
+ }
} catch (err) {
let errorMessage = `An error occured while selecting the store state: ${
err.message
@@ -72,8 +80,6 @@ export function useSelector(selector, equalityFn = refEquality) {
throw new Error(errorMessage)
}
- const latestSelectedState = useRef(selectedState)
-
useIsomorphicLayoutEffect(() => {
latestSelector.current = selector
latestSelectedState.current = selectedState
diff --git a/test/hooks/useSelector.spec.js b/test/hooks/useSelector.spec.js
index <HASH>..<HASH> 100644
--- a/test/hooks/useSelector.spec.js
+++ b/test/hooks/useSelector.spec.js
@@ -1,6 +1,6 @@
/*eslint-disable react/prop-types*/
-import React from 'react'
+import React, { useCallback, useReducer } from 'react'
import { createStore } from 'redux'
import { renderHook, act } from 'react-hooks-testing-library'
import * as rtl from 'react-testing-library'
@@ -51,6 +51,29 @@ describe('React', () => {
})
describe('lifeycle interactions', () => {
+ it('always uses the latest state', () => {
+ store = createStore(c => c + 1, -1)
+
+ const Comp = () => {
+ const selector = useCallback(c => c + 1, [])
+ const value = useSelector(selector)
+ renderedItems.push(value)
+ return <div />
+ }
+
+ rtl.render(
+ <ProviderMock store={store}>
+ <Comp />
+ </ProviderMock>
+ )
+
+ expect(renderedItems).toEqual([1])
+
+ store.dispatch({ type: '' })
+
+ expect(renderedItems).toEqual([1, 2])
+ })
+
it('subscribes to the store synchronously', () => {
let rootSubscription
@@ -183,6 +206,39 @@ describe('React', () => {
})
})
+ it('uses the latest selector', () => {
+ let selectorId = 0
+ let forceRender
+
+ const Comp = () => {
+ const [, f] = useReducer(c => c + 1, 0)
+ forceRender = f
+ const renderedSelectorId = selectorId++
+ const value = useSelector(() => renderedSelectorId)
+ renderedItems.push(value)
+ return <div />
+ }
+
+ rtl.render(
+ <ProviderMock store={store}>
+ <Comp />
+ </ProviderMock>
+ )
+
+ expect(renderedItems).toEqual([0])
+
+ rtl.act(forceRender)
+ expect(renderedItems).toEqual([0, 1])
+
+ rtl.act(() => {
+ store.dispatch({ type: '' })
+ })
+ expect(renderedItems).toEqual([0, 1])
+
+ rtl.act(forceRender)
+ expect(renderedItems).toEqual([0, 1, 2])
+ })
+
describe('edge cases', () => {
it('ignores transient errors in selector (e.g. due to stale props)', () => {
const spy = jest.spyOn(console, 'error').mockImplementation(() => {}) | Avoid unnecessary selector evaluations (#<I>)
* Avoid unnecessary selector evaluations
* Clean up state assignment logic
* Add missing shallowEqual export | reduxjs_react-redux | train |
4be757d073c481b87c69c3765b42cfc39b6d0bfd | diff --git a/scanpy/tools/_phenograph.py b/scanpy/tools/_phenograph.py
index <HASH>..<HASH> 100644
--- a/scanpy/tools/_phenograph.py
+++ b/scanpy/tools/_phenograph.py
@@ -77,7 +77,7 @@ def phenograph( adata,
>>> result = sce.tl.phenograph(adata.obsm['X_pca'], k = 30)
- Imbed the phenograph result into adata as a *categorical* variable (this helps in plotting):
+ Embed the phenograph result into adata as a *categorical* variable (this helps in plotting):
>>> adata.obs['pheno'] = pd.Categorical(result[0]) | Update _phenograph.py | theislab_scanpy | train |
6d846449922b854fe3929e0a81b389c232c210c8 | diff --git a/src/Worker.php b/src/Worker.php
index <HASH>..<HASH> 100644
--- a/src/Worker.php
+++ b/src/Worker.php
@@ -120,6 +120,7 @@ class Worker
]);
$this->updateJob($this->current_job, JobInterface::STATUS_TIMEOUT);
+ $this->cancelChildJobs($this->current_job);
$job = $this->current_job;
if (0 !== $job['options']['retry']) {
@@ -262,6 +263,7 @@ class Worker
]);
$this->updateJob($this->current_job, JobInterface::STATUS_CANCELED);
+ $this->cancelChildJobs(($this->current_job));
$options = $this->current_job['options'];
$options['at'] = 0;
@@ -410,6 +412,44 @@ class Worker
$session->commitTransaction();
+ if ($result->getModifiedCount() >= 1) {
+ $this->logger->debug('updated job ['.$job['_id'].'] with status ['.$status.']', [
+ 'category' => get_class($this),
+ 'pm' => $this->process,
+ ]);
+ }
+
+ return $result->isAcknowledged();
+ }
+
+ /**
+ * Cancel child jobs.
+ */
+ protected function cancelChildJobs(array $job): bool
+ {
+ $session = $this->sessionHandler->getSession();
+ $session->startTransaction($this->sessionHandler->getOptions());
+
+ $result = $this->db->{$this->scheduler->getJobQueue()}->updateMany([
+ 'status' => [
+ '$ne' => JobInterface::STATUS_DONE,
+ ],
+ 'data.parent' => $job['_id'],
+ ], [
+ '$set' => [
+ 'status' => JobInterface::STATUS_CANCELED,
+ ],
+ ]);
+
+ $session->commitTransaction();
+
+ if ($result->getModifiedCount() >= 1) {
+ $this->logger->debug('canceled ['.$result->getModifiedCount().'] child jobs for parent job ['.$job['_id'].']', [
+ 'category' => get_class($this),
+ 'pm' => $this->process,
+ ]);
+ }
+
return $result->isAcknowledged();
} | #<I> cancel child job when parent is canceled | gyselroth_mongodb-php-task-scheduler | train |
18113f1afef5ed4e735057dbcaeac0911cb53551 | diff --git a/src/histogram.js b/src/histogram.js
index <HASH>..<HASH> 100644
--- a/src/histogram.js
+++ b/src/histogram.js
@@ -30,7 +30,7 @@ export default function() {
// Convert number of thresholds into uniform thresholds.
if (!Array.isArray(tz)) {
tz = tickStep(x0, x1, tz);
- tz = range(Math.ceil(x0 / tz) * tz, Math.floor(x1 / tz) * tz, tz); // exclusive
+ tz = range(Math.ceil(x0 / tz) * tz, x1, tz); // exclusive
}
// Remove any thresholds outside the domain.
diff --git a/test/histogram-test.js b/test/histogram-test.js
index <HASH>..<HASH> 100644
--- a/test/histogram-test.js
+++ b/test/histogram-test.js
@@ -122,6 +122,18 @@ tape("histogram.thresholds(function) sets the bin thresholds accessor", function
test.end();
});
+tape("histogram()() returns bins whose rightmost bin is not too wide", function(test) {
+ var h = arrays.histogram();
+ test.deepEqual(h([9.8, 10, 11, 12, 13, 13.2]), [
+ bin([9.8], 9.8, 10),
+ bin([10], 10, 11),
+ bin([11], 11, 12),
+ bin([12], 12, 13),
+ bin([13, 13.2], 13, 13.2),
+ ]);
+ test.end();
+});
+
function bin(bin, x0, x1) {
bin.x0 = x0;
bin.x1 = x1; | Fix that the width of rightmost bin by default thresholds was too wide. | d3_d3-array | train |
b0708dbb0f246a6841510e04c08a324db195482f | diff --git a/luigi/contrib/hadoop.py b/luigi/contrib/hadoop.py
index <HASH>..<HASH> 100644
--- a/luigi/contrib/hadoop.py
+++ b/luigi/contrib/hadoop.py
@@ -596,7 +596,6 @@ class LocalJobRunner(JobRunner):
map_output.close()
return
- job.init_mapper()
# run job now...
map_output = StringIO()
job.run_mapper(map_input, map_output)
@@ -611,7 +610,6 @@ class LocalJobRunner(JobRunner):
combine_output.seek(0)
reduce_input = self.group(combine_output)
- job.init_reducer()
reduce_output = job.output().open('w')
job.run_reducer(reduce_input, reduce_output)
reduce_output.close() | Remove redundant init_mapper/init_reducer calls in LocalJobRunner | spotify_luigi | train |
fd7b77f765e34734e29dc4085a042e401ecaf8f6 | diff --git a/src/Pho/Kernel/Kernel.php b/src/Pho/Kernel/Kernel.php
index <HASH>..<HASH> 100644
--- a/src/Pho/Kernel/Kernel.php
+++ b/src/Pho/Kernel/Kernel.php
@@ -176,6 +176,8 @@ class Kernel extends Init
/**
* Imports from a given Pho backup file
+ *
+ * @see Kernel::export()
*
* @param string $blob
*
@@ -186,7 +188,7 @@ class Kernel extends Init
if(!$this->is_running) {
throw new Exceptions\KernelNotRunningException();
}
- $import = json_decode($blob, true);
+ $import = unserialize($blob);
foreach($import as $key=>$value) {
$this->database()->restore($key, 0, $value);
}
@@ -227,6 +229,11 @@ class Kernel extends Init
/**
* Exports in Pho backup file format
+ *
+ * There was a problem with json_encode in large files
+ * hence switched to php serialize format instead.
+ *
+ * @see Kernel::import
*
* @return string
*/
@@ -241,7 +248,7 @@ class Kernel extends Init
// if($key!="index") // skip list
$return[$key] = $this->database()->dump($key);
}
- return json_encode($return);
+ return serialize($return);
}
-}
\ No newline at end of file
+} | switched to php serialize for import/export
otherwise it fails with large files | phonetworks_pho-microkernel | train |
3ab9da999ac53dc7c8dea7a8a9be4802c9f16042 | diff --git a/pypuppetdb/api/v3.py b/pypuppetdb/api/v3.py
index <HASH>..<HASH> 100644
--- a/pypuppetdb/api/v3.py
+++ b/pypuppetdb/api/v3.py
@@ -78,6 +78,8 @@ class API(BaseAPI):
node['events'] = status = status[0]
if status['successes'] > 0:
node['status'] = 'changed'
+ if status['noops'] > 0:
+ node['status'] = 'noop'
if status['failures'] > 0:
node['status'] = 'failed'
else: | new node['status'] - 'noop' (api v3)
set node['status'] to noop when noops are present in event-counts of latest
report | voxpupuli_pypuppetdb | train |
652771ffe48241c8ea74aa0bc7837c882742bfb8 | diff --git a/code/forms/EventRegisterTicketsStep.php b/code/forms/EventRegisterTicketsStep.php
index <HASH>..<HASH> 100644
--- a/code/forms/EventRegisterTicketsStep.php
+++ b/code/forms/EventRegisterTicketsStep.php
@@ -90,7 +90,7 @@ class EventRegisterTicketsStep extends MultiFormStep {
$form->addErrorMessage(
'Tickets',
'Please only enter numerical amounts for ticket quantities.',
- 'bad');
+ 'required');
return false;
}
@@ -98,7 +98,7 @@ class EventRegisterTicketsStep extends MultiFormStep {
if (!$ticket = $ticket->First()) {
$form->addErrorMessage(
- 'Tickets', 'An invalid ticket ID was entered.', 'bad');
+ 'Tickets', 'An invalid ticket ID was entered.', 'required');
return false;
}
@@ -109,7 +109,7 @@ class EventRegisterTicketsStep extends MultiFormStep {
$form->addErrorMessage(
'Tickets',
sprintf('%s is currently not available.', $ticket->Title),
- 'bad');
+ 'required');
return false;
}
@@ -117,21 +117,21 @@ class EventRegisterTicketsStep extends MultiFormStep {
$form->addErrorMessage(
'Tickets',
sprintf('There are only %d of "%s" available.', $avail, $ticket->Title),
- 'bad');
+ 'required');
return false;
}
if ($ticket->MinTickets && $quantity < $ticket->MinTickets) {
$form->addErrorMessage('Tickets',sprintf(
'You must purchase at least %d of "%s".',
- $ticket->MinTickets, $ticket->Title), 'bad');
+ $ticket->MinTickets, $ticket->Title), 'required');
return false;
}
if ($ticket->MaxTickets && $quantity > $ticket->MaxTickets) {
$form->addErrorMessage('Tickets', sprintf(
'You can only purchase at most %d of "%s".',
- $ticket->MaxTickets, $ticket->Title), 'bad');
+ $ticket->MaxTickets, $ticket->Title), 'required');
return false;
}
@@ -140,7 +140,7 @@ class EventRegisterTicketsStep extends MultiFormStep {
if (!$has) {
$form->addErrorMessage(
- 'Tickets', 'Please select at least one ticket to purchase.', 'bad');
+ 'Tickets', 'Please select at least one ticket to purchase.', 'required');
return false;
} | Updated the tickets step error message type to be required rather than bad. | registripe_registripe-core | train |
a64f60e1f0bd12006cdcdf434ee8b2f774c9062a | diff --git a/ohc-core/src/main/java/org/caffinitas/ohc/chunked/Hasher.java b/ohc-core/src/main/java/org/caffinitas/ohc/chunked/Hasher.java
index <HASH>..<HASH> 100644
--- a/ohc-core/src/main/java/org/caffinitas/ohc/chunked/Hasher.java
+++ b/ohc-core/src/main/java/org/caffinitas/ohc/chunked/Hasher.java
@@ -15,6 +15,7 @@
*/
package org.caffinitas.ohc.chunked;
+import java.lang.reflect.InvocationTargetException;
import java.nio.ByteBuffer;
import org.caffinitas.ohc.HashAlgorithm;
@@ -26,18 +27,18 @@ abstract class Hasher
String cls = forAlg(hashAlgorithm);
try
{
- return (Hasher) Class.forName(cls).newInstance();
+ return (Hasher) Class.forName(cls).getDeclaredConstructor().newInstance();
}
- catch (ClassNotFoundException e)
+ catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException e)
{
if (hashAlgorithm == HashAlgorithm.XX)
{
cls = forAlg(HashAlgorithm.CRC32C);
try
{
- return (Hasher) Class.forName(cls).newInstance();
+ return (Hasher) Class.forName(cls).getDeclaredConstructor().newInstance();
}
- catch (InstantiationException | ClassNotFoundException | IllegalAccessException e1)
+ catch (InstantiationException | ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e1)
{
throw new RuntimeException(e1);
}
@@ -53,7 +54,7 @@ abstract class Hasher
private static String forAlg(HashAlgorithm hashAlgorithm)
{
return Hasher.class.getName().substring(0, Hasher.class.getName().lastIndexOf('.') + 1)
- + hashAlgorithm.name().substring(0, 1)
+ + hashAlgorithm.name().charAt(0)
+ hashAlgorithm.name().substring(1).toLowerCase()
+ "Hash";
}
diff --git a/ohc-core/src/main/java/org/caffinitas/ohc/linked/Hasher.java b/ohc-core/src/main/java/org/caffinitas/ohc/linked/Hasher.java
index <HASH>..<HASH> 100644
--- a/ohc-core/src/main/java/org/caffinitas/ohc/linked/Hasher.java
+++ b/ohc-core/src/main/java/org/caffinitas/ohc/linked/Hasher.java
@@ -17,6 +17,8 @@ package org.caffinitas.ohc.linked;
import org.caffinitas.ohc.HashAlgorithm;
+import java.lang.reflect.InvocationTargetException;
+
abstract class Hasher
{
static Hasher create(HashAlgorithm hashAlgorithm)
@@ -24,18 +26,18 @@ abstract class Hasher
String cls = forAlg(hashAlgorithm);
try
{
- return (Hasher) Class.forName(cls).newInstance();
+ return (Hasher) Class.forName(cls).getDeclaredConstructor().newInstance();
}
- catch (ClassNotFoundException e)
+ catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException e)
{
if (hashAlgorithm == HashAlgorithm.XX)
{
cls = forAlg(HashAlgorithm.CRC32);
try
{
- return (Hasher) Class.forName(cls).newInstance();
+ return (Hasher) Class.forName(cls).getDeclaredConstructor().newInstance();
}
- catch (InstantiationException | ClassNotFoundException | IllegalAccessException e1)
+ catch (InstantiationException | ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e1)
{
throw new RuntimeException(e1);
}
@@ -51,7 +53,7 @@ abstract class Hasher
private static String forAlg(HashAlgorithm hashAlgorithm)
{
return Hasher.class.getName().substring(0, Hasher.class.getName().lastIndexOf('.') + 1)
- + hashAlgorithm.name().substring(0, 1)
+ + hashAlgorithm.name().charAt(0)
+ hashAlgorithm.name().substring(1).toLowerCase()
+ "Hash";
} | Fix minor code issues in Hasher.java | snazy_ohc | train |
0579fa10cb6c0e8cf141ce1b6093d7d648258fac | diff --git a/bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/windup/DisplayHelpCommand.java b/bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/windup/DisplayHelpCommand.java
index <HASH>..<HASH> 100644
--- a/bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/windup/DisplayHelpCommand.java
+++ b/bootstrap/src/main/java/org/jboss/windup/bootstrap/commands/windup/DisplayHelpCommand.java
@@ -45,6 +45,9 @@ public class DisplayHelpCommand implements Command
sb.append(System.lineSeparator()).append(" Forge Options:").append(System.lineSeparator());
+ sb.append("-b, --batchMode").append(System.lineSeparator());
+ sb.append("\t run Forge in batch mode and does not prompt for confirmation (exits immediately after running) ").append(System.lineSeparator());
+
sb.append("-i, --install GROUP_ID:ARTIFACT_ID[:VERSION]").append(System.lineSeparator());
sb.append("\t install the required addons and exit. ex: `"+Util.WINDUP_CLI_NAME+" -i core-addon-x` or `"+Util.WINDUP_CLI_NAME+" -i org.example.addon:example:1.0.0` ").append(System.lineSeparator());
@@ -60,9 +63,6 @@ public class DisplayHelpCommand implements Command
sb.append("-m, --immutableAddonDir DIR").append(System.lineSeparator());
sb.append("\t add the given directory for use as a custom immutable addon repository (read only) ").append(System.lineSeparator());
- sb.append("-b, --batchMode").append(System.lineSeparator());
- sb.append("\t run Forge in batch mode and does not prompt for confirmation (exits immediately after running) ").append(System.lineSeparator());
-
sb.append("-d, --debug").append(System.lineSeparator());
sb.append("\t run Forge in debug mode (wait on port 8000 for a debugger to attach) ").append(System.lineSeparator());
diff --git a/exec/api/src/main/java/org/jboss/windup/exec/configuration/WindupConfiguration.java b/exec/api/src/main/java/org/jboss/windup/exec/configuration/WindupConfiguration.java
index <HASH>..<HASH> 100644
--- a/exec/api/src/main/java/org/jboss/windup/exec/configuration/WindupConfiguration.java
+++ b/exec/api/src/main/java/org/jboss/windup/exec/configuration/WindupConfiguration.java
@@ -170,7 +170,22 @@ public class WindupConfiguration
@Override
public int compare(ConfigurationOption o1, ConfigurationOption o2)
{
- return o2.getPriority() - o1.getPriority();
+ // if the 1st is required and...
+ if (o1.isRequired())
+ {
+ // the 2nd isn't, the 1st is "before" than the 2nd
+ if (!o2.isRequired()) return -1;
+ // otherwise if also the 2nd is required, then order is priority-based
+ else return o2.getPriority() - o1.getPriority();
+ }
+ // if the 1st is not required and...
+ else
+ {
+ // the 2nd is, the 1st is "after" than the 2nd
+ if (o2.isRequired()) return 1;
+ // otherwise also the 2nd isn't and order is priority-based
+ else return o2.getPriority() - o1.getPriority();
+ }
}
});
return results;
diff --git a/exec/api/src/main/java/org/jboss/windup/exec/configuration/options/OverwriteOption.java b/exec/api/src/main/java/org/jboss/windup/exec/configuration/options/OverwriteOption.java
index <HASH>..<HASH> 100644
--- a/exec/api/src/main/java/org/jboss/windup/exec/configuration/options/OverwriteOption.java
+++ b/exec/api/src/main/java/org/jboss/windup/exec/configuration/options/OverwriteOption.java
@@ -55,4 +55,10 @@ public class OverwriteOption extends AbstractConfigurationOption
{
return ValidationResult.SUCCESS;
}
+
+ @Override
+ public int getPriority()
+ {
+ return 8500;
+ }
} | WINDUP-<I> CLI to describe what parameters are required: reordering | windup_windup | train |
d2f10c60fbbac263f668665bd59c74443a8f8e4e | diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Changelog
* added `JsonVersioner` and implementations `VersionFieldVersioner` and
`SchemaUriVersioner`
* added support for `$ref` to external schema
+ * added support for validation against `$schema` property
* 1.2.2 (2016-01-14)
diff --git a/src/JsonValidator.php b/src/JsonValidator.php
index <HASH>..<HASH> 100644
--- a/src/JsonValidator.php
+++ b/src/JsonValidator.php
@@ -12,6 +12,7 @@
namespace Webmozart\Json;
use JsonSchema\Exception\InvalidArgumentException;
+use JsonSchema\Exception\ResourceNotFoundException;
use JsonSchema\RefResolver;
use JsonSchema\Uri\UriRetriever;
use JsonSchema\Validator;
@@ -68,20 +69,32 @@ class JsonValidator
* The schema may be passed as file path or as object returned from
* `json_decode($schemaFile)`.
*
- * @param mixed $data The decoded JSON data.
- * @param string|object $schema The schema file or object.
+ * @param mixed $data The decoded JSON data.
+ * @param string|object|null $schema The schema file or object. If `null`,
+ * the validator will look for a `$schema`
+ * property.
*
* @return string[] The errors found during validation. Returns an empty
* array if no errors were found.
*
* @throws InvalidSchemaException If the schema is invalid.
*/
- public function validate($data, $schema)
+ public function validate($data, $schema = null)
{
+ if (null === $schema && isset($data->{'$schema'})) {
+ $schema = $data->{'$schema'};
+ }
+
if (is_string($schema)) {
$schema = $this->loadSchema($schema);
- } else {
+ } elseif (is_object($schema)) {
$this->assertSchemaValid($schema);
+ } else {
+ throw new InvalidSchemaException(sprintf(
+ 'The schema must be given as string, object or in the "$schema" '.
+ 'property of the JSON data. Got: %s',
+ is_object($schema) ? get_class($schema) : gettype($schema)
+ ));
}
$this->validator->reset();
@@ -129,26 +142,10 @@ class JsonValidator
implode("\n", $errors)
));
}
-
- // not caught by justinrainbow/json-schema
- if (!is_object($schema)) {
- throw new InvalidSchemaException(sprintf(
- 'The schema must be an object. Got: %s',
- $schema,
- gettype($schema)
- ));
- }
}
private function loadSchema($file)
{
- if (!file_exists($file)) {
- throw new InvalidSchemaException(sprintf(
- 'The schema file %s does not exist.',
- $file
- ));
- }
-
// Retrieve schema and cache in UriRetriever
$file = Path::canonicalize($file);
@@ -157,7 +154,14 @@ class JsonValidator
$file = 'file://'.$file;
}
- $schema = $this->uriRetriever->retrieve($file);
+ try {
+ $schema = $this->uriRetriever->retrieve($file);
+ } catch (ResourceNotFoundException $e) {
+ throw new InvalidSchemaException(sprintf(
+ 'The schema %s does not exist.',
+ $file
+ ), 0, $e);
+ }
// Resolve references to other schemas
$resolver = new RefResolver($this->uriRetriever);
diff --git a/tests/JsonValidatorTest.php b/tests/JsonValidatorTest.php
index <HASH>..<HASH> 100644
--- a/tests/JsonValidatorTest.php
+++ b/tests/JsonValidatorTest.php
@@ -74,6 +74,23 @@ class JsonValidatorTest extends \PHPUnit_Framework_TestCase
$this->assertCount(0, $errors);
}
+ public function testValidateWithSchemaField()
+ {
+ $uriRetriever = new UriRetriever();
+ $uriRetriever->setUriRetriever(new PredefinedArray(array(
+ 'http://webmozart.io/fixtures/schema' => file_get_contents(__DIR__.'/Fixtures/schema.json'),
+ )));
+
+ $this->validator = new JsonValidator(null, $uriRetriever);
+
+ $errors = $this->validator->validate((object) array(
+ '$schema' => 'http://webmozart.io/fixtures/schema',
+ 'name' => 'Bernhard',
+ ));
+
+ $this->assertCount(0, $errors);
+ }
+
public function testValidateWithReferences()
{
$errors = $this->validator->validate(
@@ -209,4 +226,25 @@ class JsonValidatorTest extends \PHPUnit_Framework_TestCase
(object) array('type' => 12345)
);
}
+
+ /**
+ * @expectedException \Webmozart\Json\InvalidSchemaException
+ */
+ public function testValidateFailsIfMissingSchema()
+ {
+ $this->validator->validate(
+ (object) array('name' => 'Bernhard')
+ );
+ }
+
+ /**
+ * @expectedException \Webmozart\Json\InvalidSchemaException
+ */
+ public function testValidateFailsIfInvalidSchemaType()
+ {
+ $this->validator->validate(
+ (object) array('name' => 'Bernhard'),
+ 1234
+ );
+ }
} | Added support for validation against `$schema` property | webmozart_json | train |
8fe14fc8cb3f59b00b6ab99063866a8da213ef54 | diff --git a/resource_aws_elastic_beanstalk_environment.go b/resource_aws_elastic_beanstalk_environment.go
index <HASH>..<HASH> 100644
--- a/resource_aws_elastic_beanstalk_environment.go
+++ b/resource_aws_elastic_beanstalk_environment.go
@@ -249,7 +249,7 @@ func resourceAwsElasticBeanstalkEnvironmentCreate(d *schema.ResourceData, meta i
Refresh: environmentStateRefreshFunc(conn, d.Id()),
Timeout: waitForReadyTimeOut,
Delay: 10 * time.Second,
- MinTimeout: 3 * time.Second,
+ MinTimeout: 20 * time.Second,
}
_, err = stateConf.WaitForState()
@@ -321,7 +321,7 @@ func resourceAwsElasticBeanstalkEnvironmentUpdate(d *schema.ResourceData, meta i
Refresh: environmentStateRefreshFunc(conn, d.Id()),
Timeout: waitForReadyTimeOut,
Delay: 10 * time.Second,
- MinTimeout: 3 * time.Second,
+ MinTimeout: 20 * time.Second,
}
_, err = stateConf.WaitForState()
@@ -567,7 +567,7 @@ func resourceAwsElasticBeanstalkEnvironmentDelete(d *schema.ResourceData, meta i
Refresh: environmentStateRefreshFunc(conn, d.Id()),
Timeout: waitForReadyTimeOut,
Delay: 10 * time.Second,
- MinTimeout: 3 * time.Second,
+ MinTimeout: 20 * time.Second,
}
_, err = stateConf.WaitForState() | provider/aws: Beanstalk environments, bump the minimum timeout between API calls | terraform-providers_terraform-provider-aws | train |
04f73eabd448500d4bcc769a597f1ea93be1a0e1 | diff --git a/src/ipcalc.py b/src/ipcalc.py
index <HASH>..<HASH> 100644
--- a/src/ipcalc.py
+++ b/src/ipcalc.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-# pep8-ignore: E501
+# pep8-ignore: E501, E241
'''
====================================
@@ -267,10 +267,10 @@ class IP(object):
# No :: in address
if not '' in hx:
raise ValueError('%s: IPv6 address invalid: '
- 'compressed format malformed' % dq)
+ 'compressed format malformed' % dq)
elif not (dq.startswith('::') or dq.endswith('::')) and len([x for x in hx if x == '']) > 1:
raise ValueError('%s: IPv6 address invalid: '
- 'compressed format malformed' % dq)
+ 'compressed format malformed' % dq)
ix = hx.index('')
px = len(hx[ix + 1:])
for x in xrange(ix + px + 1, 8):
@@ -279,7 +279,7 @@ class IP(object):
pass
elif '' in hx:
raise ValueError('%s: IPv6 address invalid: '
- 'compressed format detected in full notation' % dq())
+ 'compressed format detected in full notation' % dq())
ip = ''
hx = [x == '' and '0' or x for x in hx]
for h in hx:
@@ -287,7 +287,7 @@ class IP(object):
h = '%04x' % int(h, 16)
if not 0 <= int(h, 16) <= 0xffff:
raise ValueError('%r: IPv6 address invalid: '
- 'hexlets should be between 0x0000 and 0xffff' % dq)
+ 'hexlets should be between 0x0000 and 0xffff' % dq)
ip += h
self.v = 6
return long(ip, 16)
@@ -302,11 +302,11 @@ class IP(object):
q.reverse()
if len(q) > 4:
raise ValueError('%s: IPv4 address invalid: '
- 'more than 4 bytes' % dq)
+ 'more than 4 bytes' % dq)
for x in q:
if not 0 <= int(x) <= 255:
raise ValueError('%s: IPv4 address invalid: '
- 'bytes should be between 0 and 255' % dq)
+ 'bytes should be between 0 and 255' % dq)
while len(q) < 4:
q.insert(1, '0')
self.v = 4
@@ -393,7 +393,7 @@ class IP(object):
return IP((long(self) - 0x20020000000000000000000000000000L) >> 80, version=4)
else:
return ValueError('%s: IPv6 address is not IPv4 compatible or mapped, '
- 'nor an 6-to-4 IP' % self.dq)
+ 'nor an 6-to-4 IP' % self.dq)
@classmethod
def from_bin(cls, value): | Some small PEP8 style fixes - Line under indention | tehmaze_ipcalc | train |
df54dd233a991b8c7e3cd244dfac13dc7bf8e82c | diff --git a/acme/commons.go b/acme/commons.go
index <HASH>..<HASH> 100644
--- a/acme/commons.go
+++ b/acme/commons.go
@@ -7,16 +7,33 @@ import (
"time"
)
-// Challenge statuses.
-// https://tools.ietf.org/html/rfc8555#section-7.1.6
+// ACME status values of Account, Order, Authorization and Challenge objects.
+// See https://tools.ietf.org/html/rfc8555#section-7.1.6 for details.
const (
- StatusPending = "pending"
- StatusInvalid = "invalid"
- StatusValid = "valid"
- StatusProcessing = "processing"
StatusDeactivated = "deactivated"
StatusExpired = "expired"
+ StatusInvalid = "invalid"
+ StatusPending = "pending"
+ StatusProcessing = "processing"
+ StatusReady = "ready"
StatusRevoked = "revoked"
+ StatusUnknown = "unknown"
+ StatusValid = "valid"
+)
+
+// CRL reason codes as defined in RFC 5280.
+// https://datatracker.ietf.org/doc/html/rfc5280#section-5.3.1
+const (
+ CRLReasonUnspecified uint = 0
+ CRLReasonKeyCompromise uint = 1
+ CRLReasonCACompromise uint = 2
+ CRLReasonAffiliationChanged uint = 3
+ CRLReasonSuperseded uint = 4
+ CRLReasonCessationOfOperation uint = 5
+ CRLReasonCertificateHold uint = 6
+ CRLReasonRemoveFromCRL uint = 8
+ CRLReasonPrivilegeWithdrawn uint = 9
+ CRLReasonAACompromise uint = 10
)
// Directory the ACME directory object.
diff --git a/certificate/certificates.go b/certificate/certificates.go
index <HASH>..<HASH> 100644
--- a/certificate/certificates.go
+++ b/certificate/certificates.go
@@ -365,6 +365,11 @@ func (c *Certifier) checkResponse(order acme.ExtendedOrder, certRes *Resource, b
// Revoke takes a PEM encoded certificate or bundle and tries to revoke it at the CA.
func (c *Certifier) Revoke(cert []byte) error {
+ return c.RevokeWithReason(cert, nil)
+}
+
+// RevokeWithReason takes a PEM encoded certificate or bundle and tries to revoke it at the CA.
+func (c *Certifier) RevokeWithReason(cert []byte, reason *uint) error {
certificates, err := certcrypto.ParsePEMBundle(cert)
if err != nil {
return err
@@ -377,6 +382,7 @@ func (c *Certifier) Revoke(cert []byte) error {
revokeMsg := acme.RevokeCertMessage{
Certificate: base64.RawURLEncoding.EncodeToString(x509Cert.Raw),
+ Reason: reason,
}
return c.core.Certificates.Revoke(revokeMsg)
diff --git a/cmd/cmd_revoke.go b/cmd/cmd_revoke.go
index <HASH>..<HASH> 100644
--- a/cmd/cmd_revoke.go
+++ b/cmd/cmd_revoke.go
@@ -1,6 +1,7 @@
package cmd
import (
+ "github.com/go-acme/lego/v4/acme"
"github.com/go-acme/lego/v4/log"
"github.com/urfave/cli"
)
@@ -15,6 +16,11 @@ func createRevoke() cli.Command {
Name: "keep, k",
Usage: "Keep the certificates after the revocation instead of archiving them.",
},
+ cli.UintFlag{
+ Name: "reason",
+ Usage: "Identifies the reason for the certificate revocation. See https://tools.ietf.org/html/rfc5280#section-5.3.1. 0(unspecified),1(keyCompromise),2(cACompromise),3(affiliationChanged),4(superseded),5(cessationOfOperation),6(certificateHold),8(removeFromCRL),9(privilegeWithdrawn),10(aACompromise)",
+ Value: acme.CRLReasonUnspecified,
+ },
},
}
}
@@ -37,7 +43,9 @@ func revoke(ctx *cli.Context) error {
log.Fatalf("Error while revoking the certificate for domain %s\n\t%v", domain, err)
}
- err = client.Certificate.Revoke(certBytes)
+ reason := ctx.Uint("reason")
+
+ err = client.Certificate.RevokeWithReason(certBytes, &reason)
if err != nil {
log.Fatalf("Error while revoking the certificate for domain %s\n\t%v", domain, err)
} | feat: Allows defining the reason for the certificate revocation (#<I>) | go-acme_lego | train |
e234c183cc40df43da997fa1eeccd847a65cedd7 | diff --git a/mmcv/ops/border_align.py b/mmcv/ops/border_align.py
index <HASH>..<HASH> 100644
--- a/mmcv/ops/border_align.py
+++ b/mmcv/ops/border_align.py
@@ -85,11 +85,12 @@ class BorderAlign(nn.Module):
(e.g. top, bottom, left, right).
"""
- def __init__(self, pool_size):
+ def __init__(self, pool_size: int):
super().__init__()
self.pool_size = pool_size
- def forward(self, input, boxes):
+ def forward(self, input: torch.Tensor,
+ boxes: torch.Tensor) -> torch.Tensor:
"""
Args:
input: Features with shape [N,4C,H,W]. Channels ranged in [0,C), | Add type hints in ops/border_align.py (#<I>) | open-mmlab_mmcv | train |
ec2423ddbf9ee6b9f9e5422eb75f3cd7fbb73c8b | diff --git a/lib/sbaudio/__init__.py b/lib/sbaudio/__init__.py
index <HASH>..<HASH> 100644
--- a/lib/sbaudio/__init__.py
+++ b/lib/sbaudio/__init__.py
@@ -1,17 +1,18 @@
-try:
- import pysoundcard
-except ImportError:
- print('imstall pysoundcard with "pip install pysoundcard"')
-
from pysoundcard import Stream, continue_flag
+import procname
import atexit
+import collections
import time
import threading
import math
import numpy as np
import struct
+from pysoundcard import devices
+from fuzzywuzzy import fuzz
+
+
BUFF_LENGTH = 1024
CHANNELS = 2
NUM_SAMPLES = 512
@@ -37,34 +38,76 @@ def triple(spectrogram):
return bass, mid, treble
+def fuzzydevices(match='', min_ratio=30):
+ device_ratios = []
+ for device in devices():
+ ratio = fuzz.partial_ratio(match, device['name'])
+ if ratio > min_ratio:
+ device_ratios.append((ratio, device))
+
+ for ratio, device in sorted(device_ratios, key=lambda ratio_device: (ratio_device[0])):
+ yield device
+
+def firstfuzzydevice(match=''):
+ devices = list(fuzzydevices(match, 0))
+ return devices[0]
+
+class AudioException(Exception):
+ def __init__(self, msg):
+ Exception.__init__(self)
+ self.msg = msg
+
+ def __str__(self):
+ return self.msg
+
class AudioThread(threading.Thread):
def __init__(self):
super(self.__class__, self).__init__()
- self.quit = False
- self.spectrogram = np.zeros(BUFF_LENGTH)
- self.bandpassed = np.zeros(BUFF_LENGTH)
+ self._spectrogram = np.zeros(BUFF_LENGTH)
+ self._bandpassed = np.zeros(BUFF_LENGTH)
self.daemon = True
+ self.streams = {}
+ self.running = False
+
+ def settings(self, **kwargs):
+ if self.running:
+ raise AudioException('Audio is already running')
+
def run(self):
with Stream(sample_rate=44100, block_length=16) as s:
- while self.quit is False:
+ while self.running:
vec = s.read(NUM_SAMPLES)
# Downsample to mono
mono_vec = vec.sum(-1) / float(s.input_channels)
- self.spectrogram = np.fft.fft(mono_vec)
+ self._spectrogram = np.fft.fft(mono_vec)
#self.bandpassed = fft_bandpassfilter(self.spectrogram, 44010, 100, 20)
#print random()
-def quit():
- audio.quit = True
- audio.join()
+ def autostart(self):
+ if not self.running:
+ self.running = True
+ self.start()
+ atexit.register(self.quit)
+
+ def quit(self):
+ """
+ Shutdown the audio thread
+ """
+ if self.running:
+ self.running = False
+ self.join()
+
+ @property
+ def spectrogram(self):
+ self.autostart()
+ return self._spectrogram
+procname.setprocname('looper')
audio = AudioThread()
-audio.start()
-atexit.register(quit) | Newer version of sbaudio I used on a daily bot | shoebot_shoebot | train |
6437baab0eefdb268ba690141dc70c95d12ba113 | diff --git a/core/src/test/java/org/infinispan/replication/SyncReplTest.java b/core/src/test/java/org/infinispan/replication/SyncReplTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/org/infinispan/replication/SyncReplTest.java
+++ b/core/src/test/java/org/infinispan/replication/SyncReplTest.java
@@ -33,9 +33,7 @@ import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.*;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
@@ -203,6 +201,9 @@ public class SyncReplTest extends MultipleCacheManagersTest {
// check that the replication call was sync
cache1.put("k", "v");
+ verify(mockTransport).invokeRemotely((List<Address>) anyObject(),
+ (CacheRpcCommand) anyObject(), eq(ResponseMode.SYNCHRONOUS), anyLong(),
+ anyBoolean(), (ResponseFilter) anyObject());
// resume to test for async
asyncRpcManager = (RpcManagerImpl) TestingUtil.extractComponent(asyncCache1, RpcManager.class);
@@ -217,7 +218,9 @@ public class SyncReplTest extends MultipleCacheManagersTest {
anyBoolean(), (ResponseFilter) anyObject())).thenReturn(emptyResponses);
asyncCache1.put("k", "v");
- // check that the replication call was async
+ verify(mockTransport).invokeRemotely((List<Address>) anyObject(),
+ (CacheRpcCommand) anyObject(), eq(ResponseMode.ASYNCHRONOUS), anyLong(),
+ anyBoolean(), (ResponseFilter) anyObject());
} finally {
// replace original transport
if (rpcManager != null) | ISPN-<I> - SyncReplTest#testMixingSyncAndAsyncOnSameTransport() looks to be broken
- the test was incomplete as it didn't run verification phase in order to make sure that the RPC methods were invoked with appropriate params | infinispan_infinispan | train |
63e1aa7be8b08dc580bbc5cf9541f18c76a776a8 | diff --git a/lib/jellyfish.rb b/lib/jellyfish.rb
index <HASH>..<HASH> 100644
--- a/lib/jellyfish.rb
+++ b/lib/jellyfish.rb
@@ -155,7 +155,7 @@ module Jellyfish
def log_error e, stderr
return unless stderr
- log("#{e.inspect} #{e.backtrace}", stderr)
+ stderr.puts("[#{self.class.name}] #{e.inspect} #{e.backtrace}")
end
def log msg, stderr | jellyfish.rb: we don't really have to afford an extra function call | godfat_jellyfish | train |
Subsets and Splits