hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
1d8e0fa3edb57d79761ec1bccfc5545beb633a8d
|
diff --git a/warehouse/macaroons/models.py b/warehouse/macaroons/models.py
index <HASH>..<HASH> 100644
--- a/warehouse/macaroons/models.py
+++ b/warehouse/macaroons/models.py
@@ -60,6 +60,6 @@ class Macaroon(db.Model):
# default would be to generate a random key). However, it appears the
# PostgreSQL pgcrypto extension uses OpenSSL RAND_bytes if available
# instead of urandom. This is less than optimal, and we would generally
- # prefer to just always use usrandom. Thus we'll do this ourselves here
+ # prefer to just always use urandom. Thus we'll do this ourselves here
# in our application.
key = Column(LargeBinary, nullable=False, default=_generate_key)
|
Fixed a typo in a comment (#<I>)
|
pypa_warehouse
|
train
|
93b69e1aac3ac69204cbdc164cc601e97aa88916
|
diff --git a/lib/puppet/type/cron.rb b/lib/puppet/type/cron.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/type/cron.rb
+++ b/lib/puppet/type/cron.rb
@@ -4,12 +4,12 @@ require 'puppet/util/filetype'
Puppet::Type.newtype(:cron) do
@doc = <<-'EOT'
- Installs and manages cron jobs. Every cron resource requires a command
- and user attribute, as well as at least one periodic attribute (hour,
- minute, month, monthday, weekday, or special). While the name of the cron
- job is not part of the actual job, the name is stored in a comment beginning with
- `# Puppet Name: `. These comments are used to match crontab entries created by
- Puppet with cron resources.
+ Installs and manages cron jobs. Every cron resource created by Puppet
+ requires a command and at least one periodic attribute (hour, minute,
+ month, monthday, weekday, or special). While the name of the cron job is
+ not part of the actual job, the name is stored in a comment beginning with
+ `# Puppet Name: `. These comments are used to match crontab entries created
+ by Puppet with cron resources.
If an existing crontab entry happens to match the scheduling and command of a
cron resource that has never been synched, Puppet will defer to the existing
|
(maint) Update required params when creating cron jobs
The cron type only requires `command` and a schedule component _when creating
jobs_. `user` is not strictly required as a default will be used.
When managing existing jobs, one only needs to provide the properties to manage
and the namevar.
|
puppetlabs_puppet
|
train
|
9053083056467a6379b18fa025d8009e9fec2b06
|
diff --git a/libs/commandio.js b/libs/commandio.js
index <HASH>..<HASH> 100644
--- a/libs/commandio.js
+++ b/libs/commandio.js
@@ -14,11 +14,13 @@
var logger = require(__dirname+'/logger');
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
-var stdin = process.stdin;
-var commandDescriptor = {};
-var exitActions = [];
-var indentLength = 15;
-var CONST = {
+
+var stdin = process.stdin,
+ commandDescriptor = {},
+ commandContoler = {},
+ exitActions = [],
+ indentLength = 15,
+ CONST = {
descriptorType: {
name: 'string',
description: 'string',
@@ -246,3 +248,35 @@ function checkDescriptor(descriptor, err){
return true;
}
+
+// ERRORS
+
+function CommandError(message){
+ var that = this, error;
+
+ error = new Error('[command.io] '+message);
+
+ Object.defineProperties(this, {
+ 'stack': {
+ get: function(){
+ return error.stack;
+ }
+ },
+ message: {
+ get: function(){
+ return error.message;
+ }
+ },
+ name: {
+ get: function(){
+ return that.constructor.name;
+ }
+ }
+ });
+}
+CommandError.prototype.__proto__ = Error.prototype;
+
+function RuntimeCommandError(message){
+ CommandError.call(this, message);
+}
+RuntimeCommandError.prototype.__proto__ = CommandError.prototype;
diff --git a/tests/internal-test.js b/tests/internal-test.js
index <HASH>..<HASH> 100644
--- a/tests/internal-test.js
+++ b/tests/internal-test.js
@@ -14,5 +14,21 @@ module.exports = {
test.equal(endLine.length,formatEndLine);
test.done();
+ },
+
+ errors: function(test){
+
+ var commandError = new commandio.CommandError('test');
+ var runtimeCommandError = new commandio.RuntimeCommandError('test');
+
+ test.equal(commandError.name, 'CommandError', 'Error name');
+ test.equal(runtimeCommandError.name, 'RuntimeCommandError', 'Error name');
+
+ test.equal(typeof commandError.stack, 'string', 'Error stack');
+ test.equal(typeof runtimeCommandError.stack, 'string', 'Error stack');
+
+ test.ok(runtimeCommandError instanceof commandio.CommandError, 'Error inheritance');
+
+ test.done();
}
}
|
Add two custom Error types.
|
Techniv_node-command-io
|
train
|
ccb3eb8fdffef9c24e38da30bd5d7afde5f66797
|
diff --git a/lib/text-formatters.spec.js b/lib/text-formatters.spec.js
index <HASH>..<HASH> 100644
--- a/lib/text-formatters.spec.js
+++ b/lib/text-formatters.spec.js
@@ -1,7 +1,7 @@
'use strict';
const { test, given } = require('sazerac');
-const moment = require('moment');
+const sinon = require('sinon');
const {
starRating,
currencyFromCode,
@@ -76,6 +76,15 @@ describe('Text formatters', function() {
test(formatDate, () => {
given(1465513200000).describe('when given a timestamp in june 2016').expect('june 2016');
- given(moment().startOf('year')).describe('when given the beginning of this year').expect('january');
+ });
+
+ context('in october', function () {
+ beforeEach(function () {
+ sinon.useFakeTimers(new Date(2017, 9, 15).getTime());
+ });
+
+ test(formatDate, () => {
+ given(new Date(2017, 0, 1).getTime()).describe('when given the beginning of this year').expect('january');
+ });
});
});
|
Fix January unit test (#<I>)
|
badges_shields
|
train
|
020d2abf3282fa3a36847a93a6539d9e0fc08f31
|
diff --git a/Components/CommitsManager.php b/Components/CommitsManager.php
index <HASH>..<HASH> 100644
--- a/Components/CommitsManager.php
+++ b/Components/CommitsManager.php
@@ -139,6 +139,8 @@ class CommitsManager
* @param string $user User Name
* @param null|string $comment Operation Comment for logs
*
+ * @throws Exception
+ *
* @return void
*/
public static function simSessionCommit(
@@ -149,7 +151,7 @@ class CommitsManager
string $comment = null
): void {
if (!Splash::isDebugMode()) {
- return;
+ throw new Exception("You cannot Simulate Commit without Debug Mode");
}
self::$committed[] = self::getCommitParameters(
|
ADD: Post Request Commit Feature
|
SplashSync_Php-Core
|
train
|
2f95364795491eed1c743098c4d33e2739756e6f
|
diff --git a/openxc/measurements.py b/openxc/measurements.py
index <HASH>..<HASH> 100644
--- a/openxc/measurements.py
+++ b/openxc/measurements.py
@@ -15,17 +15,30 @@ class Measurement(AgingData):
_measurement_map = {}
unit = units.Undefined
- def __init__(self, name, value, event=None):
+ def __init__(self, name, value, event=None, override_unit=False):
super(Measurement, self).__init__()
self.name = name
- self.value = self.unit(value)
+ if override_unit:
+ value = self.unit(value)
+ self.value = value
self.event = event
+ @property
+ def value(self):
+ return self._value
+
+ @value.setter
+ def value(self, new_value):
+ if new_value.unit != self.unit:
+ raise AttributeError("%s must be in %s" % (self.__class__,
+ self.unit))
+ self._value = new_value
+
@classmethod
def from_dict(cls, data):
measurement_class = cls._class_from_name(data['name'])
return measurement_class(data['name'], data['value'],
- data.get('event', None))
+ data.get('event', None), override_unit=True)
@classmethod
def _class_from_name(cls, measurement_name):
@@ -47,8 +60,9 @@ class Measurement(AgingData):
class NamedMeasurement(Measurement):
- def __init__(self, value, event=None):
- super(NamedMeasurement, self).__init__(self.name, value, event)
+ def __init__(self, value, event=None, **kwargs):
+ super(NamedMeasurement, self).__init__(self.name, value, event,
+ **kwargs)
class NumericMeasurement(NamedMeasurement):
diff --git a/tests/test_measurement.py b/tests/test_measurement.py
index <HASH>..<HASH> 100644
--- a/tests/test_measurement.py
+++ b/tests/test_measurement.py
@@ -8,15 +8,15 @@ class MeasurementTests(unittest.TestCase):
super(MeasurementTests, self).setUp()
def test_basic(self):
- Measurement("name", "value")
+ Measurement("name", "value", override_unit=True)
def test_has_age(self):
- measurement = Measurement("name", "value")
+ measurement = Measurement("name", "value", override_unit=True)
age = measurement.age
ok_(measurement.age > age)
def test_unit(self):
- measurement = VehicleSpeed(42)
+ measurement = VehicleSpeed(42, override_unit=True)
try:
eq_(measurement.value, 42)
except AttributeError:
@@ -24,3 +24,27 @@ class MeasurementTests(unittest.TestCase):
else:
self.fail()
eq_(measurement.value, measurement.unit(42))
+
+ def test_override_unit(self):
+ try:
+ VehicleSpeed(42)
+ except AttributeError:
+ pass
+ else:
+ self.fail()
+
+ VehicleSpeed(42, override_unit=True)
+
+ def test_assign_value(self):
+ measurement = VehicleSpeed(42, override_unit=True)
+ new_value = VehicleSpeed.unit(42)
+
+ try:
+ measurement.value = 24
+ except AttributeError:
+ eq_(measurement.value, new_value)
+ else:
+ self.fail()
+
+ measurement.value = new_value
+ eq_(measurement.value, new_value)
|
Don't allow assigning values with the wrong units unless building from JSON.
|
openxc_openxc-python
|
train
|
057585fac40a74ecc720f158fef5d48ceb1ba78f
|
diff --git a/pyinfra/api/state.py b/pyinfra/api/state.py
index <HASH>..<HASH> 100644
--- a/pyinfra/api/state.py
+++ b/pyinfra/api/state.py
@@ -328,6 +328,9 @@ class State(object):
Flag a ``set`` of hosts as failed, error for ``config.FAIL_PERCENT``.
'''
+ if not hosts_to_fail:
+ return
+
activated_count = activated_count or len(self.activated_hosts)
logger.debug('Failing hosts: {0}'.format(', '.join(
|
Return early if `hosts_to_fail` is empty.
|
Fizzadar_pyinfra
|
train
|
4d65a992f85f4c64537d94c64a4911f98174817e
|
diff --git a/bundler.go b/bundler.go
index <HASH>..<HASH> 100644
--- a/bundler.go
+++ b/bundler.go
@@ -13,7 +13,6 @@ import (
"github.com/asticode/go-astilectron"
"github.com/asticode/go-astilog"
"github.com/asticode/go-astitools/os"
- "github.com/asticode/go-astitools/slice"
"github.com/jteeuwen/go-bindata"
"github.com/pkg/errors"
)
@@ -37,6 +36,15 @@ func New(c *Configuration) (b *Bundler, err error) {
environments: c.Environments,
}
+ // Loop through environments
+ for _, env := range b.environments {
+ // Validate OS
+ if !astilectron.IsValidOS(env.OS) {
+ err = fmt.Errorf("OS %s is invalid", env.OS)
+ return
+ }
+ }
+
// Darwin app icon path
if len(c.AppIconDarwinPath) > 0 {
if b.pathAppIconDarwin, err = filepath.Abs(c.AppIconDarwinPath); err != nil {
@@ -149,14 +157,8 @@ func (b *Bundler) bindResources() (err error) {
// bundle bundles an os
func (b *Bundler) bundle(e ConfigurationEnvironment) (err error) {
- // Validate OS
- if !astislice.InStringSlice(e.OS, astilectron.ValidOSes()) {
- err = fmt.Errorf("OS %s is not supported", e.OS)
- return
- }
-
// Remove previous environment folder
- var environmentPath = filepath.Join(b.pathOutput, e.OS, e.Arch)
+ var environmentPath = filepath.Join(b.pathOutput, e.OS+"-"+e.Arch)
astilog.Debugf("Removing %s", environmentPath)
if err = os.RemoveAll(environmentPath); err != nil {
err = errors.Wrapf(err, "removing %s failed", environmentPath)
@@ -192,13 +194,17 @@ func (b *Bundler) bundle(e ConfigurationEnvironment) (err error) {
switch e.OS {
case "darwin":
err = b.finishDarwin(environmentPath, binaryPath)
+ case "linux":
+ err = b.finishLinux(environmentPath, binaryPath)
+ case "windows":
+ err = b.finishWindows(environmentPath, binaryPath)
default:
err = fmt.Errorf("OS %s is not yet implemented", e.OS)
}
return
}
-// finishDarwin finishes bundle for a darwin system
+// finishDarwin finishes bundling for a darwin system
func (b *Bundler) finishDarwin(environmentPath, binaryPath string) (err error) {
// Create MacOS folder
var contentsPath = filepath.Join(environmentPath, b.appName+".app", "Contents")
@@ -266,3 +272,29 @@ func (b *Bundler) finishDarwin(environmentPath, binaryPath string) (err error) {
}
return
}
+
+// finishLinux finishes bundling for a linux system
+// TODO Add .desktop file
+func (b *Bundler) finishLinux(environmentPath, binaryPath string) (err error) {
+ // Move binary
+ var linuxBinaryPath = filepath.Join(environmentPath, b.appName)
+ astilog.Debugf("Moving %s to %s", binaryPath, linuxBinaryPath)
+ if err = astios.Move(context.Background(), binaryPath, linuxBinaryPath); err != nil {
+ err = errors.Wrapf(err, "moving %s to %s failed", binaryPath, linuxBinaryPath)
+ return
+ }
+ return
+}
+
+// finishWindows finishes bundling for a linux system
+// TODO Add .ico file
+func (b *Bundler) finishWindows(environmentPath, binaryPath string) (err error) {
+ // Move binary
+ var windowsBinaryPath = filepath.Join(environmentPath, b.appName+".exe")
+ astilog.Debugf("Moving %s to %s", binaryPath, windowsBinaryPath)
+ if err = astios.Move(context.Background(), binaryPath, windowsBinaryPath); err != nil {
+ err = errors.Wrapf(err, "moving %s to %s failed", binaryPath, windowsBinaryPath)
+ return
+ }
+ return
+}
|
Added environment validation and linux + windows finish
|
asticode_go-astilectron-bundler
|
train
|
868102ffa4d8c1f1bae8c7de9ed81caa0e561d6d
|
diff --git a/src/framework/src/Co.php b/src/framework/src/Co.php
index <HASH>..<HASH> 100644
--- a/src/framework/src/Co.php
+++ b/src/framework/src/Co.php
@@ -151,9 +151,10 @@ class Co
$result = $channel->pop($timeout);
if ($result === false) {
Debug::log('Co::multi request fail!');
+ } else {
+ [$key, $value] = $result;
+ $response[$key] = $value;
}
- [$key, $value] = $result;
- $response[$key] = $value;
$count--;
}
diff --git a/src/log/src/CLogger.php b/src/log/src/CLogger.php
index <HASH>..<HASH> 100644
--- a/src/log/src/CLogger.php
+++ b/src/log/src/CLogger.php
@@ -84,15 +84,15 @@ class CLogger extends \Monolog\Logger
public function getTrace(string $message): string
{
$stackStr = '';
- $traces = debug_backtrace();
+ $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 10);
$count = count($traces);
- if ($count >= 5) {
- $info = $traces[4];
+ if ($count >= 6) {
+ $info = $traces[5];
if (isset($info['file'], $info['class'])) {
- $class = $info['class'];
- $lineNum = $info['line'];
- $function = $info['function'];
+ $class = $traces[5]['class'];
+ $lineNum = $traces[5]['line'];
+ $function = $traces[5]['function'];
$stackStr = sprintf('%s:%s(%s)', $class, $function, $lineNum);
}
}
|
Fix multi and clog trace bug
|
swoft-cloud_swoft-process
|
train
|
c28cdb1bfd557ecb28e43dadd3045086a307c37e
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -84,11 +84,11 @@ class Service {
createQuery (paramsQuery = {}) {
const { filters, query } = filter(paramsQuery);
- let q = this.db().select(['*']);
+ let q = this.db().select([`${this.table}.*`]);
// $select uses a specific find syntax, so it has to come first.
if (filters.$select) {
- q = this.db().select(...filters.$select.concat(this.id));
+ q = this.db().select(...filters.$select.concat(`${this.table}.${this.id}`));
}
// build up the knex query out of the query params
|
Scoping select to current table to prevent "ambiguous" joins queries (#<I>)
|
feathersjs-ecosystem_feathers-knex
|
train
|
f170aada91fd309f0416dff4759bacb44defb25e
|
diff --git a/src/ElasticsearchServiceProvider.php b/src/ElasticsearchServiceProvider.php
index <HASH>..<HASH> 100755
--- a/src/ElasticsearchServiceProvider.php
+++ b/src/ElasticsearchServiceProvider.php
@@ -5,7 +5,6 @@ namespace Basemkhirat\Elasticsearch;
use Basemkhirat\Elasticsearch\Commands\ReindexCommand;
use Elasticsearch\ClientBuilder as ElasticBuilder;
use Illuminate\Contracts\Container\BindingResolutionException;
-use Illuminate\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Laravel\Scout\EngineManager;
use Basemkhirat\Elasticsearch\Commands\ListIndicesCommand;
@@ -24,7 +23,7 @@ class ElasticsearchServiceProvider extends ServiceProvider
* ElasticsearchServiceProvider constructor.
* @param Application $app
*/
- function __construct(Application $app)
+ function __construct($app)
{
$this->app = $app;
}
|
fixing the application class error in service provider
|
basemkhirat_elasticsearch
|
train
|
2658fe48e8398881e2e2ef657b9c98750f2cf3c6
|
diff --git a/Utility/JsonParser.php b/Utility/JsonParser.php
index <HASH>..<HASH> 100755
--- a/Utility/JsonParser.php
+++ b/Utility/JsonParser.php
@@ -62,7 +62,7 @@ class JsonParser
private function validatePath($path)
{
- $regexp = '/^(?:[a-z0-9_]*(?:\.|\[\d+\]|\*)?)+$/i';
+ $regexp = '/^(?:[a-z0-9_\-]*(?:\.|\[\d+\]|\*)?)+$/i';
$isValid = preg_match($regexp, $path, $matches);
if(!$isValid)
{
|
Allow hyphen in json property
|
Atlantic18_CoralCoreBundle
|
train
|
e4c78c6b4c90265c3d3af08fce3e15b554cf3b2b
|
diff --git a/src/test/java/io/github/theangrydev/businessflows/TwoFlowsTest.java b/src/test/java/io/github/theangrydev/businessflows/TwoFlowsTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/io/github/theangrydev/businessflows/TwoFlowsTest.java
+++ b/src/test/java/io/github/theangrydev/businessflows/TwoFlowsTest.java
@@ -49,22 +49,34 @@ public class TwoFlowsTest implements WithAssertions {
private HappyPath<Number, ErrorResult> lookupNumber() {
return numberRepository.lookupNumber(new NumberId())
- .ifSad().map(numberError -> new ErrorResult())
+ .ifSad().peek(this::recordNumberError).map(numberError -> new ErrorResult())
.ifHappy();
}
+ private void recordNumberError(NumberError numberError) {
+ System.out.println("numberError = " + numberError);
+ }
+
private HappyPath<NumberAndService, ErrorResult> lookupService(Number number) {
return serviceRepository.lookupService(new ServiceId())
- .ifSad().map(serviceError -> new ErrorResult())
+ .ifSad().peek(this::recordServiceError).map(serviceError -> new ErrorResult())
.ifHappy().map(service -> new NumberAndService(number, service));
}
+ private void recordServiceError(ServiceError serviceError) {
+ System.out.println("serviceError = " + serviceError);
+ }
+
private HappyPath<Result, ErrorResult> executeCommand(NumberAndService numberAndService) {
return commandExecutor.execute(numberAndService)
- .ifSad().map(commandError -> new ErrorResult())
+ .ifSad().peek(this::recordCommandError).map(commandError -> new ErrorResult())
.ifHappy().map(commandResult -> new Result());
}
+ private void recordCommandError(CommandError commandError) {
+ System.out.println("commandError = " + commandError);
+ }
+
class ErrorResult {
}
|
Expanding TwoFlowsTest example
|
theangrydev_business-flows
|
train
|
68d0df04b12c709356119ccf0566981559476a12
|
diff --git a/clonevirtualenv.py b/clonevirtualenv.py
index <HASH>..<HASH> 100644
--- a/clonevirtualenv.py
+++ b/clonevirtualenv.py
@@ -65,9 +65,12 @@ def clone_virtualenv(src_dir, dst_dir):
if os.path.exists(dst_dir):
raise UserError('dest dir %r exists' % dst_dir)
#sys_path = _virtualenv_syspath(src_dir)
+ logger.info('cloning virtualenv \'%s\' => \'%s\'...' %
+ (src_dir, dst_dir))
shutil.copytree(src_dir, dst_dir, symlinks=True,
ignore=shutil.ignore_patterns('*.pyc'))
version, sys_path = _virtualenv_sys(dst_dir)
+ logger.info('fixing scripts in bin...')
fixup_scripts(src_dir, dst_dir, version)
has_old = lambda s: any(i for i in s if _dirmatch(i, src_dir))
@@ -75,6 +78,7 @@ def clone_virtualenv(src_dir, dst_dir):
if has_old(sys_path):
# only need to fix stuff in sys.path if we have old
# paths in the sys.path of new python env. right?
+ logger.info('fixing paths in sys.path...')
fixup_syspath_items(sys_path, src_dir, dst_dir)
remaining = has_old(_virtualenv_sys(dst_dir)[1])
assert not remaining, _virtualenv_sys(dst_dir)
@@ -245,16 +249,22 @@ def fixup_egglink_file(filename, old_dir, new_dir):
def main():
- parser = optparse.OptionParser("usage: %prog /path/to/existing/venv"
- " /path/to/cloned/venv")
+ parser = optparse.OptionParser("usage: %prog [options]"
+ " /path/to/existing/venv /path/to/cloned/venv")
+ parser.add_option('-v',
+ action="store_true",
+ dest='verbose',
+ default=False,
+ help='verbose')
options, args = parser.parse_args()
try:
- old_dir, new_dir = sys.argv[1:]
+ old_dir, new_dir = args
except ValueError:
parser.error("not enough arguments given.")
old_dir = os.path.normpath(os.path.abspath(old_dir))
new_dir = os.path.normpath(os.path.abspath(new_dir))
- logging.basicConfig(level=logging.WARNING)
+ loglevel = logging.INFO if options.verbose else logging.WARNING
+ logging.basicConfig(level=loglevel, format='%(message)s')
try:
clone_virtualenv(old_dir, new_dir)
except UserError:
|
added verbose mode with logging.
|
edwardgeorge_virtualenv-clone
|
train
|
fcb1b4180d86e3dd10462bc97af1c3cd6ceb9f30
|
diff --git a/src/Analyser/TypeSpecifier.php b/src/Analyser/TypeSpecifier.php
index <HASH>..<HASH> 100644
--- a/src/Analyser/TypeSpecifier.php
+++ b/src/Analyser/TypeSpecifier.php
@@ -286,11 +286,11 @@ class TypeSpecifier
}
} elseif ($expr instanceof BooleanAnd || $expr instanceof LogicalAnd) {
$leftTypes = $this->specifyTypesInCondition($scope, $expr->left, $context);
- $rightTypes = $this->specifyTypesInCondition($scope, $expr->right, $context);
+ $rightTypes = $this->specifyTypesInCondition($scope->filterByTruthyValue($expr->left), $expr->right, $context);
return $context->true() ? $leftTypes->unionWith($rightTypes) : $leftTypes->intersectWith($rightTypes);
} elseif ($expr instanceof BooleanOr || $expr instanceof LogicalOr) {
$leftTypes = $this->specifyTypesInCondition($scope, $expr->left, $context);
- $rightTypes = $this->specifyTypesInCondition($scope, $expr->right, $context);
+ $rightTypes = $this->specifyTypesInCondition($scope->filterByFalseyValue($expr->left), $expr->right, $context);
return $context->true() ? $leftTypes->intersectWith($rightTypes) : $leftTypes->unionWith($rightTypes);
} elseif ($expr instanceof Node\Expr\BooleanNot && !$context->null()) {
return $this->specifyTypesInCondition($scope, $expr->expr, $context->negate());
|
TypeSpecifier - filter by truthy/falsey values for right expressions in && and ||
|
phpstan_phpstan
|
train
|
c51445214838929aeef14c97a2915fecb9270983
|
diff --git a/android/src/main/java/com/geniem/rnble/RNBLEModule.java b/android/src/main/java/com/geniem/rnble/RNBLEModule.java
index <HASH>..<HASH> 100644
--- a/android/src/main/java/com/geniem/rnble/RNBLEModule.java
+++ b/android/src/main/java/com/geniem/rnble/RNBLEModule.java
@@ -547,9 +547,10 @@ class RNBLEModule extends ReactContextBaseJavaModule implements LifecycleEventLi
byte[] characteristicValue = null;
Boolean notification = false;
if (status == BluetoothGatt.GATT_SUCCESS) {
+ Log.w(TAG, "!!! characteristic read!!!");
characteristicValue = characteristic.getValue();
} else {
- Log.w(TAG, "onServicesDiscovered received: " + status);
+ Log.w(TAG, "onCharacteristicRead received: " + status);
}
WritableMap params = Arguments.createMap();
@@ -590,7 +591,8 @@ class RNBLEModule extends ReactContextBaseJavaModule implements LifecycleEventLi
private String toNobleUuid(String uuid) {
- return uuid.replaceAll("[\\s\\-()]", "");
+ String result = uuid.replaceAll("[\\s\\-()]", "");
+ return result.toLowerCase();
}
//RnbleScanCallback scan callback
diff --git a/bindings.android.js b/bindings.android.js
index <HASH>..<HASH> 100644
--- a/bindings.android.js
+++ b/bindings.android.js
@@ -108,7 +108,7 @@ nobleBindings.disconnect = function(deviceUuid) {
nobleBindings.startScanning = function(serviceUuids, allowDuplicates) {
var duplicates = allowDuplicates || false;
let serviceUuid = serviceUuids ? serviceUuids.pop() : null;
- RNBLE.startScanning(serviceUuid, duplicates);
+ RNBLE.startScanning(toAppleUuid(serviceUuid), duplicates);
this.emit('scanStart');
};
@@ -118,7 +118,7 @@ nobleBindings.stopScanning = function() {
};
nobleBindings.discoverServices = function(deviceUuid, uuids) {
- RNBLE.discoverServices(deviceUuid, uuids);
+ RNBLE.discoverServices(deviceUuid, toAppleUuids(uuids));
};
nobleBindings.discoverIncludedServices = function(deviceUuid, serviceUuid, serviceUuids) {
@@ -126,21 +126,37 @@ nobleBindings.discoverIncludedServices = function(deviceUuid, serviceUuid, servi
};
nobleBindings.discoverCharacteristics = function(deviceUuid, serviceUuid, characteristicUuids) {
- RNBLE.discoverCharacteristics(deviceUuid, serviceUuid, characteristicUuids);
+ RNBLE.discoverCharacteristics(deviceUuid, toAppleUuid(serviceUuid), toAppleUuids(characteristicUuids));
};
nobleBindings.discoverDescriptors = function(deviceUuid, serviceUuid, characteristicUuid) {
- RNBLE.discoverDescriptors(deviceUuid, serviceUuid, characteristicUuid);
+ RNBLE.discoverDescriptors(deviceUuid, toAppleUuid(serviceUuid), toAppleUuid(characteristicUuid));
};
nobleBindings.read = function(deviceUuid, serviceUuid, characteristicUuid) {
- RNBLE.read(deviceUuid, serviceUuid, characteristicUuid);
+ RNBLE.read(deviceUuid, toAppleUuid(serviceUuid), toAppleUuid(characteristicUuid));
};
nobleBindings.write = function(deviceUuid, serviceUuid, characteristicUuid, data, withoutResponse) {
- RNBLE.write(deviceUuid, serviceUuid, characteristicUuid, data.toString("base64"), withoutResponse);
+ RNBLE.write(deviceUuid, toAppleUuid(serviceUuid), toAppleUuid(characteristicUuid), data.toString("base64"), withoutResponse);
};
+function toAppleUuid(uuid) {
+ return uuid.replace(/(\S{8})(\S{4})(\S{4})(\S{4})(\S{12})/, "$1-$2-$3-$4-$5").toUpperCase();
+}
+
+function toAppleUuids(uuids) {
+ var convertedUuids = [];
+
+ if (uuids) {
+ uuids.forEach(function(uuid) {
+ convertedUuids.push(toAppleUuid(uuid));
+ });
+ }
+
+ return convertedUuids;
+}
+
// Exports
module.exports = nobleBindings;
\ No newline at end of file
|
convert noble uuids to native uuids
|
jacobrosenthal_react-native-ble
|
train
|
0bcdfb2ce04fbcf47e0ef37dd7ad11cde8a0e57d
|
diff --git a/tensorflow_probability/python/mcmc/random_walk_metropolis.py b/tensorflow_probability/python/mcmc/random_walk_metropolis.py
index <HASH>..<HASH> 100644
--- a/tensorflow_probability/python/mcmc/random_walk_metropolis.py
+++ b/tensorflow_probability/python/mcmc/random_walk_metropolis.py
@@ -249,7 +249,7 @@ class RandomWalkMetropolis(kernel_base.TransitionKernel):
# Then the target log-density is defined as follows:
def target_log_prob(x, y):
# Stack the input tensors together
- z = tf.stack([x, y], axis=-1) - true_mean
+ z = tf.stack([x, y], axis=-1)
return target.log_prob(tf.squeeze(z))
# Initial state of the chain
|
Update random_walk_metropolis.py
There is no need for one to substract `true_mean` here. It is because the `target = tfd.MultivariateNormalTriL(loc=true_mean, scale_tril=L)` already contains the `loc`.
|
tensorflow_probability
|
train
|
2fe16403b360080fdb2911e5ca6f80177df05f5d
|
diff --git a/py/h2o.py b/py/h2o.py
index <HASH>..<HASH> 100644
--- a/py/h2o.py
+++ b/py/h2o.py
@@ -1086,10 +1086,17 @@ class H2O(object):
def GLM(self, key, timeoutSecs=300, retryDelaySecs=0.5, **kwargs):
a = self.GLM_shared(key, timeoutSecs, retryDelaySecs, parentName="GLM", **kwargs)
+ # Check that the response has the right Progress url it's going to steer us to.
+ if a['response']['redirect_request']!='GLMProgress':
+ print dump_json(a)
+ raise Exception('H2O GLM redirect is not GLMProgress. GLM json response precedes.')
+ a = self.poll_url(a['response'], timeoutSecs, retryDelaySecs)
+ verboseprint("GLM done:", dump_json(a))
+
browseAlso = kwargs.get('browseAlso', False)
if (browseAlso | browse_json):
- print "Redoing the GLM through the browser, no results saved though"
- h2b.browseJsonHistoryAsUrlLastMatch('GLM')
+ print "Viewing the GLM grid result through the browser"
+ h2b.browseJsonHistoryAsUrlLastMatch('GLMProgress')
time.sleep(5)
return a
@@ -1097,10 +1104,6 @@ class H2O(object):
def GLMGrid(self, key, timeoutSecs=300, retryDelaySecs=1.0, **kwargs):
a = self.GLM_shared(key, timeoutSecs, retryDelaySecs, parentName="GLMGrid", **kwargs)
- if kwargs.get('norm'):
- # don't have to pop, GLMGrid ignores
- print "\nWARNING: norm param is ignored by GLMGrid. Always uses LASSO (L1+L2)."
-
# Check that the response has the right Progress url it's going to steer us to.
if a['response']['redirect_request']!='GLMGridProgress':
print dump_json(a)
|
update to match tomas' release of GLMProgress (so GLM acts like RF/parse/GLMGrid)
|
h2oai_h2o-2
|
train
|
05fac3e1a559cc344593161fdc65a28ce549fad3
|
diff --git a/lib/global_id/global_id.rb b/lib/global_id/global_id.rb
index <HASH>..<HASH> 100644
--- a/lib/global_id/global_id.rb
+++ b/lib/global_id/global_id.rb
@@ -63,6 +63,11 @@ class GlobalID
def ==(other)
other.is_a?(GlobalID) && @uri == other.uri
end
+ alias_method :eql?, :==
+
+ def hash
+ self.class.hash | @uri.hash
+ end
def to_param
# remove the = padding character for a prettier param -- it'll be added back in parse_encoded_gid
diff --git a/test/cases/global_id_test.rb b/test/cases/global_id_test.rb
index <HASH>..<HASH> 100644
--- a/test/cases/global_id_test.rb
+++ b/test/cases/global_id_test.rb
@@ -190,6 +190,30 @@ class GlobalIDCreationTest < ActiveSupport::TestCase
person_gid = GlobalID.create(Person.new(5), app: nil)
end
end
+
+ test 'equality' do
+ p1 = Person.new(5)
+ p2 = Person.new(5)
+ p3 = Person.new(10)
+ assert_equal p1, p2
+ assert_not_equal p2, p3
+
+ gid1 = GlobalID.create(p1)
+ gid2 = GlobalID.create(p2)
+ gid3 = GlobalID.create(p3)
+ assert_equal gid1, gid2
+ assert_not_equal gid2, gid3
+
+ # hash and eql? to match for two GlobalID's pointing to the same object
+ assert_equal [gid1], [gid1, gid2].uniq
+ assert_equal [gid1, gid3], [gid1, gid2, gid3].uniq
+
+ # verify that the GlobalID's hash is different to the underlaying URI
+ assert_not_equal gid1.hash, gid1.uri.hash
+
+ # verify that URI and GlobalID do not pass the uniq test
+ assert_equal [gid1, gid1.uri], [gid1, gid1.uri].uniq
+ end
end
class GlobalIDCustomParamsTest < ActiveSupport::TestCase
|
Array#uniq to correctly identify == GlobalIDs
|
rails_globalid
|
train
|
467011e4449fa0d4e1473a31505bf07ab925752b
|
diff --git a/inginious/agent/docker_agent.py b/inginious/agent/docker_agent.py
index <HASH>..<HASH> 100644
--- a/inginious/agent/docker_agent.py
+++ b/inginious/agent/docker_agent.py
@@ -432,17 +432,24 @@ class DockerAgent(object):
future_results):
""" Talk with a container. Sends the initial input. Allows to start student containers """
sock = await self._loop.run_in_executor(None, lambda: self._docker.attach_to_container(container_id))
- read_stream, write_stream = await asyncio.open_connection(sock=sock.get_socket())
+ try:
+ read_stream, write_stream = await asyncio.open_connection(sock=sock.get_socket())
+ except:
+ self._logger.exception("Exception occured while creating read/write stream to container")
+ return None
# a small helper
async def write(o):
- write_stream.write(msgpack.dumps(o, encoding="utf8", use_bin_type=True))
+ msg = msgpack.dumps(o, encoding="utf8", use_bin_type=True)
+ self._logger.debug("Sending %i bytes to container", len(msg))
+ write_stream.write(struct.pack('I', len(msg)))
+ write_stream.write(msg)
await write_stream.drain()
# Send hello msg
await write({"type": "start", "input": inputdata, "debug": debug})
- unpacker = Unpacker(encoding="utf8", use_list=False)
+ buffer = bytearray()
try:
while not read_stream.at_eof():
msg_header = await read_stream.readexactly(8)
@@ -450,11 +457,17 @@ class DockerAgent(object):
if length != 0:
content = await read_stream.readexactly(length)
if type == 1: # stdout
- unpacker.feed(content)
+ buffer += content
+
+ if type == 2: # stderr
+ self._logger.debug("Received stderr from containers:\n%s", content)
- # parse the messages
- for msg in unpacker:
+ # 4 first bytes are the lenght of the message. If we have a complete message...
+ while len(buffer) > 4 and len(buffer) >= 4+struct.unpack('I',buffer[0:4])[0]:
+ msg_encoded = buffer[4:4 + struct.unpack('I', buffer[0:4])[0]] # ... get it
+ buffer = buffer[4 + struct.unpack('I', buffer[0:4])[0]:] # ... withdraw it from the buffer
try:
+ msg = msgpack.unpackb(msg_encoded, encoding="utf8", use_list=False)
self._logger.debug("Received msg %s from container %s", msg["type"], container_id)
if msg["type"] == "run_student":
# start a new student container
|
msgpack.Unpacker _*-~/IS/~-*_ horribly slow. And shouldn't be.
|
UCL-INGI_INGInious
|
train
|
d28c1da167afbbc0314ed3c708aaaa957ff3eed3
|
diff --git a/tutorials/js/adjust-vertices.js b/tutorials/js/adjust-vertices.js
index <HASH>..<HASH> 100644
--- a/tutorials/js/adjust-vertices.js
+++ b/tutorials/js/adjust-vertices.js
@@ -11,7 +11,7 @@ function adjustVertices(graph, cell) {
}).each(function(group, key) {
// If the member of the group has both source and target model adjust vertices.
if (key !== 'undefined') adjustVertices(graph, _.first(group));
- });
+ }).value();
return;
}
|
fix: correct the code shown in "multiple links" tutorial (#<I>)
|
clientIO_joint
|
train
|
87677fcc4dfda7ee9e0b5609344b46d6e3ccd227
|
diff --git a/examples/run_gpt2.py b/examples/run_gpt2.py
index <HASH>..<HASH> 100644
--- a/examples/run_gpt2.py
+++ b/examples/run_gpt2.py
@@ -58,7 +58,7 @@ def run_model():
parser.add_argument("--nsamples", type=int, default=1)
parser.add_argument("--batch_size", type=int, default=-1)
parser.add_argument("--length", type=int, default=-1)
- parser.add_argument("--temperature", type=int, default=1)
+ parser.add_argument("--temperature", type=float, default=1.0)
parser.add_argument("--top_k", type=int, default=0)
parser.add_argument('--unconditional', action='store_true', help='If true, unconditional generation.')
args = parser.parse_args()
|
[run_gpt2.py] temperature should be a float, not int
|
huggingface_pytorch-pretrained-BERT
|
train
|
a51e824c381e7db3fec406ed11e172be690c19be
|
diff --git a/app/resonant-laboratory/models/Dataset.js b/app/resonant-laboratory/models/Dataset.js
index <HASH>..<HASH> 100644
--- a/app/resonant-laboratory/models/Dataset.js
+++ b/app/resonant-laboratory/models/Dataset.js
@@ -46,6 +46,9 @@ class DatasetCache {
set cachedPromises (value) {
this._cachedPromises = value;
}
+ clear () {
+ this.cachedPromises = {};
+ }
get filter () {
if (!this._filter) {
this._filter = {
@@ -187,7 +190,7 @@ class DatasetCache {
cache: false
}
});
- }).then(this.model.improveHistogramLabels);
+ }).then(this.model.postProcessHistogram);
this.cachedPromises.overviewHistogram.then(() => {
this.model.trigger('rl:loadedHistogram');
});
@@ -206,7 +209,7 @@ class DatasetCache {
cache: false
}
});
- }).then(this.model.improveHistogramLabels);
+ }).then(this.model.postProcessHistogram);
this.cachedPromises.filteredHistogram.then(() => {
this.model.trigger('rl:loadedHistogram');
});
@@ -227,7 +230,7 @@ class DatasetCache {
// Don't cache the page histograms on the server
}
});
- }).then(this.model.improveHistogramLabels);
+ }).then(this.model.postProcessHistogram);
this.cachedPromises.pageHistogram.then(() => {
this.model.trigger('rl:loadedHistogram');
});
@@ -276,6 +279,10 @@ let Dataset = MetadataItem.extend({
// its own non-Backbone cache class
this.cache = new DatasetCache(this);
this.dropped = false;
+
+ this.listenTo(this, 'rl:swappedId', () => {
+ this.handleSwappedId();
+ });
},
identifyAsDataset: function () {
return this.restRequest({
@@ -340,8 +347,16 @@ let Dataset = MetadataItem.extend({
return this.autoDetectAttributeType(schema, attrName);
}
},
- improveHistogramLabels: function (histogram) {
+ handleSwappedId: function () {
+ this.cache.clear();
+ },
+ postProcessHistogram: function (histogram) {
let formatter = d3.format('0.3s');
+ // If the user is logged out, we'll sometimes get an
+ // empty histogram back
+ if (!('__passedFilters__' in histogram)) {
+ return null;
+ }
Object.keys(histogram).forEach(attrName => {
histogram[attrName].forEach((bin, index) => {
if (typeof bin.lowBound === 'number' &&
diff --git a/app/resonant-laboratory/models/MetadataItem.js b/app/resonant-laboratory/models/MetadataItem.js
index <HASH>..<HASH> 100644
--- a/app/resonant-laboratory/models/MetadataItem.js
+++ b/app/resonant-laboratory/models/MetadataItem.js
@@ -95,6 +95,16 @@ let MetadataItem = girder.models.ItemModel.extend({
*/
}
+ // Ignore authentication errors; we still want the user to
+ // be able to function in a logged-out state
+ promiseObj = promiseObj.catch(errObj => {
+ if (errObj.status === 401) {
+ return {};
+ } else {
+ throw errObj;
+ }
+ });
+
// beforeSuccess is a function that should
// be called before options.success
beforeSuccess = beforeSuccess || (d => d);
diff --git a/app/resonant-laboratory/models/User.js b/app/resonant-laboratory/models/User.js
index <HASH>..<HASH> 100644
--- a/app/resonant-laboratory/models/User.js
+++ b/app/resonant-laboratory/models/User.js
@@ -74,14 +74,16 @@ let User = girder.models.UserModel.extend({
},
updatePrivateFolder: function () {
this.privateFolder = null;
- new Promise((resolve, reject) => {
- return girder.restRequest({
- path: '/folder/anonymousAccess/privateFolder',
- error: reject
- }).done(resolve).error(reject);
- }).then(folder => {
- this.privateFolder = new girder.models.FolderModel(folder);
- });
+ if (this.isLoggedIn()) {
+ new Promise((resolve, reject) => {
+ return girder.restRequest({
+ path: '/folder/anonymousAccess/privateFolder',
+ error: reject
+ }).done(resolve).error(reject);
+ }).then(folder => {
+ this.privateFolder = new girder.models.FolderModel(folder);
+ });
+ }
},
isLoggedIn: function () {
return this.loggedIn;
|
Show the correct access error dialog instead of crashing
|
Kitware_candela
|
train
|
84ac2a259e534808eb8acd411d9107bea3fffbd8
|
diff --git a/eemeter/caltrack/hourly.py b/eemeter/caltrack/hourly.py
index <HASH>..<HASH> 100644
--- a/eemeter/caltrack/hourly.py
+++ b/eemeter/caltrack/hourly.py
@@ -138,6 +138,38 @@ class CalTRACKHourlyModelResults(object):
}
return data
+ @classmethod
+ def fromJson(cls, data):
+ """ Loads a JSON-serializable representation into the model state.
+
+ The input of this function is a dict which can be the result
+ of :any:`json.loads`.
+ """
+
+ # "model" is a CalTRACKHourlyModel that was serialized
+ model = None
+ d = data.get('model')
+ if d:
+ model = CalTRACKHourlyModel.fromJson(d)
+
+ c = cls(
+ data.get('status'),
+ data.get('method_name'),
+ model=model,
+ warnings=data.get('warnings'),
+ metadata=data.get('metadata'),
+ settings=data.get('settings'))
+
+ # Note the metrics do not contain all the data needed
+ # for reconstruction (like the input pandas) ...
+ d = data.get('avgs_metrics')
+ if d:
+ c.avgs_metrics = ModelMetrics.fromJson(d)
+ d = data.get('totals_metrics')
+ if d:
+ c.totals_metrics = ModelMetrics.fromJson(d)
+ return c
+
def predict(self, prediction_index, temperature_data, **kwargs):
""" Predict over a particular index using temperature data.
@@ -217,6 +249,27 @@ class CalTRACKHourlyModel(SegmentedModel):
)
return data
+ @classmethod
+ def fromJson(cls, data):
+ """ Loads a JSON-serializable representation into the model state.
+
+ The input of this function is a dict which can be the result
+ of :any:`json.loads`.
+ """
+
+ segment_models = [
+ CalTRACKSegmentModel.fromJson(s)
+ for s in data.get('segment_models')
+ ]
+
+ c = cls(
+ segment_models,
+ pd.read_json(data.get('occupancy_lookup'), orient="split"),
+ pd.read_json(data.get('temperature_bins'), orient="split")
+ )
+
+ return c
+
def caltrack_hourly_fit_feature_processor(
segment_name, segmented_data, occupancy_lookup, temperature_bins
diff --git a/eemeter/segmentation.py b/eemeter/segmentation.py
index <HASH>..<HASH> 100644
--- a/eemeter/segmentation.py
+++ b/eemeter/segmentation.py
@@ -117,6 +117,24 @@ class CalTRACKSegmentModel(object):
}
return data
+ @classmethod
+ def fromJson(cls, data):
+ """ Loads a JSON-serializable representation into the model state.
+
+ The input of this function is a dict which can be the result
+ of :any:`json.loads`.
+ """
+
+ c = cls(
+ data.get('segment_name'),
+ None,
+ data.get('formula'),
+ data.get('model_params'),
+ warnings=data.get('warnings')
+ )
+
+ return c
+
class SegmentedModel(object):
""" Represent a model which has been broken into multiple model segments (for
|
Add fromJson to the CalTRACKHourlyModelResults
|
openeemeter_eemeter
|
train
|
3f8d43897909291f1255c549754911a3d22498eb
|
diff --git a/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/SimpleDbTemplate.java b/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/SimpleDbTemplate.java
index <HASH>..<HASH> 100644
--- a/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/SimpleDbTemplate.java
+++ b/spring-data-simpledb-impl/src/main/java/org/springframework/data/simpledb/core/SimpleDbTemplate.java
@@ -316,11 +316,7 @@ public class SimpleDbTemplate extends AbstractSimpleDbTemplate {
if (FieldTypeIdentifier.isOfType(propertyField, FieldType.PRIMITIVE, FieldType.CORE_TYPE)) {
serializedPropertyValue = SimpleDBAttributeConverter.encode(propertyValue);
- } else if (FieldTypeIdentifier.isOfType(propertyField, FieldType.COLLECTION, FieldType.ARRAY, FieldType.MAP)) {
- serializedPropertyValue = JsonMarshaller.getInstance().marshall(propertyValue);
-
} else if (FieldTypeIdentifier.isOfType(propertyField, FieldType.NESTED_ENTITY)) {
-
SimpleDbEntityInformation<T, Serializable> entityMetadata = (SimpleDbEntityInformation<T, Serializable>) SimpleDbEntityInformationSupport.getMetadata(propertyValue.getClass(), domainName);
EntityWrapper<T, Serializable> entity = new EntityWrapper<T, Serializable>(entityMetadata, (T) propertyValue, true);
Map<String, String> nestedAttributes = entity.serialize();
@@ -329,7 +325,11 @@ public class SimpleDbTemplate extends AbstractSimpleDbTemplate {
String key = String.format("%s.%s", propertyPath, e.getKey());
serializedValues.put(key, e.getValue());
}
+
+ } else {
+ serializedPropertyValue = JsonMarshaller.getInstance().marshall(propertyValue);
}
+
if (serializedPropertyValue != null) {
serializedValues.put(propertyPath, serializedPropertyValue);
}
|
Fixed issue with updateImpl - added JSON fallback for property type
|
3pillarlabs_spring-data-simpledb
|
train
|
5f34da52748a482a76f1a0060d63127d0a0683e6
|
diff --git a/src/tag/Expression.js b/src/tag/Expression.js
index <HASH>..<HASH> 100644
--- a/src/tag/Expression.js
+++ b/src/tag/Expression.js
@@ -16,9 +16,11 @@ export function Expression(tagName, typeValue) {
const expectedType = typeofName(typeValue.name);
if (expectedType == null) {
const expectedName = typeValue.name;
- // nullable instanceof
+ // if right-hand is undefined, return true
+ // if right-hand is not function, return true
+ // if right-hand is function && left instanceof right
return `(
- typeof ${expectedName} === "undefined" || (typeof ${expectedName} === "function" && ${tagName} instanceof ${expectedName})
+ typeof ${expectedName} === "undefined" || typeof ${expectedName} !== "function" || ${tagName} instanceof ${expectedName}
)`;
} else {
return `typeof ${tagName} === "${expectedType}"`;
diff --git a/test/create-asserts-test.js b/test/create-asserts-test.js
index <HASH>..<HASH> 100644
--- a/test/create-asserts-test.js
+++ b/test/create-asserts-test.js
@@ -169,7 +169,7 @@ describe("create-assert", function() {
* @param {RegExp} x - this is RegExp.
*/`;
const assertion = createAssertion(jsdoc);
- astEqual(assertion, `typeof RegExp === 'undefined' || (typeof RegExp === 'function' && x instanceof RegExp)`);
+ astEqual(assertion, `typeof RegExp === 'undefined' || typeof RegExp !== 'function' || x instanceof RegExp`);
});
});
context("when pass Custom Object", function() {
@@ -179,7 +179,7 @@ describe("create-assert", function() {
* @param {A} x - this is ArrayType param.
*/`;
const numberAssertion = createAssertion(jsdoc);
- astEqual(numberAssertion, `typeof A === 'undefined' || (typeof A === 'function' && x instanceof A)`);
+ astEqual(numberAssertion, `typeof A === 'undefined' || typeof A !== 'function' || x instanceof A`);
});
});
context("when pass ArrayType", function() {
@@ -259,7 +259,7 @@ describe("create-assert", function() {
* @param {{foo: number, bar: RegExp}} x - this is object param.
*/`;
const numberAssertion = createAssertion(jsdoc);
- astEqual(numberAssertion, `(typeof x.foo === "number" && (typeof RegExp === 'undefined' || typeof RegExp === 'function' && x.bar instanceof RegExp))`);
+ astEqual(numberAssertion, `typeof x.foo === 'number' && (typeof RegExp === 'undefined' || typeof RegExp !== 'function' || x.bar instanceof RegExp)`);
});
});
context("When generic", function() {
|
fix(expressin): safe-undefined detection
|
azu_jsdoc-to-assert
|
train
|
52b6042734c4da7552b7dc5635e8d51dc5711ffb
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -1,6 +1,7 @@
"use strict";
module.exports = {
rules: {
+ 'accidental_assignment': require('./lib/rules/accidental_assignment.js'),
'assign_to_hostname': require('./lib/rules/assign_to_hostname'),
'assign_to_href': require('./lib/rules/assign_to_href'),
'assign_to_location': require('./lib/rules/assign_to_location'),
@@ -53,6 +54,7 @@ module.exports = {
'object_mozSystem': require('./lib/rules/object_mozSystem'),
'property_addIdleObserver': require('./lib/rules/property_addIdleObserver'),
'property_createContextualFragment': require('./lib/rules/property_createContextualFragment'),
+ 'property_crypto': require('./lib/rules/property_crypto'),
'property_geolocation': require('./lib/rules/property_geolocation'),
'property_getDataStores': require('./lib/rules/property_getDataStores'),
'property_getDeviceStorage': require('./lib/rules/property_getDeviceStorage'),
@@ -89,6 +91,7 @@ module.exports = {
'property_sessionStorage': require('./lib/rules/property_sessionStorage')
},
rulesConfig: {
+ 'accidental_assignment': 2,
'assign_to_hostname': 2,
'assign_to_href': 2,
'assign_to_location': 2,
@@ -141,6 +144,7 @@ module.exports = {
'object_mozSystem': 2,
'property_addIdleObserver': 2,
'property_createContextualFragment': 2,
+ 'property_crypto': 2,
'property_geolocation': 2,
'property_getDataStores': 2,
'property_getDeviceStorage': 2,
|
Add missing rules to index.js (fixes #4)
|
mozfreddyb_eslint-plugin-scanjs-rules
|
train
|
178af58f4c038eadcc8c62493cd0e74f0027f03b
|
diff --git a/src/python/dxpy/cli/exec_io.py b/src/python/dxpy/cli/exec_io.py
index <HASH>..<HASH> 100644
--- a/src/python/dxpy/cli/exec_io.py
+++ b/src/python/dxpy/cli/exec_io.py
@@ -447,7 +447,7 @@ class ExecutableInputs(object):
input_class = None
if self.input_spec is not None:
- if input_name not in self.input_spec and self._desc['class'] != 'workflow':
+ if input_name not in self.input_spec and self._desc.get('class') != 'workflow':
raise Exception('Input field called ' + input_name + ' was not found in the input spec')
elif input_name in self.input_spec:
input_class = self.input_spec[input_name]['class']
@@ -604,7 +604,7 @@ class ExecutableInputs(object):
except:
raise Exception('An input was found that did not conform to the syntax: -i<input name>=<input value>')
self.add(self.executable._get_input_name(name) if \
- self._desc['class'] == 'workflow' else name, value)
+ self._desc.get('class') == 'workflow' else name, value)
if self.input_spec is None:
for i in self.inputs:
@@ -613,9 +613,9 @@ class ExecutableInputs(object):
# For now, we do not handle prompting for workflow inputs nor
# recognizing when not all inputs haven't been bound
- if sys.stdout.isatty() and self._desc['class'] != 'workflow':
+ if sys.stdout.isatty() and self._desc.get('class') != 'workflow':
self.prompt_for_missing()
- elif self._desc['class'] != 'workflow':
+ elif self._desc.get('class') != 'workflow':
missing_required_inputs = set(self.required_inputs) - set(self.inputs.keys())
if missing_required_inputs:
raise Exception('Some inputs (%s) are missing, and interactive mode is not available' % (', '.join(missing_required_inputs)))
|
Bugfix for dx-run-app-locally compatibility
|
dnanexus_dx-toolkit
|
train
|
dfc2cf96a6c1bea8ab63d045712c5c2599565633
|
diff --git a/cassandra/cluster.py b/cassandra/cluster.py
index <HASH>..<HASH> 100644
--- a/cassandra/cluster.py
+++ b/cassandra/cluster.py
@@ -1456,11 +1456,6 @@ class Cluster(object):
connection = None
try:
connection = self.connection_factory(host.address)
- try:
- self.control_connection.wait_for_schema_agreement(connection)
- except Exception:
- log.debug("Error waiting for schema agreement before preparing statements against host %s", host, exc_info=True)
-
statements = self._prepared_statements.values()
for keyspace, ks_statements in groupby(statements, lambda s: s.keyspace):
if keyspace is not None:
|
don't wait for schema agreement when repreparing on up
PYTHON-<I>
|
datastax_python-driver
|
train
|
d3acb377f5cae3e152cd451e6f96159a3e4f9c88
|
diff --git a/hyperv/neutron/security_groups_driver.py b/hyperv/neutron/security_groups_driver.py
index <HASH>..<HASH> 100755
--- a/hyperv/neutron/security_groups_driver.py
+++ b/hyperv/neutron/security_groups_driver.py
@@ -16,6 +16,7 @@
from eventlet import greenthread
import netaddr
from neutron.agent import firewall
+from os_win import exceptions
from os_win.utils.network import networkutils
from os_win import utilsfactory
from oslo_log import log as logging
@@ -163,6 +164,10 @@ class HyperVSecurityGroupsDriverMixin(object):
try:
self._utils.create_security_rules(port_id, sg_rules)
old_sg_rules.extend(sg_rules)
+ except exceptions.NotFound:
+ # port no longer exists.
+ self._sec_group_rules.pop(port_id, None)
+ raise
except Exception:
LOG.exception(_LE('Exception encountered while adding rules for '
'port: %s'), port_id)
@@ -177,6 +182,10 @@ class HyperVSecurityGroupsDriverMixin(object):
for rule in sg_rules:
if rule in old_sg_rules:
old_sg_rules.remove(rule)
+ except exceptions.NotFound:
+ # port no longer exists.
+ self._sec_group_rules.pop(port_id, None)
+ raise
except Exception:
LOG.exception(_LE('Exception encountered while removing rules for '
'port: %s'), port_id)
diff --git a/hyperv/tests/unit/neutron/test_security_groups_driver.py b/hyperv/tests/unit/neutron/test_security_groups_driver.py
index <HASH>..<HASH> 100644
--- a/hyperv/tests/unit/neutron/test_security_groups_driver.py
+++ b/hyperv/tests/unit/neutron/test_security_groups_driver.py
@@ -273,6 +273,17 @@ class TestHyperVSecurityGroupsDriver(SecurityGroupRuleTestHelper):
self.assertNotIn(mock_rule,
self._driver._sec_group_rules[self._FAKE_ID])
+ def test_add_sg_port_rules_port_not_found(self):
+ self._driver._sec_group_rules[self._FAKE_ID] = []
+ self._driver._utils.create_security_rules.side_effect = (
+ exceptions.NotFound(resource='port_id'))
+
+ self.assertRaises(exceptions.NotFound,
+ self._driver._add_sg_port_rules,
+ self._FAKE_ID, [mock.sentinel.rule])
+
+ self.assertNotIn(self._FAKE_ID, self._driver._sec_group_rules)
+
def test_add_sg_port_rules(self):
mock_rule = mock.MagicMock()
self._driver._sec_group_rules[self._FAKE_ID] = []
@@ -298,6 +309,17 @@ class TestHyperVSecurityGroupsDriver(SecurityGroupRuleTestHelper):
self.assertIn(mock_rule, self._driver._sec_group_rules[self._FAKE_ID])
+ def test_remove_sg_port_rules_port_not_found(self):
+ self._driver._sec_group_rules[self._FAKE_ID] = []
+ self._driver._utils.remove_security_rules.side_effect = (
+ exceptions.NotFound(resource='port_id'))
+
+ self.assertRaises(exceptions.NotFound,
+ self._driver._remove_sg_port_rules,
+ self._FAKE_ID, [mock.sentinel.rule])
+
+ self.assertNotIn(self._FAKE_ID, self._driver._sec_group_rules)
+
def test_remove_sg_port_rules(self):
mock_rule = mock.MagicMock()
self._driver._sec_group_rules[self._FAKE_ID] = [mock_rule]
|
SecurityGroups: clears port SG rule cache if port doesn't exist
If an exceptions.NotFound is raised when binding / removing
security group rules, it means that the port no longer exists.
Clears the port's cached SG rules in this case.
Change-Id: I0ce1c<I>b4a8b<I>f<I>f<I>fd2a<I>e4f<I>bf<I>
Closes-Bug: #<I>
|
openstack_networking-hyperv
|
train
|
29bb75a79e5f01e24720899ded30d3833268952c
|
diff --git a/parthial/built_ins.py b/parthial/built_ins.py
index <HASH>..<HASH> 100644
--- a/parthial/built_ins.py
+++ b/parthial/built_ins.py
@@ -91,3 +91,9 @@ def lisp_cdr(self, ctx, l):
cdr = l.val[1:]
return ctx.env.new(LispList(cdr))
+@built_in(default_globals, 'list', count_args=False)
+def lisp_list(self, ctx, l):
+ if len(l) > 1024:
+ raise LispError('too many items in list')
+ return ctx.env.new(LispList(l))
+
|
Fixed an incredibly stupid typo bug.
|
benzrf_parthial
|
train
|
9431d0d97114564b55b221f017fd8764099b83d0
|
diff --git a/probability.py b/probability.py
index <HASH>..<HASH> 100644
--- a/probability.py
+++ b/probability.py
@@ -87,22 +87,22 @@ class JointProbDist(ProbDist):
>>> P = JointProbDist(['X', 'Y']); P[1, 1] = 0.25
>>> P[1, 1]
0.25
+ >>> P[dict(X=0, Y=1)] = 0.5
+ >>> P[dict(X=0, Y=1)]
+ 0.5
"""
def __init__(self, variables):
update(self, prob={}, variables=variables, vals=DefaultDict([]))
def __getitem__(self, values):
"Given a tuple or dict of values, return P(values)."
- if isinstance(values, dict):
- values = tuple([values[var] for var in self.variables])
- return self.prob[values]
+ return self.prob[event_values(values, self.variables)]
def __setitem__(self, values, p):
"""Set P(values) = p. Values can be a tuple or a dict; it must
have a value for each of the variables in the joint. Also keep track
of the values we have seen so far for each variable."""
- if isinstance(values, dict):
- values = [values[var] for var in self.variables]
+ values = event_values(values, self.variables)
self.prob[values] = p
for var, val in zip(self.variables, values):
if val not in self.vals[var]:
@@ -247,13 +247,16 @@ class BoolCpt:
return (random() <= self.p(True, parents, event))
-def event_values (event, vars):
+def event_values(event, vars):
"""Return a tuple of the values of variables vars in event.
>>> event_values ({'A': 10, 'B': 9, 'C': 8}, ['C', 'A'])
(8, 10)
+ >>> event_values ((1, 2), ['C', 'A'])
+ (1, 2)
"""
-
+ if isinstance(event, tuple) and len(event) == len(vars):
+ return event
return tuple([event[parent] for parent in vars])
|
Fixed type error in ProbDist.__setitem__ and factored out common logic.
|
hobson_aima
|
train
|
b302731a504a7073a7cdfb1b40e0654cac1a40c1
|
diff --git a/packages/cerebral/src/devtools/index.js b/packages/cerebral/src/devtools/index.js
index <HASH>..<HASH> 100644
--- a/packages/cerebral/src/devtools/index.js
+++ b/packages/cerebral/src/devtools/index.js
@@ -42,7 +42,7 @@ class Devtools {
this.controller = null
this.originalRunTreeFunction = null
this.ws = null
- this.isUpdatingDebuggerAfterTabChange = false
+ this.isResettingDebugger = false
this.sendInitial = this.sendInitial.bind(this)
this.sendComponentsMap = debounce(this.sendComponentsMap, 50)
@@ -171,7 +171,10 @@ class Devtools {
this.ws.onopen = () => {
this.ws.send(JSON.stringify({type: 'ping'}))
}
- this.ws.onclose = () => this.reInit()
+ this.ws.onclose = () => {
+ console.warn('You have configured remoteDebugger, but could not connect. Falling back to Chrome extension')
+ this.reInit()
+ }
this.ws.onerror = () => this.reInit()
} else {
const event = new CustomEvent('cerebral2.client.message', {
@@ -195,11 +198,11 @@ class Devtools {
document.addEventListener(visibilityChange, () => {
if (!document[hidden]) {
- this.isUpdatingDebuggerAfterTabChange = true
+ this.isResettingDebugger = true
this.backlog.forEach((message) => {
this.sendMessage(message)
})
- this.isUpdatingDebuggerAfterTabChange = false
+ this.isResettingDebugger = false
}
}, false)
}
@@ -222,7 +225,7 @@ class Devtools {
Sends message to chrome extension or remote debugger
*/
sendMessage (stringifiedMessage) {
- if (this.multipleApps && !this.isUpdatingDebuggerAfterTabChange) {
+ if (this.multipleApps && !this.isResettingDebugger) {
this.backlog.push(stringifiedMessage)
}
@@ -328,17 +331,19 @@ class Devtools {
}
}).replace(`"${PLACEHOLDER_INITIAL_MODEL}"`, this.initialModelString)
- this.isConnected = true
+ this.isResettingDebugger = true
this.sendMessage(message)
-
this.backlog.forEach((backlogItem) => {
this.sendMessage(backlogItem)
})
+ this.isResettingDebugger = false
if (!this.multipleApps) {
this.backlog = []
}
+ this.isConnected = true
+
this.sendMessage(JSON.stringify({
type: 'components',
data: {
diff --git a/packages/todomvc/src/controller.js b/packages/todomvc/src/controller.js
index <HASH>..<HASH> 100644
--- a/packages/todomvc/src/controller.js
+++ b/packages/todomvc/src/controller.js
@@ -7,7 +7,9 @@ import Recorder from './modules/recorder'
const controller = Controller({
options: {strictRender: true},
- devtools: Devtools(),
+ devtools: Devtools({
+ remoteDebugger: 'localhost:8585'
+ }),
router: Router({
onlyHash: true,
routes: {
|
fix(Devtools): fix sending initial backlog (#<I>)
|
cerebral_cerebral
|
train
|
86d5e906d7125c5285c663dc4068ecb9d5a802aa
|
diff --git a/lib/friendly_id/adapters/active_record/slugged_model.rb b/lib/friendly_id/adapters/active_record/slugged_model.rb
index <HASH>..<HASH> 100644
--- a/lib/friendly_id/adapters/active_record/slugged_model.rb
+++ b/lib/friendly_id/adapters/active_record/slugged_model.rb
@@ -224,7 +224,7 @@ module FriendlyId
end
def normalize_friendly_id(string)
- SlugString.new(string).normalize_for!(friendly_id_config).to_s
+ string.normalize_for!(friendly_id_config).to_s
end
def slug
@@ -243,7 +243,7 @@ module FriendlyId
# Get the processed string used as the basis of the friendly id.
def slug_text
- normalize_friendly_id(send(friendly_id_config.method))
+ normalize_friendly_id(SlugString.new(send(friendly_id_config.method)))
end
def slug_text_changed?
diff --git a/test/slugged_model_test.rb b/test/slugged_model_test.rb
index <HASH>..<HASH> 100644
--- a/test/slugged_model_test.rb
+++ b/test/slugged_model_test.rb
@@ -118,7 +118,7 @@ class SluggedModelTest < Test::Unit::TestCase
end
should "not convert to ASCII" do
- post = Post.new(:name => "katakana: ゲコゴサザシジ")
+ post = Post.new(:name => "katakana: ゲコゴサザシジ!")
assert_equal "katakana-ゲコゴサザシジ", post.send(:slug_text)
end
|
Made normalize_friendly_id receive instance of SlugString.
|
norman_friendly_id
|
train
|
02da49597dce2e8206495eb3f778b22126ca6724
|
diff --git a/hugolib/page.go b/hugolib/page.go
index <HASH>..<HASH> 100644
--- a/hugolib/page.go
+++ b/hugolib/page.go
@@ -169,7 +169,7 @@ func (p *Page) setSummary() {
} else {
// If hugo defines split:
// render, strip html, then split
- plain := strings.TrimSpace(p.Plain())
+ plain := strings.Join(strings.Fields(p.Plain()), " ")
p.Summary = helpers.BytesToHTML([]byte(helpers.TruncateWordsToWholeSentence(plain, helpers.SummaryLength)))
p.Truncated = len(p.Summary) != len(plain)
}
|
Fix string comparison for .Truncated page variable
Instead of `strings.TrimSpace()`, use `strings.Join(strings.Fields(s), " ")`
to collapse all whitespaces into single spaces, in order to match the
behaviour of helpers.TruncateWordsToWholeSentence(),
in order to detect non-truncated content correctly.
|
gohugoio_hugo
|
train
|
a8fe54db428e7c059900d3c7f74cd3d6d9c97861
|
diff --git a/sovrin_client/test/cli/conftest.py b/sovrin_client/test/cli/conftest.py
index <HASH>..<HASH> 100644
--- a/sovrin_client/test/cli/conftest.py
+++ b/sovrin_client/test/cli/conftest.py
@@ -1,30 +1,22 @@
import json
import os
import tempfile
-import traceback
-
-import itertools
-from time import sleep
import re
from typing import List
import plenum
import pytest
-from plenum.common.exceptions import BlowUp, ProdableAlreadyAdded, \
- PortNotAvailable
+from plenum.common.exceptions import BlowUp
from plenum.common.log import getlogger
from plenum.common.raet import initLocalKeep
from plenum.common.eventually import eventually
+from plenum.common.roles import Roles
from plenum.test.conftest import tconf, conf, tdirWithPoolTxns, poolTxnData, \
- dirName, tdirWithDomainTxns, poolTxnNodeNames
-from plenum.test.helper import createTempDir, waitUntillPortIsAvailable
-from sovrin_client.agent import agent
-from sovrin_client.agent.agent import runAgent
+ tdirWithDomainTxns, poolTxnNodeNames
from sovrin_client.cli.helper import USAGE_TEXT, NEXT_COMMANDS_TO_TRY_TEXT
-from sovrin_client.test.agent.acme import createAcme
-from sovrin_common.txn import SPONSOR, ENDPOINT, TRUST_ANCHOR
+from sovrin_common.txn import ENDPOINT, TRUST_ANCHOR
from sovrin_node.test.conftest import domainTxnOrderedFields
from sovrin_client.test.helper import createNym, buildStewardClient
@@ -1249,75 +1241,32 @@ def philCli(be, do, philCLI):
return philCLI
-@pytest.fixture(scope="module")
-def faberAddedByPhil(be, do, poolNodesStarted, philCli, connectedToTest,
- nymAddedOut, faberMap):
- be(philCli)
- if not philCli._isConnectedToAnyEnv():
+def addAgent(be, do, userCli, mapper, connectExpMsgs, nymAddExpMsgs):
+ be(userCli)
+ if not userCli._isConnectedToAnyEnv():
do('connect test', within=3,
- expect=connectedToTest)
+ expect=connectExpMsgs)
- do('send NYM dest={target} role=SPONSOR',
+ do('send NYM dest={{target}} role={role}'.format(
+ role=Roles.TRUST_ANCHOR.name),
within=3,
- expect=nymAddedOut, mapper=faberMap)
+ expect=nymAddExpMsgs, mapper=mapper)
return philCli
@pytest.fixture(scope="module")
+def faberAddedByPhil(be, do, poolNodesStarted, philCli, connectedToTest,
+ nymAddedOut, faberMap):
+ return addAgent(be, do, philCli, faberMap, connectedToTest, nymAddedOut)
+
+
+@pytest.fixture(scope="module")
def acmeAddedByPhil(be, do, poolNodesStarted, philCli, connectedToTest,
nymAddedOut, acmeMap):
- be(philCli)
- if not philCli._isConnectedToAnyEnv():
- do('connect test', within=3,
- expect=connectedToTest)
-
- do('send NYM dest={target} role=SPONSOR',
- within=3,
- expect=nymAddedOut, mapper=acmeMap)
- return philCli
+ return addAgent(be, do, philCli, acmeMap, connectedToTest, nymAddedOut)
@pytest.fixture(scope="module")
def thriftAddedByPhil(be, do, poolNodesStarted, philCli, connectedToTest,
nymAddedOut, thriftMap):
- be(philCli)
- if not philCli._isConnectedToAnyEnv():
- do('connect test', within=3,
- expect=connectedToTest)
-
- do('send NYM dest={target} role=SPONSOR',
- within=3,
- expect=nymAddedOut, mapper=thriftMap)
- return philCli
-
-
-# @pytest.fixture(scope="module")
-# def faberRestartedOnSamePort(poolNodesStarted, emptyLooper,
-# tdirWithPoolTxns, faberWallet,
-# faberAddedByPhil, faberAgent):
-# freeupPorts(emptyLooper, [faberAgent.port])
-# with pytest.raises(ProdableAlreadyAdded):
-# runningFaber(emptyLooper, tdirWithPoolTxns,
-# faberWallet, faberAgent, faberAddedByPhil)
-# runningFaber(emptyLooper, tdirWithPoolTxns,
-# faberWallet, faberAgent, faberAddedByPhil)
-#
-# freeupPorts(emptyLooper, [faberAgent.port])
-#
-#
-# @pytest.fixture(scope="module")
-# def acmeRestartedWithUsedPort(looper, poolNodesStarted, emptyLooper,
-# tdirWithPoolTxns, faberWallet, faberAgentPort,
-# faberAddedByPhil, acmeAddedByPhil,
-# faberAgent, acmeWallet):
-# freeupPorts(emptyLooper, [faberAgent.port])
-# runningFaber(emptyLooper, tdirWithPoolTxns, faberWallet, faberAgent,
-# faberAddedByPhil)
-#
-# acmeAgent = createAcme(acmeWallet.name, acmeWallet,
-# basedirpath=tdirWithPoolTxns,
-# port=faberAgentPort)
-#
-# with pytest.raises(PortNotAvailable):
-# runningAcme(emptyLooper, tdirWithPoolTxns, acmeWallet,
-# acmeAgent, acmeAddedByPhil)
+ return addAgent(be, do, philCli, thriftMap, connectedToTest, nymAddedOut)
|
refactored few fixtures to re-use code, removed unused imports
|
hyperledger-archives_indy-client
|
train
|
d59fd3537d9e174e373581d67d6ca20cd4a3ab52
|
diff --git a/findbugs/src/java/edu/umd/cs/findbugs/detect/FindOpenStream.java b/findbugs/src/java/edu/umd/cs/findbugs/detect/FindOpenStream.java
index <HASH>..<HASH> 100644
--- a/findbugs/src/java/edu/umd/cs/findbugs/detect/FindOpenStream.java
+++ b/findbugs/src/java/edu/umd/cs/findbugs/detect/FindOpenStream.java
@@ -62,36 +62,33 @@ public class FindOpenStream implements Detector {
}
public void transferInstruction(InstructionHandle handle, BasicBlock basicBlock) {
- Instruction ins = handle.getInstruction();
- ins.accept(this);
-
+ final Instruction ins = handle.getInstruction();
final ConstantPoolGen cpg = getCPG();
final ResourceValueFrame frame = getFrame();
- final int numSlots = frame.getNumSlots();
+ // Model use of instance values in frame slots
+ ins.accept(this);
+
+ // Is a resource created or closed by this instruction?
Location creationPoint = stream.creationPoint;
if (handle == creationPoint.getHandle() && basicBlock == creationPoint.getBasicBlock()) {
// Resource creation
- frame.setValue(numSlots - 1, ResourceValue.instance());
+ frame.setValue(frame.getNumSlots() - 1, ResourceValue.instance());
frame.setStatus(ResourceValueFrame.OPEN);
} else if (resourceTracker.isResourceClose(basicBlock, handle, cpg, stream)) {
// Resource closed
- frame.setStatus(ResourceValueFrame.OPEN);
+ frame.setStatus(ResourceValueFrame.CLOSED);
}
}
- protected boolean instanceEscapes(InvokeInstruction inv) {
+ protected boolean instanceEscapes(InvokeInstruction inv, int instanceArgNum) {
ConstantPoolGen cpg = getCPG();
String className = inv.getClassName(cpg);
- try {
- // FIXME: is this right?
- return !Repository.instanceOf(className, "java.io.InputStream");
- } catch (ClassNotFoundException e) {
- bugReporter.reportMissingClass(e);
- return true;
- }
+ boolean escapes = (inv.getOpcode() == Constants.INVOKESTATIC || instanceArgNum != 0);
+ //if (escapes) System.out.println("Escape at " + inv + " argNum=" + instanceArgNum);
+ return escapes;
}
}
@@ -109,11 +106,22 @@ public class FindOpenStream implements Detector {
Type type = newIns.getType(cpg);
String sig = type.getSignature();
- // TODO: make this more general, to handle all input and output streams
- if (sig.equals("Ljava/io/FileInputStream;"))
- return new Stream(new Location(handle, basicBlock), "java.io.FileInputStream");
- else
+ if (!sig.startsWith("L") || !sig.endsWith(";"))
+ return null;
+
+ // Track any subclass of InputStream or OutputStream
+ // (but not ByteArray variants)
+ String className = sig.substring(1, sig.length() - 1).replace('/', '.');
+ if (className.startsWith("ByteArray"))
return null;
+ try {
+ boolean isStream = Repository.instanceOf(className, "java.io.InputStream")
+ || Repository.instanceOf(className, "java.io.OutputStream");
+ return isStream ? new Stream(new Location(handle, basicBlock), className) : null;
+ } catch (ClassNotFoundException e) {
+ bugReporter.reportMissingClass(e);
+ return null;
+ }
}
public boolean isResourceClose(BasicBlock basicBlock, InstructionHandle handle, ConstantPoolGen cpg, Stream resource) {
@@ -169,7 +177,7 @@ public class FindOpenStream implements Detector {
BitSet bytecodeSet = classContext.getBytecodeSet(method);
if (!bytecodeSet.get(Constants.NEW))
- continue;
+ continue; // no streams created in this method
MethodGen methodGen = classContext.getMethodGen(method);
CFG cfg = classContext.getCFG(method);
|
Changed escape detection using the instance argument number - if the
method is static or if the instance is passed as anything other than
arg 0, then it escapes. Changed so all objects of types derived
from java.io.InputStream and java.io.OutputStream are checked,
except for the ByteArray variants.
git-svn-id: <URL>
|
spotbugs_spotbugs
|
train
|
efc269250a1df95a32232eeea370b37e3911cb71
|
diff --git a/pyemma/plots/thermo.py b/pyemma/plots/thermo.py
index <HASH>..<HASH> 100644
--- a/pyemma/plots/thermo.py
+++ b/pyemma/plots/thermo.py
@@ -88,7 +88,7 @@ def plot_convergence_info(thermo_estimator, axes=None):
def plot_memm_implied_timescales(thermo_estimators,
ax=None, nits=None, therm_state=None, xlog=False, ylog=True, units='steps', dt=1.0, refs=None,
- annotate=True):
+ annotate=True, **kwargs):
colors = ['blue', 'red', 'green', 'cyan', 'purple', 'orange', 'violet']
# Check units and dt for user error.
if isinstance(units, list) and len(units) != 2:
@@ -124,7 +124,7 @@ def plot_memm_implied_timescales(thermo_estimators,
srt = _np.argsort(lags)
# Plot the implied timescales
for i in range(ts.shape[1]):
- ax.plot(lags[srt], ts[srt, i], '-o', color=colors[i % len(colors)])
+ ax.plot(lags[srt], ts[srt, i], color=colors[i % len(colors)], **kwargs)
# Set boundaries
ax.set_xlim([lags.min() * dt[0], lags.max() * dt[0]])
# Plot cutoff
|
[thermo] adding **kwargs to plot_memm_implied_timescales()
|
markovmodel_PyEMMA
|
train
|
f7ed7f127d90de7a3fb37ed6cac33175d9badace
|
diff --git a/tests/explainers/test_tree.py b/tests/explainers/test_tree.py
index <HASH>..<HASH> 100644
--- a/tests/explainers/test_tree.py
+++ b/tests/explainers/test_tree.py
@@ -208,15 +208,15 @@ def test_pyspark_classifier_decision_tree():
from pyspark.ml.classification import RandomForestClassifier, DecisionTreeClassifier, GBTClassifier
import pandas as pd
import pickle
+
+ iris_sk = sklearn.datasets.load_iris()
+ iris = pd.DataFrame(data= np.c_[iris_sk['data'], iris_sk['target']], columns= iris_sk['feature_names'] + ['target'])[:100]
+ spark = SparkSession.builder.config(conf=SparkConf().set("spark.master", "local[*]")).getOrCreate()
except:
print("Skipping test_pyspark_classifier_decision_tree!")
return
import shap
- iris_sk = sklearn.datasets.load_iris()
- iris = pd.DataFrame(data= np.c_[iris_sk['data'], iris_sk['target']], columns= iris_sk['feature_names'] + ['target'])[:100]
- spark = SparkSession.builder.config(conf=SparkConf().set("spark.master", "local[*]")).getOrCreate()
-
col = ["sepal_length","sepal_width","petal_length","petal_width","type"]
iris = spark.createDataFrame(iris, col)
iris = VectorAssembler(inputCols=col[:-1],outputCol="features").transform(iris)
@@ -259,15 +259,15 @@ def test_pyspark_regression_decision_tree():
from pyspark.ml.feature import VectorAssembler, StringIndexer
from pyspark.ml.regression import DecisionTreeRegressor, GBTRegressor, RandomForestRegressor
import pandas as pd
+
+ iris_sk = sklearn.datasets.load_iris()
+ iris = pd.DataFrame(data= np.c_[iris_sk['data'], iris_sk['target']], columns= iris_sk['feature_names'] + ['target'])[:100]
+ spark = SparkSession.builder.config(conf=SparkConf().set("spark.master", "local[*]")).getOrCreate()
except:
print("Skipping test_pyspark_regression_decision_tree!")
return
import shap
- iris_sk = sklearn.datasets.load_iris()
- iris = pd.DataFrame(data= np.c_[iris_sk['data'], iris_sk['target']], columns= iris_sk['feature_names'] + ['target'])[:100]
- spark = SparkSession.builder.config(conf=SparkConf().set("spark.master", "local[*]")).getOrCreate()
-
# Simple regressor: try to predict sepal length based on the other features
col = ["sepal_length","sepal_width","petal_length","petal_width","type"]
iris = spark.createDataFrame(iris, col).drop("type")
|
Skip pyspark tests when pyspark fails to load
|
slundberg_shap
|
train
|
bd42a1e546b26317a4d3a1010fd111c230c65ec6
|
diff --git a/tests/streambase.py b/tests/streambase.py
index <HASH>..<HASH> 100755
--- a/tests/streambase.py
+++ b/tests/streambase.py
@@ -210,15 +210,21 @@ class TestReceiverSelect(ReceiverSelectTestCase):
self.client.write(C2S_CLIENT_STREAM_HEAD)
self.wait_short(0.2)
self.client.write("</stream:test>")
+ logger.debug("waiting for exception...")
with self.assertRaises(StreamParseError):
self.wait()
+ logger.debug(" got it!")
self.assertFalse(self.stream.is_connected())
self.wait_short(0.1)
+ logger.debug("waiting for connection close...")
self.client.wait(1)
+ logger.debug(" done")
self.assertTrue(self.client.eof)
self.assertTrue(self.client.rdata.endswith(PARSE_ERROR_RESPONSE))
self.client.close()
+ logger.debug("final wait...")
self.wait()
+ logger.debug(" done")
event_classes = [e.__class__ for e in handler.events_received]
# when exception was raised by a thread DisconnectedEvent won't
|
More debug logs for streambase.py test
|
Jajcus_pyxmpp2
|
train
|
cf040f2224e5b3ac4809c7967cee3f9c362b8cf4
|
diff --git a/lib/origami/pdf.rb b/lib/origami/pdf.rb
index <HASH>..<HASH> 100644
--- a/lib/origami/pdf.rb
+++ b/lib/origami/pdf.rb
@@ -392,7 +392,7 @@ module Origami
# Looking for an object present at a specified file offset.
#
def get_object_by_offset(offset) #:nodoc:
- self.indirect_objects.find { |obj| obj.file_offset == offset }
+ self.each_object.find { |obj| obj.file_offset == offset }
end
#
@@ -676,7 +676,7 @@ module Origami
startxref = @header.to_s.size
@revisions.each do |revision|
- revision.objects.each do |object|
+ revision.each_object do |object|
startxref += object.to_s.size
end
@@ -788,7 +788,7 @@ module Origami
#
def output(params = {})
- has_objstm = self.indirect_objects.any?{|obj| obj.is_a?(ObjectStream)}
+ has_objstm = self.each_object.any?{|obj| obj.is_a?(ObjectStream)}
options =
{
@@ -1037,7 +1037,7 @@ module Origami
startxref = @header.to_s.size
@revisions.each do |revision|
- revision.objects.each do |object|
+ revision.each_object do |object|
startxref += object.to_s.size
end
|
pdf: replace some unnecessary arrays by enumerators
|
gdelugre_origami
|
train
|
065d8066b728fdfe5af1a52735aa0b31791bd5a5
|
diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/description/method/MethodDescription.java b/byte-buddy-dep/src/main/java/net/bytebuddy/description/method/MethodDescription.java
index <HASH>..<HASH> 100644
--- a/byte-buddy-dep/src/main/java/net/bytebuddy/description/method/MethodDescription.java
+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/description/method/MethodDescription.java
@@ -1732,8 +1732,9 @@ public interface MethodDescription extends TypeVariableSource,
*
* @return This token's parameter types.
*/
+ @SuppressWarnings("unchecked")
public List<TypeDescription> getParameterTypes() {
- return new ArrayList<TypeDescription>(parameterTypes);
+ return (List<TypeDescription>) parameterTypes;
}
/**
@@ -1746,6 +1747,14 @@ public interface MethodDescription extends TypeVariableSource,
}
@Override
+ public int hashCode() {
+ int result = name.hashCode();
+ result = 31 * result + returnType.hashCode();
+ result = 31 * result + parameterTypes.hashCode();
+ return result;
+ }
+
+ @Override
public boolean equals(Object other) {
if (this == other) {
return true;
@@ -1759,14 +1768,6 @@ public interface MethodDescription extends TypeVariableSource,
}
@Override
- public int hashCode() {
- int result = name.hashCode();
- result = 31 * result + returnType.hashCode();
- result = 31 * result + parameterTypes.hashCode();
- return result;
- }
-
- @Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder().append(returnType).append(' ').append(name).append('(');
boolean first = true;
@@ -1822,8 +1823,16 @@ public interface MethodDescription extends TypeVariableSource,
*
* @return This token's parameter types.
*/
+ @SuppressWarnings("unchecked")
public List<TypeDescription> getParameterTypes() {
- return new ArrayList<TypeDescription>(parameterTypes);
+ return (List<TypeDescription>) parameterTypes;
+ }
+
+ @Override
+ public int hashCode() {
+ int result = returnType.hashCode();
+ result = 31 * result + parameterTypes.hashCode();
+ return result;
}
@Override
@@ -1838,13 +1847,6 @@ public interface MethodDescription extends TypeVariableSource,
}
@Override
- public int hashCode() {
- int result = returnType.hashCode();
- result = 31 * result + parameterTypes.hashCode();
- return result;
- }
-
- @Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder().append('(');
for (TypeDescription parameterType : parameterTypes) {
diff --git a/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/MethodGraph.java b/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/MethodGraph.java
index <HASH>..<HASH> 100644
--- a/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/MethodGraph.java
+++ b/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/MethodGraph.java
@@ -621,12 +621,18 @@ public interface MethodGraph {
private final MethodDescription.TypeToken typeToken;
/**
+ * The hash code of this token which is precomputed for to improve performance.
+ */
+ private final int hashCode;
+
+ /**
* Creates a new type token for a Java method.
*
* @param typeToken The represented type token.
*/
protected Token(MethodDescription.TypeToken typeToken) {
this.typeToken = typeToken;
+ hashCode = typeToken.getParameterTypes().hashCode();
}
@Override
@@ -636,7 +642,7 @@ public interface MethodGraph {
@Override
public int hashCode() {
- return typeToken.getParameterTypes().hashCode();
+ return hashCode;
}
@Override
@@ -672,12 +678,18 @@ public interface MethodGraph {
private final MethodDescription.TypeToken typeToken;
/**
+ * The hash code of this token which is precomputed for to improve performance.
+ */
+ private final int hashCode;
+
+ /**
* Creates a new type token for a JVM method.
*
* @param typeToken The represented type token.
*/
public Token(MethodDescription.TypeToken typeToken) {
this.typeToken = typeToken;
+ hashCode = typeToken.getReturnType().hashCode() + 31 * typeToken.getParameterTypes().hashCode();
}
@Override
@@ -694,7 +706,7 @@ public interface MethodGraph {
@Override
public int hashCode() {
- return typeToken.getReturnType().hashCode() + 31 * typeToken.getParameterTypes().hashCode();
+ return hashCode;
}
@Override
|
Cache the hash code of tokens to avoid unneccessary recalculation.
|
raphw_byte-buddy
|
train
|
3e93ce2ba16292fa5007df653436964a2c90cd45
|
diff --git a/lib/sheepsafe/config.rb b/lib/sheepsafe/config.rb
index <HASH>..<HASH> 100644
--- a/lib/sheepsafe/config.rb
+++ b/lib/sheepsafe/config.rb
@@ -3,8 +3,8 @@ require 'yaml'
module Sheepsafe
class Config
FILE = File.expand_path('~/.sheepsafe/sheepsafe.yml')
- DEFAULT_CONFIG = {"untrusted_location" => "Untrusted", "socks_port" => "9999", "trust_encrypted?" => "false"}
- ATTRS = %w(trusted_location untrusted_location last_network ssh_host ssh_port socks_port trust_encrypted?)
+ DEFAULT_CONFIG = {"untrusted_location" => "Untrusted", "socks_port" => "9999", "trust_encrypted?" => "false", "disabled" => "false"}
+ ATTRS = %w(trusted_location untrusted_location last_network ssh_host ssh_port socks_port trust_encrypted? disabled)
ARRAY_ATTRS = %w(trusted_names untrusted_names)
def self.load_config
diff --git a/lib/sheepsafe/controller.rb b/lib/sheepsafe/controller.rb
index <HASH>..<HASH> 100644
--- a/lib/sheepsafe/controller.rb
+++ b/lib/sheepsafe/controller.rb
@@ -35,13 +35,21 @@ module Sheepsafe
def run
log("Sheepsafe starting")
- if ARGV.first == 'proxy' # 'sheepsafe proxy up/down/kick'
+ case ARGV.first
+ when 'proxy' # 'sheepsafe proxy up/down/kick'
bring_socks_proxy ARGV[1]
return
+ when 'enable', 'disable'
+ @config.disabled = (ARGV.first == 'disable')
+ @config.write
+ return
end
# Always recycle the proxy server on network changes
bring_socks_proxy 'down'
+
+ return if @config.disabled
+
if network_up?
if network_changed?
if switch_to_trusted?
diff --git a/spec/sheepsafe_spec.rb b/spec/sheepsafe_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/sheepsafe_spec.rb
+++ b/spec/sheepsafe_spec.rb
@@ -4,7 +4,7 @@ require 'sheepsafe'
describe Sheepsafe::Controller do
let(:config) do
double("config", :trusted_location => "trusted_location", :untrusted_location => "untrusted_location",
- :last_network= => nil, :write => nil)
+ :last_network= => nil, :write => nil, :disabled => nil)
end
let (:network) do
@@ -72,6 +72,15 @@ describe Sheepsafe::Controller do
end
end
+ context "disabled in config" do
+ it "does nothing" do
+ config.stub :disabled => true
+ controller.should_receive(:bring_socks_proxy).with('down')
+ config.should_not_receive(:write)
+ controller.run
+ end
+ end
+
context "network changed" do
before :each do
controller.stub(:network_changed? => true, :switch_to_trusted? => false,
|
Enable/disable without uninstalling
|
nicksieger_sheepsafe
|
train
|
a4f7d0f3218427787a7af7c9f8d02baa88926b8a
|
diff --git a/src/Gregwar/Captcha/CaptchaBuilder.php b/src/Gregwar/Captcha/CaptchaBuilder.php
index <HASH>..<HASH> 100644
--- a/src/Gregwar/Captcha/CaptchaBuilder.php
+++ b/src/Gregwar/Captcha/CaptchaBuilder.php
@@ -26,7 +26,7 @@ class CaptchaBuilder implements CaptchaBuilderInterface
/**
* @var array
*/
- protected $textColor = null;
+ protected $textColor = array();
/**
* @var array
|
php7 error: Parameter must be an array or an object that implements Countable in CaptchaBuilder.php on line <I>
I got this error using xampp with php7 under windows <I> <I>bit.
Parameter must be an array or an object that implements Countable in CaptchaBuilder.php on line <I>
I fixed it by declaring $textColor as array() at line <I>.
|
Gregwar_Captcha
|
train
|
cf52020f8caa48635f511479cfecafbf4065abd2
|
diff --git a/spec/PHPeg/Generator/ToClassVisitorSpec.php b/spec/PHPeg/Generator/ToClassVisitorSpec.php
index <HASH>..<HASH> 100644
--- a/spec/PHPeg/Generator/ToClassVisitorSpec.php
+++ b/spec/PHPeg/Generator/ToClassVisitorSpec.php
@@ -119,7 +119,10 @@ EOS;
function it_should_create_a_grammar_from_a_node()
{
$grammarNode = new GrammarNode('FooFile', 'Foo', array(new RuleNode('Foo', new RuleReferenceNode('Bar'))));
+ $grammarNode->setNamespace('Acme\\Factory');
$grammarCode = <<<EOS
+namespace Acme\Factory;
+
class FooFile implements \PHPeg\ParserInterface
{
protected \$string;
diff --git a/src/PHPeg/Generator/ToClassVisitor.php b/src/PHPeg/Generator/ToClassVisitor.php
index <HASH>..<HASH> 100644
--- a/src/PHPeg/Generator/ToClassVisitor.php
+++ b/src/PHPeg/Generator/ToClassVisitor.php
@@ -124,7 +124,17 @@ EOS;
public function visitGrammar(GrammarNode $node)
{
- $result = <<<EOS
+ $result = '';
+
+ if ($node->getNamespace() !== null) {
+ $result .= <<<EOS
+namespace {$node->getNamespace()};
+
+
+EOS;
+ }
+
+ $result .= <<<EOS
class {$node->getName()} implements \PHPeg\ParserInterface
{
protected \$string;
|
Added namespaces to generated parser code
|
scato_phpeg
|
train
|
2657975489cb37257c339a78bc16d5e63af5085f
|
diff --git a/src/adapt/viewer.js b/src/adapt/viewer.js
index <HASH>..<HASH> 100644
--- a/src/adapt/viewer.js
+++ b/src/adapt/viewer.js
@@ -182,9 +182,16 @@ adapt.viewer.Viewer.prototype.loadEPUB = function(command) {
self.opf = opf;
self.opf.resolveFragment(fragment).then(function(position) {
self.pagePosition = position;
- self.resize().then(function() {
- vivliostyle.profile.profiler.registerEndTiming("loadEPUB");
- self.callback({"t":"loaded", "metadata": self.opf.getMetadata()});
+ self.resize().then(function(task) {
+ function loaded() {
+ vivliostyle.profile.profiler.registerEndTiming("loadEPUB");
+ self.callback({"t":"loaded", "metadata": self.opf.getMetadata()});
+ }
+ if (task) {
+ task.whenDone(loaded);
+ } else {
+ loaded();
+ }
frame.finish(true);
});
});
@@ -237,9 +244,16 @@ adapt.viewer.Viewer.prototype.loadXML = function(command) {
self.opf.initWithChapters(resolvedParams, doc).then(function() {
self.opf.resolveFragment(fragment).then(function(position) {
self.pagePosition = position;
- self.resize().then(function() {
- vivliostyle.profile.profiler.registerEndTiming("loadXML");
- self.callback({"t":"loaded"});
+ self.resize().then(function(task) {
+ function loaded() {
+ vivliostyle.profile.profiler.registerEndTiming("loadXML");
+ self.callback({"t":"loaded"});
+ }
+ if (task) {
+ task.whenDone(loaded);
+ } else {
+ loaded();
+ }
frame.finish(true);
});
});
@@ -633,16 +647,16 @@ adapt.viewer.Viewer.prototype.queryZoomFactor = function(type) {
};
/**
- * @return {!adapt.task.Result.<boolean>}
+ * @return {!adapt.task.Result.<?adapt.task.Task>}
*/
adapt.viewer.Viewer.prototype.resize = function() {
this.needResize = false;
if (this.sizeIsGood()) {
- return adapt.task.newResult(true);
+ return adapt.task.newResult(/** @type {?adapt.task.Task} */ (null));
}
var self = this;
this.setReadyState(vivliostyle.constants.ReadyState.LOADING);
- adapt.task.currentTask().getScheduler().run(function() {
+ var task = adapt.task.currentTask().getScheduler().run(function() {
/** @type {!adapt.task.Frame.<boolean>} */ var frame = adapt.task.newFrame("resize");
self.reset();
@@ -671,7 +685,7 @@ adapt.viewer.Viewer.prototype.resize = function() {
});
return frame.result();
});
- return adapt.task.newResult(true);
+ return adapt.task.newResult(task);
};
/**
|
Fix timing of 'loaded' event
- 'loaded' event is fired after the rendering task is done, which is returned from `resize` method.
|
vivliostyle_vivliostyle.js
|
train
|
3969011f7f4c9cbc18e66a920fe2707399e67bc5
|
diff --git a/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php b/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php
+++ b/src/Symfony/Component/Routing/Tests/Generator/UrlGeneratorTest.php
@@ -175,7 +175,7 @@ class UrlGeneratorTest extends \PHPUnit_Framework_TestCase
public function testGenerateForRouteWithInvalidOptionalParameterNonStrictWithLogger()
{
- if (!class_exists('Symfony\Component\HttpKernel\Log\LoggerInterface')) {
+ if (!interface_exists('Symfony\Component\HttpKernel\Log\LoggerInterface')) {
$this->markTestSkipped('The "HttpKernel" component is not available');
}
|
[Routing] fixed a test
|
symfony_symfony
|
train
|
dd49e370f4c3e30a4d346ad0d445c0e185c81292
|
diff --git a/lib/softlayer/NetworkMonitor.rb b/lib/softlayer/NetworkMonitor.rb
index <HASH>..<HASH> 100644
--- a/lib/softlayer/NetworkMonitor.rb
+++ b/lib/softlayer/NetworkMonitor.rb
@@ -20,6 +20,17 @@ module SoftLayer
# This struct represents a network monitor query result that shows the last
# state of the network monitor
class NetworkMonitorQueryResult < Struct.new(:finished_at, :responded_in, :response_status)
+ ##
+ # This constant is a mapping of network monitor query result statuses to descriptions
+ QUERY_RESULT_STATUS_DESCRIPTIONS = {
+ 0 => "Down/Critical: Server is down and/or has passed the critical response threshold (extremely long ping response, abnormal behavior, etc.).",
+ 1 => "Warning - Server may be recovering from a previous down state, or may have taken too long to respond.",
+ 2 => "Up",
+ 3 => "Not used",
+ 4 => "Unknown - An unknown error has occurred. If the problem persists, contact support.",
+ 5 => "Unknown - An unknown error has occurred. If the problem persists, contact support."
+ }
+
def initialize(query_result_data)
self.finished_at = query_result_data['finishTime']
self.responded_in = query_result_data['responseTime']
@@ -60,15 +71,6 @@ module SoftLayer
class NetworkMonitor < ModelBase
include ::SoftLayer::DynamicAttribute
- QUERY_RESULT_DESCRIPTIONS = {
- 0 => "Down/Critical: Server is down and/or has passed the critical response threshold (extremely long ping response, abnormal behavior, etc.).",
- 1 => "Warning - Server may be recovering from a previous down state, or may have taken too long to respond.",
- 2 => "Up",
- 3 => "Not used",
- 4 => "Unknown - An unknown error has occurred. If the problem persists, contact support.",
- 5 => "Unknown - An unknown error has occurred. If the problem persists, contact support."
- }
-
@@available_query_types = nil
@@available_response_types = nil
diff --git a/lib/softlayer/Server.rb b/lib/softlayer/Server.rb
index <HASH>..<HASH> 100644
--- a/lib/softlayer/Server.rb
+++ b/lib/softlayer/Server.rb
@@ -55,7 +55,8 @@ module SoftLayer
##
# The maximum network monitor query/response levels currently supported by the server
- #
+ # :call-seq:
+ # network_monitor_levels(force_update=false)
sl_dynamic_attr :network_monitor_levels do |resource|
resource.should_update? do
@network_monitor_levels == nil
@@ -68,7 +69,8 @@ module SoftLayer
##
# A lsst of configured network monitors.
- #
+ # :call-seq:
+ # network_monitors(force_update=false)
sl_dynamic_attr :network_monitors do |resource|
resource.should_update? do
@network_monitors == nil
@@ -88,6 +90,8 @@ module SoftLayer
##
# :attr_reader:
# The list of user customers notified on monitoring failures
+ # :call-seq:
+ # notified_network_monitor_users(force_update=false)
sl_dynamic_attr :notified_network_monitor_users do |resource|
resource.should_update? do
#only retrieved once per instance
|
Fix rdoc in Server for Network Monitor attributes and move the query result status descriptions into its respective class
|
softlayer_softlayer-ruby
|
train
|
d4e69454b4f9f4fcf607805eb3db0e7b52b7194b
|
diff --git a/src/node.js b/src/node.js
index <HASH>..<HASH> 100644
--- a/src/node.js
+++ b/src/node.js
@@ -97,8 +97,11 @@ const Node = AsyncInit.compose({
}
this.api = client.api
- const { nodeRevision: revision, genesisKeyBlockHash: genesisHash, networkId, protocols } = await this.api.getStatus()
- this.consensusProtocolVersion = await this.getConsensusProtocolVersion(protocols)
+ const {
+ nodeRevision: revision, genesisKeyBlockHash: genesisHash, networkId,
+ protocols, topBlockHeight
+ } = await this.api.getStatus()
+ this.consensusProtocolVersion = await this.getConsensusProtocolVersion(protocols, topBlockHeight)
this.nodeNetworkId = networkId
return Object.assign(this, { revision, genesisHash })
},
|
perf: take current height from status response
|
aeternity_aepp-sdk-js
|
train
|
59c0afc203366049dfb4d45dff75903f16d544f6
|
diff --git a/taxi_zebra/backend.py b/taxi_zebra/backend.py
index <HASH>..<HASH> 100755
--- a/taxi_zebra/backend.py
+++ b/taxi_zebra/backend.py
@@ -192,7 +192,7 @@ class ZebraBackend(BaseBackend):
projects_list = []
date_attrs = ('start_date', 'end_date')
- for project in projects['data']:
+ for project in projects['data']['list'].values():
team = str(project['circle_id']) if project['circle_id'] else None
p = Project(project['id'], project['name'],
Project.STATUS_ACTIVE, project['description'],
|
Adapt code to new projects endpoint structure
|
sephii_taxi-zebra
|
train
|
60dcbc29418efde13e7eb86f71ebff1256b6638e
|
diff --git a/composer.json b/composer.json
index <HASH>..<HASH> 100644
--- a/composer.json
+++ b/composer.json
@@ -21,7 +21,7 @@
},
"require-dev": {
"phpunit/phpunit": "^7.0",
- "nyholm/psr7": "^1.0",
+ "nyholm/psr7": "^1.3",
"nyholm/nsa": "^1.1"
},
"autoload": {
diff --git a/src/ServerRequestCreator.php b/src/ServerRequestCreator.php
index <HASH>..<HASH> 100644
--- a/src/ServerRequestCreator.php
+++ b/src/ServerRequestCreator.php
@@ -65,6 +65,11 @@ final class ServerRequestCreator implements ServerRequestCreatorInterface
$serverRequest = $this->serverRequestFactory->createServerRequest($method, $uri, $server);
foreach ($headers as $name => $value) {
+ // Because PHP automatically casts array keys set with numeric strings to integers, we have to make sure
+ // that numeric headers will not be sent along as integers, as withAddedHeader can only accept strings.
+ if (\is_int($name)) {
+ $name = (string) $name;
+ }
$serverRequest = $serverRequest->withAddedHeader($name, $value);
}
@@ -237,6 +242,8 @@ final class ServerRequestCreator implements ServerRequestCreatorInterface
* Create a new uri from server variable.
*
* @param array $server typically $_SERVER or similar structure
+ *
+ * @return UriInterface
*/
private function createUriFromArray(array $server): UriInterface
{
diff --git a/tests/ServerRequestCreatorTest.php b/tests/ServerRequestCreatorTest.php
index <HASH>..<HASH> 100644
--- a/tests/ServerRequestCreatorTest.php
+++ b/tests/ServerRequestCreatorTest.php
@@ -323,6 +323,16 @@ class ServerRequestCreatorTest extends TestCase
$this->creator->fromArrays(['REQUEST_METHOD' => 'POST'], [], [], [], [], ['test' => 'something']);
}
+ public function testNumericHeaderFromHeaderArray()
+ {
+ $server = [
+ 'REQUEST_METHOD' => 'GET',
+ ];
+
+ $server = $this->creator->fromArrays($server, ['1234' => 'NumericHeader']);
+ $this->assertEquals(['1234' => ['NumericHeader']], $server->getHeaders());
+ }
+
public function testFromArrays()
{
$server = [
@@ -336,6 +346,8 @@ class ServerRequestCreatorTest extends TestCase
'REQUEST_TIME' => 'Request start time: 1280149029',
'QUERY_STRING' => 'id=10&user=foo',
'DOCUMENT_ROOT' => '/path/to/your/server/root/',
+ 'HTTP_0' => 'NumericHeaderZero',
+ 'HTTP_1234' => 'NumericHeader',
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'HTTP_ACCEPT_ENCODING' => 'gzip,deflate',
@@ -419,6 +431,8 @@ class ServerRequestCreatorTest extends TestCase
'REQUEST_TIME' => 'Request start time: 1280149029',
'QUERY_STRING' => 'id=10&user=foo',
'DOCUMENT_ROOT' => '/path/to/your/server/root/',
+ 'HTTP_0' => 'NumericHeaderZero',
+ 'HTTP_1234' => 'NumericHeader',
'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'HTTP_ACCEPT_ENCODING' => 'gzip,deflate',
@@ -497,6 +511,8 @@ class ServerRequestCreatorTest extends TestCase
public function testMarshalsExpectedHeadersFromServerArray()
{
$server = [
+ 'HTTP_0' => 'NumericHeaderZero',
+ 'HTTP_1234' => 'NumericHeader',
'HTTP_COOKIE' => 'COOKIE',
'HTTP_AUTHORIZATION' => 'token',
'HTTP_CONTENT_TYPE' => 'application/json',
@@ -507,6 +523,8 @@ class ServerRequestCreatorTest extends TestCase
];
$expected = [
+ '0' => 'NumericHeaderZero',
+ '1234' => 'NumericHeader',
'cookie' => 'COOKIE',
'authorization' => 'token',
'content-type' => 'application/json',
|
Added support for numeric headers (#<I>)
* Added support for numeric headers
* PHPdoc
require ^<I> of psr7 for tests to pass
|
Nyholm_psr7-server
|
train
|
c36388c60481fb82f16520e3f8e8075e4b255633
|
diff --git a/src/Php70/Php70.php b/src/Php70/Php70.php
index <HASH>..<HASH> 100644
--- a/src/Php70/Php70.php
+++ b/src/Php70/Php70.php
@@ -60,7 +60,7 @@ final class Php70
restore_error_handler();
}
- public static function intArg($value, $caller, $pos)
+ private static function intArg($value, $caller, $pos)
{
if (is_int($value)) {
return $value;
|
Php<I>: do not expose intArg
intArg is used from Php<I> only. make it private
|
symfony_polyfill
|
train
|
a4c3f5e249749b862a34a1ffb43098a2221bd6aa
|
diff --git a/claripy/fp.py b/claripy/fp.py
index <HASH>..<HASH> 100644
--- a/claripy/fp.py
+++ b/claripy/fp.py
@@ -134,7 +134,13 @@ class FPV(BackendObject):
@normalize_types
@compare_sorts
def __div__(self, o):
- return FPV(self.value / o.value, self.sort)
+ try:
+ return FPV(self.value / o.value, self.sort)
+ except ZeroDivisionError:
+ if str(self.value * o.value)[0] == '-':
+ return FPV(float('-inf'), self.sort)
+ else:
+ return FPV(float('inf'), self.sort)
#
# Reverse arithmetic stuff
|
account for concrete FP ZeroDivisionError
|
angr_claripy
|
train
|
b90c048804d3390f746fcceec9d7c43ba6570b74
|
diff --git a/command/image/build.go b/command/image/build.go
index <HASH>..<HASH> 100644
--- a/command/image/build.go
+++ b/command/image/build.go
@@ -59,6 +59,7 @@ type buildOptions struct {
compress bool
securityOpt []string
networkMode string
+ squash bool
}
// NewBuildCommand creates a new `docker build` command
@@ -110,6 +111,10 @@ func NewBuildCommand(dockerCli *command.DockerCli) *cobra.Command {
command.AddTrustedFlags(flags, true)
+ if dockerCli.HasExperimental() {
+ flags.BoolVar(&options.squash, "squash", false, "Squash newly built layers into a single new layer")
+ }
+
return cmd
}
@@ -305,6 +310,7 @@ func runBuild(dockerCli *command.DockerCli, options buildOptions) error {
CacheFrom: options.cacheFrom,
SecurityOpt: options.securityOpt,
NetworkMode: options.networkMode,
+ Squash: options.squash,
}
response, err := dockerCli.Client().ImageBuild(ctx, body, buildOptions)
|
Adds ability to squash image after build
Allow built images to be squash to scratch.
Squashing does not destroy any images or layers, and preserves the
build cache.
Introduce a new CLI argument --squash to docker build
Introduce a new param to the build API endpoint `squash`
Once the build is complete, docker creates a new image loading the diffs
from each layer into a single new layer and references all the parent's
layers.
|
docker_cli
|
train
|
1b294cc4c11c55948d5b5d5f3192170c47df5fa6
|
diff --git a/src/main/java/water/api/GLMProgressPage.java b/src/main/java/water/api/GLMProgressPage.java
index <HASH>..<HASH> 100644
--- a/src/main/java/water/api/GLMProgressPage.java
+++ b/src/main/java/water/api/GLMProgressPage.java
@@ -400,7 +400,7 @@ public class GLMProgressPage extends Request {
);
sb.append("var dataset = [");
- if(xval != null && xval._cm != null) {
+ if(xval != null && xval._cm != null && xval._fprs != null && xval._tprs != null) {
for(int c = 0; c < xval._cm.length; c++) {
if (c == 0) {
sb.append("["+String.valueOf(xval._fprs[c])+",").append(String.valueOf(xval._tprs[c])).append("]");
|
Fix for PUB-<I>. Forgot 2 more null checks.
|
h2oai_h2o-2
|
train
|
125a444bbd7c9e8cde2d29783ba232b5389760a0
|
diff --git a/lib/ffi_yajl/ffi/encoder.rb b/lib/ffi_yajl/ffi/encoder.rb
index <HASH>..<HASH> 100644
--- a/lib/ffi_yajl/ffi/encoder.rb
+++ b/lib/ffi_yajl/ffi/encoder.rb
@@ -88,7 +88,7 @@ end
class TrueClass
def ffi_yajl(yajl_gen, state)
- if ( status = FFI_Yajl.yajl_gen_bool(yajl_gen, 0) ) != 0
+ if ( status = FFI_Yajl.yajl_gen_bool(yajl_gen, 1) ) != 0
FFI_Yajl::Encoder.raise_error_for_status(status)
end
end
@@ -96,7 +96,7 @@ end
class FalseClass
def ffi_yajl(yajl_gen, state)
- if ( status = FFI_Yajl.yajl_gen_bool(yajl_gen, 1) ) != 0
+ if ( status = FFI_Yajl.yajl_gen_bool(yajl_gen, 0) ) != 0
FFI_Yajl::Encoder.raise_error_for_status(status)
end
end
diff --git a/lib/ffi_yajl/json_gem.rb b/lib/ffi_yajl/json_gem.rb
index <HASH>..<HASH> 100644
--- a/lib/ffi_yajl/json_gem.rb
+++ b/lib/ffi_yajl/json_gem.rb
@@ -53,6 +53,54 @@ module JSON
end
end
+class Array
+ def to_json(*opts, &block)
+ FFI_Yajl::Encoder.encode(self)
+ end
+end
+
+class Hash
+ def to_json(*opts, &block)
+ FFI_Yajl::Encoder.encode(self)
+ end
+end
+
+class Fixnum
+ def to_json(*opts, &block)
+ FFI_Yajl::Encoder.encode(self)
+ end
+end
+
+class Float
+ def to_json(*opts, &block)
+ FFI_Yajl::Encoder.encode(self)
+ end
+end
+
+class String
+ def to_json(*opts, &block)
+ FFI_Yajl::Encoder.encode(self)
+ end
+end
+
+class TrueClass
+ def to_json(*opts, &block)
+ FFI_Yajl::Encoder.encode(self)
+ end
+end
+
+class FalseClass
+ def to_json(*opts, &block)
+ FFI_Yajl::Encoder.encode(self)
+ end
+end
+
+class NilClass
+ def to_json(*opts, &block)
+ FFI_Yajl::Encoder.encode(self)
+ end
+end
+
module ::Kernel
def JSON(object, opts = {})
if object.respond_to? :to_s
diff --git a/spec/ffi_yajl/json_gem_spec.rb b/spec/ffi_yajl/json_gem_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/ffi_yajl/json_gem_spec.rb
+++ b/spec/ffi_yajl/json_gem_spec.rb
@@ -183,11 +183,9 @@ describe "JSON Gem Compat API" do
shared_examples_for "handling utf8 correctly" do
it "should encode the content correctly" do
- pending "FIXME"
expect(utf8.to_json).to eq(json)
end
it "should parse the content correctly" do
- pending "FIXME"
expect(JSON.parse(json)).to eq(utf8)
end
end
@@ -236,6 +234,40 @@ describe "JSON Gem Compat API" do
end
+ context "when encoding basic types with #to_json" do
+ it "Array#to_json should work" do
+ expect([ "a", "b", "c" ].to_json).to eq(%Q{["a","b","c"]})
+ end
+
+ it "Hash#to_json should work" do
+ expect({"a"=>"b"}.to_json).to eq(%Q{{"a":"b"}})
+ end
+
+ it "Fixnum#to_json should work" do
+ expect(1.to_json).to eq("1")
+ end
+
+ it "Float#to_json should work" do
+ expect(1.1.to_json).to eq("1.1")
+ end
+
+ it "String#to_json should work" do
+ expect("foo".to_json).to eq(%Q{"foo"})
+ end
+
+ it "TrueClass#to_json should work" do
+ expect(true.to_json).to eq("true")
+ end
+
+ it "FalseClass#to_json should work" do
+ expect(false.to_json).to eq("false")
+ end
+
+ it "NilClass#to_json should work" do
+ expect(nil.to_json).to eq("null")
+ end
+ end
+
context "ported tests for generation" do
before(:all) do
@hash = {
|
fix #to_json on base classes
|
chef_ffi-yajl
|
train
|
e0fed894d3070a3fa7a9557af31200f0e382f1da
|
diff --git a/listing-bundle/contao/ModuleListing.php b/listing-bundle/contao/ModuleListing.php
index <HASH>..<HASH> 100644
--- a/listing-bundle/contao/ModuleListing.php
+++ b/listing-bundle/contao/ModuleListing.php
@@ -258,6 +258,7 @@ class ModuleListing extends \Module
);
}
+ $j = 0;
$arrRows = $objData->fetchAllAssoc();
// TBODY
|
[Listing] More issues found by PHPStorm fixed
|
contao_contao
|
train
|
4669f1373a5524fd22a45ff730717a382272f753
|
diff --git a/salt/utils/data.py b/salt/utils/data.py
index <HASH>..<HASH> 100644
--- a/salt/utils/data.py
+++ b/salt/utils/data.py
@@ -4,7 +4,6 @@ and data structures.
"""
-# Import Python libs
import copy
import fnmatch
import functools
@@ -12,15 +11,12 @@ import logging
import re
from collections.abc import Mapping, MutableMapping, Sequence
-# Import Salt libs
import salt.utils.dictupdate
import salt.utils.stringutils
import salt.utils.yaml
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.exceptions import SaltException
from salt.ext import six
-
-# Import 3rd-party libs
from salt.ext.six.moves import range # pylint: disable=redefined-builtin
from salt.ext.six.moves import zip # pylint: disable=redefined-builtin
from salt.utils.decorators.jinja import jinja_filter
@@ -790,7 +786,10 @@ def traverse_dict_and_list(data, key, default=None, delimiter=DEFAULT_TARGET_DEL
then return data['foo']['bar']['0']
"""
ptr = data
- for each in key.split(delimiter):
+ if isinstance(key, str):
+ key = key.split(delimiter)
+
+ for each in key:
if isinstance(ptr, list):
try:
idx = int(each)
diff --git a/tests/unit/utils/test_data.py b/tests/unit/utils/test_data.py
index <HASH>..<HASH> 100644
--- a/tests/unit/utils/test_data.py
+++ b/tests/unit/utils/test_data.py
@@ -2,15 +2,11 @@
Tests for salt.utils.data
"""
-# Import Python libs
import logging
-# Import Salt libs
import salt.utils.data
import salt.utils.stringutils
-
-# Import 3rd party libs
from salt.ext.six.moves import ( # pylint: disable=import-error,redefined-builtin
builtins,
)
@@ -242,6 +238,20 @@ class DataTestCase(TestCase):
),
)
+ def test_issue_39709(self):
+ test_two_level_dict_and_list = {
+ "foo": ["bar", "baz", {"lorem": {"ipsum": [{"dolor": "sit"}]}}]
+ }
+
+ self.assertEqual(
+ "sit",
+ salt.utils.data.traverse_dict_and_list(
+ test_two_level_dict_and_list,
+ ["foo", "lorem", "ipsum", "dolor"],
+ {"not_found": "not_found"},
+ ),
+ )
+
def test_compare_dicts(self):
ret = salt.utils.data.compare_dicts(old={"foo": "bar"}, new={"foo": "bar"})
self.assertEqual(ret, {})
|
filter_by supports list fix (#<I>)
* fixed issue #<I>
* Running pre-commit bits manually.
|
saltstack_salt
|
train
|
15d08176d250b1faf701c04887a01a31f22afd28
|
diff --git a/src/main/java/org/agrona/collections/IntHashSet.java b/src/main/java/org/agrona/collections/IntHashSet.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/agrona/collections/IntHashSet.java
+++ b/src/main/java/org/agrona/collections/IntHashSet.java
@@ -343,15 +343,18 @@ public final class IntHashSet implements Set<Integer>
/**
* Alias for {@link #addAll(Collection)} for the specialized case when adding another IntHashSet,
* avoids boxing and allocations
+ *
+ * @param coll containing the values to be added.
+ * @return <tt>true</tt> if this set changed as a result of the call
*/
- public boolean addAll(final IntHashSet coll){
- Objects.requireNonNull(coll);
-
+ public boolean addAll(final IntHashSet coll)
+ {
boolean acc = false;
- int t;
- for(IntIterator it = coll.iterator(); it.hasNext(); acc |= add(t)) {
- t = it.nextValue();
+ int value;
+ for (final IntIterator iter = coll.iterator(); iter.hasNext(); acc |= add(value))
+ {
+ value = iter.nextValue();
}
return acc;
@@ -362,8 +365,6 @@ public final class IntHashSet implements Set<Integer>
*/
public boolean containsAll(final Collection<?> coll)
{
- Objects.requireNonNull(coll);
-
for (final Object t : coll)
{
if (!contains(t))
@@ -383,8 +384,6 @@ public final class IntHashSet implements Set<Integer>
*/
public boolean containsAll(final IntHashSet other)
{
- Objects.requireNonNull(other);
-
final int missingValue = other.missingValue;
for (final int value : other.values)
{
@@ -407,8 +406,6 @@ public final class IntHashSet implements Set<Integer>
*/
public IntHashSet difference(final IntHashSet other)
{
- Objects.requireNonNull(other);
-
IntHashSet difference = null;
final int missingValue = this.missingValue;
@@ -437,17 +434,20 @@ public final class IntHashSet implements Set<Integer>
}
/**
- * See {@link #addAll(IntHashSet)}
+ * Alias for {@link #removeAll(Collection)} for the specialized case when removing another IntHashSet,
+ * avoids boxing and allocations
+ *
+ * @param coll containing the values to be removed.
+ * @return <tt>true</tt> if this set changed as a result of the call
*/
public boolean removeAll(final IntHashSet coll)
{
- Objects.requireNonNull(coll);
-
boolean acc = false;
- int t;
- for(IntIterator it = coll.iterator(); it.hasNext(); acc |= remove(t)) {
- t = it.nextValue();
+ int value;
+ for (final IntIterator iter = coll.iterator(); iter.hasNext(); acc |= remove(value))
+ {
+ value = iter.nextValue();
}
return acc;
@@ -455,8 +455,6 @@ public final class IntHashSet implements Set<Integer>
private static <T> boolean disjunction(final Collection<T> coll, final Predicate<T> predicate)
{
- Objects.requireNonNull(coll);
-
boolean acc = false;
for (final T t : coll)
{
@@ -513,8 +511,6 @@ public final class IntHashSet implements Set<Integer>
@SuppressWarnings("unchecked")
public <T> T[] toArray(final T[] into)
{
- Objects.requireNonNull(into, "into");
-
final Class<?> componentType = into.getClass().getComponentType();
if (!componentType.isAssignableFrom(Integer.class))
{
diff --git a/src/test/java/org/agrona/collections/IntHashSetTest.java b/src/test/java/org/agrona/collections/IntHashSetTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/agrona/collections/IntHashSetTest.java
+++ b/src/test/java/org/agrona/collections/IntHashSetTest.java
@@ -451,7 +451,7 @@ public class IntHashSetTest
subset.add(1);
- HashSet subSetCollection = new HashSet<>(subset);
+ final HashSet<Integer> subSetCollection = new HashSet<>(subset);
assertFalse(testSet.addAll(subset));
assertFalse(testSet.addAll(subSetCollection));
@@ -467,7 +467,7 @@ public class IntHashSetTest
addTwoElements(equal);
- HashSet<Integer> equalCollection = new HashSet<>(equal);
+ final HashSet<Integer> equalCollection = new HashSet<>(equal);
assertFalse(testSet.addAll(equal));
assertFalse(testSet.addAll(equalCollection));
|
[Java] Tidy up from merge of PR #<I> to fix build errors and remove unnecessary null checks.
|
real-logic_agrona
|
train
|
23e382fae082e6ad4bd174ff8ba0d4a491c19244
|
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java
index <HASH>..<HASH> 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/SipApplicationDispatcherImpl.java
@@ -656,6 +656,11 @@ public class SipApplicationDispatcherImpl implements SipApplicationDispatcher {
private boolean isRouteExternal(RouteHeader routeHeader) {
if (routeHeader != null) {
javax.sip.address.SipURI routeUri = (javax.sip.address.SipURI) routeHeader.getAddress().getURI();
+
+ // Consider proxies external
+ if(routeUri.getParameter(RR_PARAM_APPLICATION_ROUTER_ROUTE) == null)
+ return true;
+
String routeTransport = routeUri.getTransportParam();
if(routeTransport == null) {
routeTransport = ListeningPoint.UDP;
diff --git a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyUtils.java b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyUtils.java
index <HASH>..<HASH> 100644
--- a/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyUtils.java
+++ b/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/proxy/ProxyUtils.java
@@ -23,6 +23,7 @@ import javax.sip.message.Response;
import org.mobicents.servlet.sip.JainSipUtils;
import org.mobicents.servlet.sip.SipFactories;
+import org.mobicents.servlet.sip.core.SipApplicationDispatcherImpl;
import org.mobicents.servlet.sip.core.session.SipSessionImpl;
import org.mobicents.servlet.sip.message.SipFactoryImpl;
import org.mobicents.servlet.sip.message.SipServletRequestImpl;
@@ -110,6 +111,11 @@ public class ProxyUtils {
params.routeRecord.getParameter(paramName));
}
+ rrURI.setParameter(SipApplicationDispatcherImpl.RR_PARAM_APPLICATION_NAME,
+ originalRequest.getSipSession().getKey().getApplicationName());
+ rrURI.setParameter(SipApplicationDispatcherImpl.RR_PARAM_HANDLER_NAME,
+ originalRequest.getSipSession().getHandler());
+
Address rraddress = SipFactories.addressFactory
.createAddress(null, rrURI);
RecordRouteHeader recordRouteHeader = SipFactories.headerFactory
|
Proxy and AR integration. Requests without AppName and Handler are not routed correctly, so adding them. And the proxy should be considered external and endpoint for application routing, since you can't AR beyond a proxy.
Date: <I>-<I>-<I> <I>:<I>:<I>
git-svn-id: <URL>
|
RestComm_sip-servlets
|
train
|
76a171de13d1812733be8a58f50571d2a3501775
|
diff --git a/schema/validator.js b/schema/validator.js
index <HASH>..<HASH> 100644
--- a/schema/validator.js
+++ b/schema/validator.js
@@ -2,7 +2,9 @@ var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});
module.exports = function validate(schema, data) {
- var ajv = new Ajv();
+ var ajv = new Ajv({
+ errorDataPath: 'property'
+ });
var isValid = ajv.validate(schema, data);
if(!isValid) {
diff --git a/test/extract.test.js b/test/extract.test.js
index <HASH>..<HASH> 100644
--- a/test/extract.test.js
+++ b/test/extract.test.js
@@ -29,7 +29,7 @@ describe("ExtractTextPlugin.extract()", function() {
ExtractTextPlugin.extract({style: 'file.css'});
},
function(err) {
- return err.message === 'data should NOT have additional properties';
+ return err.message === 'data[\'style\'] should NOT have additional properties';
}
);
});
|
feat(errors): show nicer errors if there are extra fields
Now you can see which field caused the error.
|
webpack-contrib_extract-text-webpack-plugin
|
train
|
7674953c75c04669d36e9e8f6a979eb3eaaadf6b
|
diff --git a/component/ViewManager.js b/component/ViewManager.js
index <HASH>..<HASH> 100644
--- a/component/ViewManager.js
+++ b/component/ViewManager.js
@@ -1,4 +1,5 @@
import React from 'react'
+import GlobalContext from '../context'
export default class ViewManager extends React.Component {
views = {}
@@ -8,9 +9,8 @@ export default class ViewManager extends React.Component {
this.addItemIfNeed(props)
}
addItemIfNeed(props) {
- let path = props.state.location.raw
- if (!this.views.hasOwnProperty(path)) {
- this.views[path] = null
+ if (!this.views.hasOwnProperty(props.currentKey)) {
+ this.views[props.currentKey] = null
}
}
clearItemIfNeed() {
@@ -31,8 +31,8 @@ export default class ViewManager extends React.Component {
}
}
componentWillReceiveProps(nextProps) {
- if (this.props.state.location !== nextProps.state.location) {
- this.scrollMap[this.props.state.location.raw] = window.scrollY
+ if (this.props.currentKey !== nextProps.currentKey) {
+ this.scrollMap[this.props.currentKey] = window.scrollY
}
this.addItemIfNeed(nextProps)
}
@@ -40,17 +40,22 @@ export default class ViewManager extends React.Component {
this.clearItemIfNeed()
}
renderView(path) {
- let { View, state, handlers, actions, controller, currentKey } = this.props
- let isActive = state.location.raw === path
+ let { controller, currentKey } = this.props
+ let isActive = currentKey === path
if (isActive) {
+ let { store, handlers, View } = controller
+ let state = store.getState()
+ let actions = store.actions
let view = (
- <View
- key={currentKey}
- state={state}
- handlers={handlers}
- actions={actions}
- />
+ <GlobalContext.Provider value={getContextByController(controller)}>
+ <View
+ key={currentKey}
+ state={state}
+ handlers={handlers}
+ actions={actions}
+ />
+ </GlobalContext.Provider>
)
if (controller.KeepAlive) {
this.views[path] = view
@@ -63,7 +68,7 @@ export default class ViewManager extends React.Component {
}
}
render() {
- let { state } = this.props
+ let { currentKey } = this.props
return (
<React.Fragment>
{Object.keys(this.views).map(path => {
@@ -71,7 +76,7 @@ export default class ViewManager extends React.Component {
<ViewItem
key={path}
path={path}
- isActive={path === state.location.raw}
+ isActive={path === currentKey}
view={this.renderView(path)}
scrollY={this.scrollMap[path]}
/>
@@ -102,13 +107,36 @@ class ViewItem extends React.Component {
}
render() {
return (
- <div
- className="imvc-view-item"
- ref={this.getContainer}
- data-path={this.props.path}
- >
+ <div className="imvc-view-item" ref={this.getContainer}>
{this.props.view}
</div>
)
}
}
+
+function getContextByController(ctrl) {
+ let {
+ store,
+ handlers,
+ location,
+ history,
+ context,
+ matcher,
+ loader,
+ prefetch,
+ handleInputChange
+ } = ctrl
+ let state = store.getState()
+ return {
+ location,
+ history,
+ state,
+ actions: store.actions,
+ preload: context.preload,
+ handleInputChange,
+ handlers,
+ matcher,
+ loader,
+ prefetch
+ }
+}
diff --git a/controller/index.js b/controller/index.js
index <HASH>..<HASH> 100644
--- a/controller/index.js
+++ b/controller/index.js
@@ -491,46 +491,12 @@ export default class Controller {
this.history.replace(this.location.raw)
}
render() {
- let {
- meta,
- View,
- store,
- handlers,
- location,
- history,
- context,
- matcher,
- loader,
- prefetch,
- handleInputChange
- } = this
- let state = store.getState()
- let componentContext = {
- location,
- history,
- state,
- actions: store.actions,
- preload: context.preload,
- handleInputChange,
- handlers,
- matcher,
- loader,
- prefetch
- }
+ let { meta, location } = this
let currentKey = `[${meta.id}]${location.raw}`
return (
<React.Fragment>
- <GlobalContext.Provider value={componentContext}>
- <ViewManager
- currentKey={currentKey}
- controller={this}
- View={View}
- state={state}
- handlers={handlers}
- actions={store.actions}
- />
- </GlobalContext.Provider>
+ <ViewManager currentKey={currentKey} controller={this} />
<ControllerProxy key={currentKey} controller={this} />
</React.Fragment>
)
|
fixed single component context bug in keep-alive mode
|
Lucifier129_react-imvc
|
train
|
0e20e764e5ad43c33d08b4c397b69e41c62fef9f
|
diff --git a/lib/rack/rewrite/rule.rb b/lib/rack/rewrite/rule.rb
index <HASH>..<HASH> 100644
--- a/lib/rack/rewrite/rule.rb
+++ b/lib/rack/rewrite/rule.rb
@@ -169,7 +169,7 @@ module Rack
}.merge!(additional_headers), []]
when :send_data
[status, {
- 'Content-Type' => interpreted_to.bytesize,
+ 'Content-Length' => interpreted_to.bytesize,
'Content-Type' => 'text/html',
}.merge!(additional_headers), [interpreted_to]]
else
|
Fix duplicated key in apply!(env) method
there is a typo in the :send_data case within the apply!(env) method of rule.rb, the key 'Content-Type' is used twice. should be 'Content-Length' on line <I>.
|
jtrupiano_rack-rewrite
|
train
|
a17dc01d55406f3b7d6c3dee8e82ebe715806b41
|
diff --git a/src/InsertOnDuplicateKey.php b/src/InsertOnDuplicateKey.php
index <HASH>..<HASH> 100644
--- a/src/InsertOnDuplicateKey.php
+++ b/src/InsertOnDuplicateKey.php
@@ -35,7 +35,7 @@ trait InsertOnDuplicateKey
$data = static::inLineArray($data);
- return DB::statement($sql, $data);
+ return DB::connection(static::getModelConnectionName())->statement($sql, $data);
}
/**
@@ -60,7 +60,7 @@ trait InsertOnDuplicateKey
$data = static::inLineArray($data);
- return DB::statement($sql, $data);
+ return DB::connection(static::getModelConnectionName())->statement($sql, $data);
}
/**
@@ -85,7 +85,7 @@ trait InsertOnDuplicateKey
$data = static::inLineArray($data);
- return DB::statement($sql, $data);
+ return DB::connection(static::getModelConnectionName())->statement($sql, $data);
}
/**
@@ -101,6 +101,17 @@ trait InsertOnDuplicateKey
}
/**
+ * Static function for getting connection name
+ *
+ * @return string
+ */
+ public static function getModelConnectionName()
+ {
+ $class = get_called_class();
+ return (new $class())->getConnectionName();
+ }
+
+ /**
* Static function for getting the primary key.
*
* @return string
|
Added support for non-default connection
|
yadakhov_insert-on-duplicate-key
|
train
|
0915c91baa6e8f3e7877ea68825321ba23cfa2b9
|
diff --git a/packages/blueprint-gatekeeper/app/-internal/granters/refresh_token.js b/packages/blueprint-gatekeeper/app/-internal/granters/refresh_token.js
index <HASH>..<HASH> 100644
--- a/packages/blueprint-gatekeeper/app/-internal/granters/refresh_token.js
+++ b/packages/blueprint-gatekeeper/app/-internal/granters/refresh_token.js
@@ -119,6 +119,7 @@ module.exports = Granter.extend ({
account: accessToken.account._id,
scope : accessToken.scope,
origin : accessToken.origin,
+ payload: accessToken.payload,
refresh_token: new ObjectId ()
};
|
fix: the user-defined payload was not included in the refreshed token
|
onehilltech_blueprint
|
train
|
218fb2e18d83e2d930466eecf773e51ecc7767f9
|
diff --git a/src/main/java/org/primefaces/component/captcha/CaptchaRenderer.java b/src/main/java/org/primefaces/component/captcha/CaptchaRenderer.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/primefaces/component/captcha/CaptchaRenderer.java
+++ b/src/main/java/org/primefaces/component/captcha/CaptchaRenderer.java
@@ -76,7 +76,9 @@ public class CaptchaRenderer extends CoreRenderer {
wb.attr("sitekey", publicKey)
.attr("theme", captcha.getTheme(), "light")
.attr("language", captcha.getLanguage(), "en")
- .attr("tabindex", captcha.getTabindex(), 0);
+ .attr("tabindex", captcha.getTabindex(), 0)
+ .attr("callback", captcha.getCallback(), null)
+ .attr("expired", captcha.getExpired(), null);
wb.finish();
}
diff --git a/src/main/resources-maven-jsf/ui/captcha.xml b/src/main/resources-maven-jsf/ui/captcha.xml
index <HASH>..<HASH> 100644
--- a/src/main/resources-maven-jsf/ui/captcha.xml
+++ b/src/main/resources-maven-jsf/ui/captcha.xml
@@ -49,6 +49,18 @@
<type>java.lang.String</type>
<description>A localized user presentable name.</description>
</attribute>
+ <attribute>
+ <name>callback</name>
+ <required>false</required>
+ <type>java.lang.String</type>
+ <description>Callback executed when the user submits a successful captcha response.</description>
+ </attribute>
+ <attribute>
+ <name>expired</name>
+ <required>false</required>
+ <type>java.lang.String</type>
+ <description>Callback executed when the captcha response expires and the user needs to solve a new captcha.</description>
+ </attribute>
</attributes>
<resources>
<resource>
diff --git a/src/main/resources/META-INF/resources/primefaces/captcha/captcha.js b/src/main/resources/META-INF/resources/primefaces/captcha/captcha.js
index <HASH>..<HASH> 100644
--- a/src/main/resources/META-INF/resources/primefaces/captcha/captcha.js
+++ b/src/main/resources/META-INF/resources/primefaces/captcha/captcha.js
@@ -17,10 +17,13 @@ PrimeFaces.widget.Captcha = PrimeFaces.widget.BaseWidget.extend({
},
render: function() {
+ $this = this;
grecaptcha.render(this.jq.get(0), {
'sitekey' : this.cfg.sitekey,
'tabindex': this.cfg.tabindex,
- 'theme': this.cfg.theme
+ 'theme': this.cfg.theme,
+ 'callback': new Function($this.cfg.callback),
+ 'expired-callback': new Function($this.cfg.expired)
});
window[this.cfg.widgetVar + '_initCallback'] = undefined;
|
callback and callback-expired from reCaptcha v2 were not supported by p:captcha.
With this patch captcha provide two attributes for javascript callbacks:
- callback (executed when the user submits a successful captcha response)
- expired (executed when the recaptcha response expires and the user needs to solve a new captcha).
|
primefaces_primefaces
|
train
|
0ed85b9e1dfa476763624b0b8637dcfa83cfdb90
|
diff --git a/grapheneexchange/exchange.py b/grapheneexchange/exchange.py
index <HASH>..<HASH> 100644
--- a/grapheneexchange/exchange.py
+++ b/grapheneexchange/exchange.py
@@ -981,11 +981,17 @@ class GrapheneExchange(GrapheneClient) :
for debt in debts:
base = self.getObject(debt["call_price"]["base"]["asset_id"])
quote = self.getObject(debt["call_price"]["quote"]["asset_id"])
- call_price = self._get_price(debt["call_price"])
+
+ if "bitasset_data_id" not in quote:
+ continue
bitasset = self.getObject(quote["bitasset_data_id"])
settlement_price = self._get_price(bitasset["current_feed"]["settlement_price"])
+ if not settlement_price:
+ continue
+
+ call_price = self._get_price(debt["call_price"])
collateral_amount = int(debt["collateral"]) / 10 ** base["precision"]
debt_amount = int(debt["debt"]) / 10 ** quote["precision"]
|
[exchange] do not fail if no settlement price exists, i.e. get_debt_position called on non-bitasset
|
xeroc_python-graphenelib
|
train
|
824b9829619673d24be8168af57d4328e4fcf545
|
diff --git a/shared/login/register/set-public-name/index.js b/shared/login/register/set-public-name/index.js
index <HASH>..<HASH> 100644
--- a/shared/login/register/set-public-name/index.js
+++ b/shared/login/register/set-public-name/index.js
@@ -29,7 +29,7 @@ export class SetPublicName extends Component<void, Props, State> {
onBack={this.props.onBack}
deviceNameError={nameTakenError || this.props.deviceNameError}
submitEnabled={submitEnabled}
- waitingForResponse={this.props.waitingForResponse}
+ waiting={this.props.waiting}
/>
)
}
@@ -46,5 +46,5 @@ export class SetPublicName extends Component<void, Props, State> {
}
export default connect(
- state => ({waitingForResponse: state.login.waitingForResponse})
+ state => ({waiting: state.login.waitingForResponse})
)(SetPublicName)
diff --git a/shared/login/register/set-public-name/index.render.desktop.js b/shared/login/register/set-public-name/index.render.desktop.js
index <HASH>..<HASH> 100644
--- a/shared/login/register/set-public-name/index.render.desktop.js
+++ b/shared/login/register/set-public-name/index.render.desktop.js
@@ -4,7 +4,7 @@ import {Text, Button, Input, Icon} from '../../../common-adapters'
import Container from '../../forms/container'
import type {Props} from './index.render'
-const SetPublicName = ({onBack, onSubmit, onChange, deviceNameError, deviceName, waitingForResponse}: Props) => (
+const SetPublicName = ({onBack, onSubmit, onChange, deviceNameError, deviceName, waiting, submitEnabled = true}: Props) => (
<Container style={styles.container} onBack={onBack}>
<Text type='Header' style={styles.header}>Set a public name for this device:</Text>
<Icon type='computer-color-m' style={styles.icon}/>
@@ -20,7 +20,8 @@ const SetPublicName = ({onBack, onSubmit, onChange, deviceNameError, deviceName,
type='Primary'
fullWidth
style={styles.button}
- waiting={waitingForResponse}
+ disabled={!submitEnabled}
+ waiting={waiting}
label='Continue'
onClick={() => onSubmit()} />
</Container>
diff --git a/shared/login/register/set-public-name/index.render.js.flow b/shared/login/register/set-public-name/index.render.js.flow
index <HASH>..<HASH> 100644
--- a/shared/login/register/set-public-name/index.render.js.flow
+++ b/shared/login/register/set-public-name/index.render.js.flow
@@ -1,14 +1,15 @@
// @flow
import {Component} from 'react'
-export type Props = {
+export type Props = $Shape<{
onBack?: () => void,
onChange: (deviceName: string) => void,
onSubmit: () => void,
deviceName: ?string,
deviceNameError?: ?string,
- waitingForResponse?: ?boolean
-}
+ submitEnabled?: ?boolean,
+ waiting?: ?boolean
+}>
export type State = {
deviceName: ?string
diff --git a/shared/login/register/set-public-name/index.render.native.js b/shared/login/register/set-public-name/index.render.native.js
index <HASH>..<HASH> 100644
--- a/shared/login/register/set-public-name/index.render.native.js
+++ b/shared/login/register/set-public-name/index.render.native.js
@@ -5,7 +5,7 @@ import Container from '../../forms/container'
import type {Props} from './index.render'
import {globalStyles} from '../../../styles/style-guide'
-const SetPublicName = ({onBack, onSubmit, onChange, deviceNameError, deviceName, waitingForResponse}: Props) => (
+const SetPublicName = ({onBack, onSubmit, onChange, deviceNameError, deviceName, waiting, submitEnabled = true}: Props) => (
<Box style={stylesBox}>
<Container
style={stylesContainer}
@@ -25,7 +25,8 @@ const SetPublicName = ({onBack, onSubmit, onChange, deviceNameError, deviceName,
type='Primary'
fullWidth
enabled={deviceName}
- waiting={waitingForResponse}
+ disabled={!submitEnabled}
+ waiting={waiting}
label='Continue'
onClick={() => onSubmit()}/>
</Container>
|
Pass in the correct waiting prop, use definite shape to catch errors like these (#<I>)
|
keybase_client
|
train
|
308d086f4a29847823a99f37cddcecce3f0a8ac7
|
diff --git a/packages/botfuel-dialog/src/brains/brain.js b/packages/botfuel-dialog/src/brains/brain.js
index <HASH>..<HASH> 100644
--- a/packages/botfuel-dialog/src/brains/brain.js
+++ b/packages/botfuel-dialog/src/brains/brain.js
@@ -110,6 +110,15 @@ class Brain {
}
/**
+ * Gets all users.
+ * @async
+ * @returns {Promise.<Object>} the users
+ */
+ async getAllUsers() {
+ throw new MissingImplementationError();
+ }
+
+ /**
* Gets the init value for creating a new conversation.
* @returns {Object}
*/
diff --git a/packages/botfuel-dialog/src/brains/memory-brain.js b/packages/botfuel-dialog/src/brains/memory-brain.js
index <HASH>..<HASH> 100644
--- a/packages/botfuel-dialog/src/brains/memory-brain.js
+++ b/packages/botfuel-dialog/src/brains/memory-brain.js
@@ -57,13 +57,19 @@ class MemoryBrain extends Brain {
/** @inheritdoc */
async getUser(userId) {
logger.debug('getUser', userId);
- if (!await this.hasUser(userId)) {
+ if (!(await this.hasUser(userId))) {
throw new Error('User does not exist');
}
return this.users[userId];
}
/** @inheritdoc */
+ async getAllUsers() {
+ logger.debug('getAllUsers');
+ return this.users;
+ }
+
+ /** @inheritdoc */
async userSet(userId, key, value) {
logger.debug('userSet', userId, key, value);
const user = await this.getUser(userId);
diff --git a/packages/botfuel-dialog/src/brains/mongo-brain.js b/packages/botfuel-dialog/src/brains/mongo-brain.js
index <HASH>..<HASH> 100644
--- a/packages/botfuel-dialog/src/brains/mongo-brain.js
+++ b/packages/botfuel-dialog/src/brains/mongo-brain.js
@@ -98,6 +98,12 @@ class MongoBrain extends Brain {
return user;
}
+ /** @inheritdoc */
+ async getAllUsers() {
+ logger.debug('getAllUsers');
+ return this.users.find().toArray();
+ }
+
/**
* Wraps mongodb findOneAndUpdate and throws if user does not exist
* @async
diff --git a/packages/botfuel-dialog/tests/brains/brains.test.js b/packages/botfuel-dialog/tests/brains/brains.test.js
index <HASH>..<HASH> 100644
--- a/packages/botfuel-dialog/tests/brains/brains.test.js
+++ b/packages/botfuel-dialog/tests/brains/brains.test.js
@@ -88,6 +88,15 @@ const brainTest = (brainLabel) => {
expect(user._conversations).toHaveLength(1);
});
+ test('get all users', async () => {
+ await brain.addUser('d8372804-2716-47aa-81bf-dd0908f9f9f7');
+ await brain.addUser('8042b7e4-445f-4fa8-891a-d734595ac706');
+ await brain.addUser('e93428x4-2236-12da-c9jf-le983nxnl2k3');
+
+ const users = await brain.getAllUsers();
+ expect(Object.keys(users)).toHaveLength(3);
+ });
+
test('sets user key', async () => {
await brain.addUser(USER_ID);
const user = await brain.userSet(USER_ID, 'name', 'test');
|
feat: added get all users method to brain
|
Botfuel_botfuel-dialog
|
train
|
62748f1262ecce8e591975ac4e3af7804f2382d3
|
diff --git a/src/main/java/com/tumblr/jumblr/types/VideoPost.java b/src/main/java/com/tumblr/jumblr/types/VideoPost.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/tumblr/jumblr/types/VideoPost.java
+++ b/src/main/java/com/tumblr/jumblr/types/VideoPost.java
@@ -9,7 +9,6 @@ import java.util.Map;
* @author jc
*/
public class VideoPost extends Post {
- private final PostType type = PostType.VIDEO;
private List<Video> player;
private String caption;
private String embed, permalink_url;
@@ -18,6 +17,10 @@ public class VideoPost extends Post {
private int thumbnail_width;
private int thumbnail_height;
+ public VideoPost() {
+ type = PostType.VIDEO;
+ }
+
/**
* Get the permalink URL for this video
*/
@@ -103,11 +106,10 @@ public class VideoPost extends Post {
*/
@Override
public Map<String, Object> detail() {
- Map<String, Object> details = super.detail();
+ final Map<String, Object> details = super.detail();
details.put("caption", caption);
details.put("embed", embed);
details.put("data", data);
- details.put("type", type.getValue());
return details;
}
|
update video post to proper type override
|
tumblr_jumblr
|
train
|
c79c2050103161fafa3b9a07d052804356014041
|
diff --git a/beautysh/beautysh.py b/beautysh/beautysh.py
index <HASH>..<HASH> 100755
--- a/beautysh/beautysh.py
+++ b/beautysh/beautysh.py
@@ -112,44 +112,48 @@ class Beautify:
output.append(record)
continue
- inc = len(re.findall(
- r'(\s|\A|;)(case|then|do)(;|\Z|\s)', test_record))
- inc += len(re.findall(r'(\{|\(|\[)', test_record))
- outc = len(re.findall(
- r'(\s|\A|;)(esac|fi|done|elif)(;|\)|\||\Z|\s)',
- test_record))
- outc += len(re.findall(r'(\}|\)|\])', test_record))
- if(re.search(r'\besac\b', test_record)):
- if(case_level == 0):
- sys.stderr.write(
- 'File %s: error: "esac" before "case" in '
- 'line %d.\n' % (path, line))
- else:
- outc += 1
- case_level -= 1
-
- # special handling for bad syntax within case ... esac
- if re.search(r'\bcase\b', test_record):
- inc += 1
- case_level += 1
-
- choice_case = 0
- if case_level:
- if(re.search(r'\A[^(]*\)', test_record)):
+ # multi-line conditions are often meticulously formatted
+ if open_brackets:
+ output.append(record)
+ else:
+ inc = len(re.findall(
+ r'(\s|\A|;)(case|then|do)(;|\Z|\s)', test_record))
+ inc += len(re.findall(r'(\{|\(|\[)', test_record))
+ outc = len(re.findall(
+ r'(\s|\A|;)(esac|fi|done|elif)(;|\)|\||\Z|\s)',
+ test_record))
+ outc += len(re.findall(r'(\}|\)|\])', test_record))
+ if(re.search(r'\besac\b', test_record)):
+ if(case_level == 0):
+ sys.stderr.write(
+ 'File %s: error: "esac" before "case" in '
+ 'line %d.\n' % (path, line))
+ else:
+ outc += 1
+ case_level -= 1
+
+ # special handling for bad syntax within case ... esac
+ if re.search(r'\bcase\b', test_record):
inc += 1
- choice_case = -1
-
- # an ad-hoc solution for the "else" keyword
- else_case = (0, -1)[re.search(r'^(else|elif)',
- test_record) is not None]
- net = inc - outc
- tab += min(net, 0)
- extab = tab + else_case + choice_case + (
- 1 if continue_line and not open_brackets else 0)
- extab = max(0, extab)
- output.append((self.tab_str * self.tab_size * extab) +
- stripped_record)
- tab += max(net, 0)
+ case_level += 1
+
+ choice_case = 0
+ if case_level:
+ if(re.search(r'\A[^(]*\)', test_record)):
+ inc += 1
+ choice_case = -1
+
+ # an ad-hoc solution for the "else" keyword
+ else_case = (0, -1)[re.search(r'^(else|elif)',
+ test_record) is not None]
+ net = inc - outc
+ tab += min(net, 0)
+ extab = tab + else_case + choice_case + (
+ 1 if continue_line and not open_brackets else 0)
+ extab = max(0, extab)
+ output.append((self.tab_str * self.tab_size * extab) +
+ stripped_record)
+ tab += max(net, 0)
if(defer_ext_quote):
in_ext_quote = True
defer_ext_quote = False
|
Let multi-line conditional statements pass through
They are often meticulously formatted
|
lovesegfault_beautysh
|
train
|
41d3b89a56cd57ce2e386259cc8b271adee5dc1c
|
diff --git a/networkzero/discovery.py b/networkzero/discovery.py
index <HASH>..<HASH> 100644
--- a/networkzero/discovery.py
+++ b/networkzero/discovery.py
@@ -11,6 +11,10 @@ The discovery module offers:
* A ZeroMQ socket which allow any process on this machine to
communicate with its broadcast socket
+In other words, we have a beacon which listens to instructions
+from processes on this machine while sending out and listening
+to adverts broadcast to/from all machines on the network.
+
The beacon is started automatically in a daemon thread when the first
attempt is made to advertise or discover. If another process already
has a beacon running (ie if this beacon can't bind to its port) this
|
Add a slight summary of the situation
|
tjguk_networkzero
|
train
|
1ad48236f5127ceb9cc548dd7c852b559b2bb2b7
|
diff --git a/database/migrations/2017_06_07_113300_modify_primary_key_in_settings_table.php b/database/migrations/2017_06_07_113300_modify_primary_key_in_settings_table.php
index <HASH>..<HASH> 100644
--- a/database/migrations/2017_06_07_113300_modify_primary_key_in_settings_table.php
+++ b/database/migrations/2017_06_07_113300_modify_primary_key_in_settings_table.php
@@ -2,6 +2,7 @@
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
class ModifyPrimaryKeyInSettingsTable extends Migration
{
@@ -10,10 +11,36 @@ class ModifyPrimaryKeyInSettingsTable extends Migration
*/
public function up()
{
- Schema::table( 'settings', function ( Blueprint $table )
- {
- $table->dropColumn( 'id' );
- $table->string( 'name' )->primary()->change();
- } );
+ if (Schema::getConnection()->getDriverName() === 'sqlsrv') {
+ $this->dropPrimaryForSqlServer();
+ }
+
+ Schema::table('settings', function (Blueprint $table) {
+ $table->dropColumn('id');
+ $table->string('name')->primary()->change();
+ });
+ }
+
+ public function down()
+ {
+ Schema::table('settings', function (Blueprint $table) {
+ $table->dropPrimary('settings_name_primary');
+ });
+ Schema::table('settings', function (Blueprint $table) {
+ $table->increments('id');
+ });
+ }
+
+ protected function dropPrimaryForSqlServer()
+ {
+ $schema = Schema::getConnection()->getDoctrineSchemaManager();
+ $indexes = $schema->listTableIndexes('settings');
+ $primaryIndex = array_get($indexes, 'primary');
+
+ if ($primaryIndex) {
+ Schema::table('settings', function (Blueprint $table) use ($primaryIndex) {
+ $table->dropPrimary($primaryIndex->getName());
+ });
+ }
}
}
|
Modify settings primary key migration to work with sqlsrv
|
arbory_arbory
|
train
|
f4a83be4315b8505f7690bcba1a781279f79beca
|
diff --git a/lib/katello/engine.rb b/lib/katello/engine.rb
index <HASH>..<HASH> 100644
--- a/lib/katello/engine.rb
+++ b/lib/katello/engine.rb
@@ -23,7 +23,7 @@ module Katello
Apipie.configuration.api_controllers_matcher = "#{Katello::Engine.root}/app/controllers/katello/api/v2/*.rb"
end
- initializer "katello.register_actions" do |app|
+ initializer "katello.register_actions", :before => 'foreman_tasks.initialize_dynflow' do |app|
ForemanTasks.dynflow.require!
action_paths = %W[#{Katello::Engine.root}/app/lib/actions
#{Katello::Engine.root}/app/lib/headpin/actions
|
Require dynflow before initializing
|
Katello_katello
|
train
|
bedf06a774449d5ea48a1ad7c57fb2a1ed23e471
|
diff --git a/moco-runner/src/test/java/com/github/dreamhead/moco/runner/DynamicSettingRunnerTest.java b/moco-runner/src/test/java/com/github/dreamhead/moco/runner/DynamicSettingRunnerTest.java
index <HASH>..<HASH> 100644
--- a/moco-runner/src/test/java/com/github/dreamhead/moco/runner/DynamicSettingRunnerTest.java
+++ b/moco-runner/src/test/java/com/github/dreamhead/moco/runner/DynamicSettingRunnerTest.java
@@ -55,7 +55,7 @@ public class DynamicSettingRunnerTest extends AbstractRunnerTest {
}
@Test
- public void should_reload_configuration_with_mulitiple_modification() throws IOException, InterruptedException {
+ public void should_reload_configuration_with_multiple_modification() throws IOException, InterruptedException {
final File config1 = tempFolder.newFile("config1.json");
changeFileContent(config1, "[{" +
" \"request\": {" +
@@ -111,7 +111,6 @@ public class DynamicSettingRunnerTest extends AbstractRunnerTest {
" \"text\": \"foo1\"" +
" }" +
"}]");
- Idles.idle(500, TimeUnit.MILLISECONDS);
changeFileContent(config2, "[{" +
" \"request\": {" +
" \"uri\": \"/bar\"" +
@@ -124,10 +123,10 @@ public class DynamicSettingRunnerTest extends AbstractRunnerTest {
waitChangeHappens();
- String result = new String(out.toByteArray());
- assertThat(result.contains("Fail"), is(false));
-
System.setOut(oldOut);
System.setErr(oldErr);
+
+ String result = new String(out.toByteArray());
+ assertThat(result.contains("Fail"), is(false));
}
}
|
reseted system out and error before assertion in should_reload_configuration_with_multiple_modification
|
dreamhead_moco
|
train
|
ce04182351e50bc1d3de76c1c9d3a3edbeb64890
|
diff --git a/form-submission-handler.js b/form-submission-handler.js
index <HASH>..<HASH> 100644
--- a/form-submission-handler.js
+++ b/form-submission-handler.js
@@ -9,6 +9,9 @@ function getFormData() {
var fields = Object.keys(elements).map(function(k) {
if(elements[k].name !== undefined) {
return elements[k].name;
+ // special case for Edge's html collection
+ }else if(elements[k].length > 0){
+ return elements[k].item(0).name;
}
}).filter(function(item, pos, self) {
return self.indexOf(item) == pos && item;
@@ -18,6 +21,13 @@ function getFormData() {
data[k] = elements[k].value;
if(elements[k].type === "checkbox"){
data[k] = elements[k].checked;
+ // special case for Edge's html collection
+ }else if(elements[k].length){
+ for(var i = 0; i < elements[k].length; i++){
+ if(elements[k].item(i).checked){
+ data[k] = elements[k].item(i).value;
+ }
+ }
}
});
console.log(data);
|
address #<I> to get radio button values
bug fix traverses a form's html collection for input values (for Edge, maybe IE)
|
dwyl_learn-to-send-email-via-google-script-html-no-server
|
train
|
e77622899688e98928eb5e7ca39b77a5e629f2ad
|
diff --git a/tools/py/pipeline/link_materialize_actions.py b/tools/py/pipeline/link_materialize_actions.py
index <HASH>..<HASH> 100644
--- a/tools/py/pipeline/link_materialize_actions.py
+++ b/tools/py/pipeline/link_materialize_actions.py
@@ -151,7 +151,7 @@ def materialize(typ, rel=None, origin=None, unique=None, fprint=None, links=None
for target in targets:
ctx_stem = ctx.copy(current_link=(ctx.current_link[ORIGIN], ctx.current_link[RELATIONSHIP], target, ctx.current_link[ATTRIBUTES]))
if origin:
- #Have been given enough info to derive the origin from context. Ignore origin in current link
+ # Have been given enough info to derive the origin from context. Ignore origin in current link
o = origin(ctx_stem)
if not o: #Defensive coding
continue
@@ -173,7 +173,7 @@ def materialize(typ, rel=None, origin=None, unique=None, fprint=None, links=None
# rels = [ ('_' + curr_rel if curr_rel.isdigit() else curr_rel) for curr_rel in rels if curr_rel ]
computed_rels = []
for curr_relobj in rels:
- #e.g. scenario if passed in rel=ifexists(...)
+ # e.g. scenario if passed in rel=ifexists(...)
curr_rels = curr_relobj(ctx_stem) if is_pipeline_action(curr_relobj) else curr_relobj
curr_rels = curr_rels if isinstance(curr_rels, list) else [curr_rels]
for curr_rel in curr_rels:
@@ -189,7 +189,7 @@ def materialize(typ, rel=None, origin=None, unique=None, fprint=None, links=None
if _typ: ctx_stem.output_model.add(I(objid), VTYPE_REL, I(iri.absolutize(_typ, ctx_stem.base)), {})
computed_unique.sort()
if preserve_fprint:
- attrs = { k:v for (k,v) in computed_unique }
+ attrs = { k:v for (k, v) in computed_unique }
ctx_stem.output_model.add(I(objid), VFPRINT_REL, _typ, attrs)
# XXX: Use Nones to mark blanks, or should Versa define some sort of null resource?
for l in links:
@@ -204,10 +204,13 @@ def materialize(typ, rel=None, origin=None, unique=None, fprint=None, links=None
lt = lt or ctx_stem.current_link[TARGET]
lo = lo(ctx_stem) if is_pipeline_action(lo) else lo
- # XXX: Do we need to use the new origin context?
- # new_current_link = (lo, ctx_stem.current_link[RELATIONSHIP], ctx_stem.current_link[TARGET], ctx_stem.current_link[ATTRIBUTES])
- # ctx_vein = ctx_stem.copy(current_link=new_current_link)
- lr = lr(ctx_stem) if is_pipeline_action(lr) else lr
+ # Update contexts as we go along
+ ctx_vein = ctx_stem.copy(current_link=(lo, ctx_stem.current_link[RELATIONSHIP],
+ ctx_stem.current_link[TARGET],
+ ctx_stem.current_link[ATTRIBUTES]))
+ lr = lr(ctx_vein) if callable(lr) else lr
+ ctx_vein = ctx_vein.copy(current_link=(lo, lr, ctx_stem.current_link[TARGET],
+ ctx_stem.current_link[ATTRIBUTES]))
# If k is a list of contexts use it to dynamically execute functions
if isinstance(lr, list):
if lr and isinstance(lr[0], context):
@@ -216,13 +219,13 @@ def materialize(typ, rel=None, origin=None, unique=None, fprint=None, links=None
lt(newctx)
continue
- #import traceback; traceback.print_stack() #For looking up the call stack e.g. to debug nested materialize
- #Check that the links key is not None, which is a signal not to
- #generate the item. For example if the key is an ifexists and the
- #test expression result is False, it will come back as None,
- #and we don't want to run the v function
+ # import traceback; traceback.print_stack() #For looking up the call stack e.g. to debug nested materialize
+ # Check that the links key is not None, which is a signal not to
+ # generate the item. For example if the key is an ifexists and the
+ # test expression result is False, it will come back as None,
+ # and we don't want to run the v function
if lr:
- lt = lt(ctx_stem) if is_pipeline_action(lt) else lt
+ lt = lt(ctx_vein) if is_pipeline_action(lt) else lt
# If k or v come from pipeline functions as None it signals to skip generating anything else for this link item
if lt is not None:
@@ -231,9 +234,9 @@ def materialize(typ, rel=None, origin=None, unique=None, fprint=None, links=None
if isinstance(lt, list):
for valitems in lt:
if valitems:
- ctx_stem.output_model.add(lo, I(iri.absolutize(lr, ctx_stem.base)), valitems, {})
+ ctx_vein.output_model.add(lo, I(iri.absolutize(lr, ctx_vein.base)), valitems, {})
else:
- ctx_stem.output_model.add(lo, I(iri.absolutize(lr, ctx_stem.base)), lt, {})
+ ctx_vein.output_model.add(lo, I(iri.absolutize(lr, ctx_vein.base)), lt, {})
ctx_stem.existing_ids.add(objid)
if '@new-entity-hook' in ctx.extras:
ctx.extras['@new-entity-hook'](objid)
|
Make sure nested materialize gets the right context link info
|
uogbuji_versa
|
train
|
5b4f848989967a51a4e21be1a3f6277f009f16ad
|
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.13.0"
+__version__ = "0.14.0"
|
Update version number to <I>
|
chaoss_grimoirelab-perceval
|
train
|
6734e67d377ec8d8096a87d0751e787d6b481a45
|
diff --git a/go/auth/credential_authority.go b/go/auth/credential_authority.go
index <HASH>..<HASH> 100644
--- a/go/auth/credential_authority.go
+++ b/go/auth/credential_authority.go
@@ -1,6 +1,7 @@
package auth
import (
+ "fmt"
libkb "github.com/keybase/client/go/libkb"
logger "github.com/keybase/client/go/logger"
keybase1 "github.com/keybase/client/go/protocol"
@@ -38,6 +39,12 @@ type checkArg struct {
retCh chan error
}
+// String implements the Stringer interface for checkArg.
+func (ca checkArg) String() string {
+ return fmt.Sprintf("{uid: %s, username: %s, kid: %s, sibkeys: %v, subkeys: %v}",
+ ca.uid, ca.username, ca.kid, ca.sibkeys, ca.subkeys)
+}
+
// userWrapper contains two fields -- one is the user object itself, which will
// spawn a go-routine that is largely off-limits to the main thread aside from
// over channels. the second field is the `atime`, or *access* time, which the main
@@ -55,6 +62,11 @@ type cleanItem struct {
ctime time.Time
}
+// String implements the Stringer interface for cleanItem.
+func (ci cleanItem) String() string {
+ return fmt.Sprintf("{uid: %s, ctime: %s}", ci.uid, ci.ctime)
+}
+
// user wraps a user who is currently active in the system. Each user has a run
// method that runs its own goRoutine, so many items, aside from the two channels,
// are off-limits to the main thread.
@@ -70,10 +82,17 @@ type user struct {
stopCh chan struct{}
}
+// String implements the stringer interface for user.
+func (u user) String() string {
+ return fmt.Sprintf("{uid: %s, username: %s, sibkeys: %v, subkeys: %v, isOK: %v, ctime: %s}",
+ u.uid, u.username, u.sibkeys, u.subkeys, u.isOK, u.ctime)
+}
+
// newUser makes a new user with the given UID for use in the given
// CredentialAuthority. This constructor sets up the necessary maps and
// channels to make the user work as expected.
func newUser(uid keybase1.UID, ca *CredentialAuthority) *user {
+ ca.log.Debug("newUser, uid %s", uid)
ret := &user{
uid: uid,
sibkeys: make(map[keybase1.KID]struct{}),
@@ -221,10 +240,12 @@ func (v *CredentialAuthority) runLoop() {
case <-v.shutdownCh:
done = true
case ca := <-v.checkCh:
+ v.log.Debug("Checking %s", ca)
u := v.makeUser(ca.uid)
go u.sendCheck(ca)
case uid := <-v.invalidateCh:
if uw := v.users[uid]; uw != nil {
+ v.log.Debug("Invalidating %s", uw)
delete(v.users, uid)
go uw.u.sendStop()
}
@@ -250,6 +271,7 @@ func (v *CredentialAuthority) clean() {
return
}
if uw := v.users[e.uid]; uw != nil && !uw.atime.After(e.ctime) {
+ v.log.Debug("Cleaning %s, clean entry: %s", uw, e)
delete(v.users, e.uid)
go uw.u.sendStop()
}
@@ -293,6 +315,7 @@ func (u *user) run() {
case ca := <-u.checkCh:
u.check(ca)
case <-u.stopCh:
+ u.ca.log.Debug("Stopping user loop for %s", u)
done = true
case <-u.ca.shutdownCh:
done = true
@@ -335,6 +358,7 @@ func (u *user) repopulate() error {
}
u.isOK = true
u.ctime = ctime
+ u.ca.log.Debug("Repopulated info for %s", u)
return nil
}
@@ -350,6 +374,7 @@ func (u *user) check(ca checkArg) {
var err error
defer func() {
+ u.ca.log.Debug("Check %s, err: %v", ca, err)
ca.retCh <- err
}()
@@ -445,6 +470,7 @@ func (u *user) checkKey(kid keybase1.KID) error {
// check fails, and nil otherwise. If username or kid are nil they aren't checked.
func (v *CredentialAuthority) CheckUserKey(ctx context.Context, uid keybase1.UID,
username *libkb.NormalizedUsername, kid *keybase1.KID) (err error) {
+ v.log.Debug("CheckUserKey uid %s, kid %s", uid, kid)
retCh := make(chan error)
v.checkCh <- checkArg{uid: uid, username: username, kid: kid, retCh: retCh}
select {
diff --git a/go/auth/user_keys_api.go b/go/auth/user_keys_api.go
index <HASH>..<HASH> 100644
--- a/go/auth/user_keys_api.go
+++ b/go/auth/user_keys_api.go
@@ -81,9 +81,10 @@ func (u *userKeyAPI) GetUser(ctx context.Context, uid keybase1.UID) (
}
func (u *userKeyAPI) PollForChanges(ctx context.Context) (uids []keybase1.UID, err error) {
- u.log.Debug("+ poll")
defer func() {
- u.log.Debug("- poll -> %v", err)
+ if err != nil {
+ u.log.Debug("- poll -> %v", err)
+ }
}()
select {
|
auth: add more credential authority logging
|
keybase_client
|
train
|
326e5de130460edec135377d225c0bcdfbdd6800
|
diff --git a/ccmlib/cluster.py b/ccmlib/cluster.py
index <HASH>..<HASH> 100644
--- a/ccmlib/cluster.py
+++ b/ccmlib/cluster.py
@@ -224,6 +224,7 @@ class Cluster():
print "[%s ERROR] %s" % (node.name, line.rstrip('\n'))
if verbose:
print "----"
+ node.watch_log_for("Listening for thrift clients...")
self.__update_pids(started)
|
Ensure thrift is ready on cluster start
|
riptano_ccm
|
train
|
25863473ed291191688a9cd084e1441292c4473d
|
diff --git a/chef/lib/chef/provider/remote_file.rb b/chef/lib/chef/provider/remote_file.rb
index <HASH>..<HASH> 100644
--- a/chef/lib/chef/provider/remote_file.rb
+++ b/chef/lib/chef/provider/remote_file.rb
@@ -73,7 +73,7 @@ class Chef
@new_resource.updated = true
# We're done with the file, so make sure to close it if it was open.
- raw_file.close
+ raw_file.close unless raw_file.closed?
rescue Net::HTTPRetriableError => e
if e.response.kind_of?(Net::HTTPNotModified)
Chef::Log.debug("File #{path} is unchanged")
|
Adding a safety check for closing already closed filehandles
|
chef_chef
|
train
|
a300e76a6822812cbb9aee30237cc6b338ff7fef
|
diff --git a/breezy/lib/index.js b/breezy/lib/index.js
index <HASH>..<HASH> 100644
--- a/breezy/lib/index.js
+++ b/breezy/lib/index.js
@@ -6,6 +6,7 @@ import {setWindow, unsetWindow, hasWindow} from './window'
import {Nav} from './utils/react'
import connect from './connector'
import {pathQuery as convertToPathQuery} from './utils/url'
+import {persist} from './action_creators'
export {mapStateToProps, mapDispatchToProps} from './utils/react'
export {breezyReducer, pageReducer, rootReducer} from './reducers'
@@ -84,6 +85,13 @@ export function start ({window, baseUrl='', history, initialPage={}}) {
url: parse(url).href
})
}
+
+ store.dispatch(persist({
+ pathQuery: convertToPathQuery(url),
+ page: initialPage,
+ dispatch: store.dispatch,
+ }))
+
store.dispatch({type: 'BREEZY_SET_BASE_URL', baseUrl})
store.dispatch({type: 'BREEZY_SET_CSRF_TOKEN', csrfToken})
},
|
Fix re-enable deferments
|
jho406_Breezy
|
train
|
e1f4a3595be79fec966fb9301f801bd8c5e0cd16
|
diff --git a/src/Models/User.php b/src/Models/User.php
index <HASH>..<HASH> 100644
--- a/src/Models/User.php
+++ b/src/Models/User.php
@@ -159,6 +159,7 @@ class User extends Model implements AuthenticatableContract, AuthenticatableTwoF
'gender',
'active',
'login_at',
+ 'abilities',
'roles',
];
@@ -413,4 +414,20 @@ class User extends Model implements AuthenticatableContract, AuthenticatableTwoF
}
});
}
+
+ /**
+ * Attach the user abilities.
+ *
+ * @param array $abilities
+ *
+ * @return void
+ */
+ public function setAbilitiesAttribute(array $abilities)
+ {
+ static::saved(function (self $model) use ($abilities) {
+ foreach (Ability::whereIn('slug', $abilities)->get() as $ability) {
+ $model->abilities()->attach($ability);
+ }
+ });
+ }
}
|
Add abilities mutator for easy user abilities attachment
|
rinvex_laravel-auth
|
train
|
b7010c6ac5818c9e041df9d5a5ae47736ede54fc
|
diff --git a/wsrequest/__init__.py b/wsrequest/__init__.py
index <HASH>..<HASH> 100644
--- a/wsrequest/__init__.py
+++ b/wsrequest/__init__.py
@@ -11,10 +11,13 @@ VERSION = __version__
class WebSocketRequest(object):
- def __init__(self, message):
+ def __init__(self, message, factory_defaults=None):
self.message = message
+ self.factory_defaults = factory_defaults
self.error = None
+ self.validate()
+
def get_url(self):
return self.json_message.get('url')
@@ -33,27 +36,20 @@ class WebSocketRequest(object):
'status_code': status_code
}
- def is_valid(self):
- is_valid = False
-
+ def validate(self):
if self.is_valid_message():
self.url = self.get_url()
self.method = self.get_method()
self.data = self.get_data()
self.token = self.get_token()
- if not self.url:
+ if self.url:
+ self.get_url_resolver_match()
+ else:
self.set_error('Missing URL')
- return False
-
- resolver_match = self.get_url_resolver_match()
- if not resolver_match:
- return False
-
- is_valid = True
-
- return is_valid
+ def is_valid(self):
+ return not self.error
def is_valid_message(self):
try:
@@ -77,6 +73,9 @@ class WebSocketRequest(object):
if self.token:
defaults['HTTP_AUTHORIZATION'] = "JWT {0}".format(self.token)
+ if self.factory_defaults:
+ defaults.update(self.factory_defaults)
+
return RequestFactory(**defaults)
def get_request(self, factory):
diff --git a/wsrequest/tests.py b/wsrequest/tests.py
index <HASH>..<HASH> 100644
--- a/wsrequest/tests.py
+++ b/wsrequest/tests.py
@@ -333,3 +333,41 @@ class WebSocketRequestTestCase(TestCase):
json_content = json.loads(response.content.decode('utf-8'))
self.assertEqual(json_content['HTTP_AUTHORIZATION'], None)
+
+ def test_initializing_should_validate(self):
+ data = {
+ 'url': '/api/nonexistent/',
+ }
+
+ message = json.dumps(data)
+ wsrequest = WebSocketRequest(message)
+
+ expected_error = {
+ 'status_code': 404,
+ 'error': 'Resource not found.'
+ }
+
+ self.assertEqual(wsrequest.error, expected_error)
+
+ def test_factory_defaults_should_update_request_factory_defaults(self):
+ data = {
+ 'url': '/api/restricted/',
+ 'method': 'get',
+ }
+
+ message = json.dumps(data)
+
+ defaults = {
+ 'REMOTE_ADDR': '123.123.123.123',
+ 'SERVER_NAME': 'TheDefiant',
+ 'HTTP_X_FORWARDED_FOR': '123.123.123.123'
+ }
+
+ wsrequest = WebSocketRequest(message, defaults)
+ factory = wsrequest.get_factory()
+ request = wsrequest.get_request(factory)
+
+ self.assertEqual(request.META['REMOTE_ADDR'], defaults['REMOTE_ADDR'])
+ self.assertEqual(request.META['SERVER_NAME'], defaults['SERVER_NAME'])
+ self.assertEqual(request.META['HTTP_X_FORWARDED_FOR'],
+ defaults['HTTP_X_FORWARDED_FOR'])
|
Allow passing extra defaults for RequestFactory
|
GetBlimp_django-websocket-request
|
train
|
695393f05a3e5287a4b4b7badf52f6047e01ce46
|
diff --git a/packages/with-without/js/handleActiveRegionChange.js b/packages/with-without/js/handleActiveRegionChange.js
index <HASH>..<HASH> 100644
--- a/packages/with-without/js/handleActiveRegionChange.js
+++ b/packages/with-without/js/handleActiveRegionChange.js
@@ -7,11 +7,14 @@ const setActiveRegionAttr = (inactiveToRemove, activeToSet) => {
};
/*
- * Filter els by likely invisibility.
+ * Filter el or array of els by likely invisibility.
* Triggering animations on els with display: none parents breaks all subsequent animations.
* Based on @https://davidwalsh.name/offsetheight-visibility
*/
const filterInvisibles = els => {
+ if (!Array.isArray(els)) {
+ return els.offsetHeight > 0 ? els : null;
+ }
return els.filter(el => el.offsetHeight > 0);
};
@@ -71,9 +74,16 @@ const triggerAnimateOutOnInOnlyContent = async (groupAttrVal, mainWrapper) => {
`bolt-animate[group="${groupAttrVal}"][type="in-effect-only"]`,
),
);
- document
- .querySelector(`#c-pega-wwo__self-drawing-circle[group="${groupAttrVal}"]`)
- .triggerAnimOut();
+
+ const desktopCircle = filterInvisibles(
+ document.querySelector(
+ `#c-pega-wwo__self-drawing-circle[group="${groupAttrVal}"]`,
+ ),
+ );
+ console.debug('desktopCircle', desktopCircle);
+ if (desktopCircle) {
+ desktopCircle.triggerAnimOut();
+ }
console.debug('triggering:triggerAnimateOutOnInOnlyContent animInEls');
await triggerAnims({
@@ -139,11 +149,14 @@ const getCurriedAnimateContentIn = (inGroupAttrVal, mainWrapper) => {
);
setTimeout(() => {
- document
- .querySelector(
+ const desktopCircle = filterInvisibles(
+ document.querySelector(
`#c-pega-wwo__self-drawing-circle[group="${inGroupAttrVal}"]`,
- )
- .triggerAnimIn();
+ ),
+ );
+ if (desktopCircle) {
+ desktopCircle.triggerAnimIn();
+ }
}, 0);
// console.log('AnimateContentIn', animInEls);
@@ -234,7 +247,6 @@ const triggerActiveRegionChange = async (checked, wwoSwiper, init = false) => {
}
console.error('withIsBecomingActive', withIsBecomingActive);
-
}
return true;
};
|
fix(with-without): ie/edge broken when animateIn called on invisible desktop circle when on mobile
|
bolt-design-system_bolt
|
train
|
1553a51e6efb943652ea29cba72c970be2b4f83d
|
diff --git a/src/main/java/com/wiley/autotest/services/SeleniumMethodsInvoker.java b/src/main/java/com/wiley/autotest/services/SeleniumMethodsInvoker.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/wiley/autotest/services/SeleniumMethodsInvoker.java
+++ b/src/main/java/com/wiley/autotest/services/SeleniumMethodsInvoker.java
@@ -128,7 +128,7 @@ public class SeleniumMethodsInvoker extends MethodsInvoker {
return true;
}
- if (driverName.contains(IE) && isNoGroupTest(method, Group.noIE)) {
+ if (driverName.startsWith(IE) && isNoGroupTest(method, Group.noIE)) {
return true;
}
|
hotfix for #<I>. Now before method should be executed for safari
|
WileyLabs_teasy
|
train
|
da612b59b1f07e1df58548e2d799611ddd59bcee
|
diff --git a/salt/modules/iptables.py b/salt/modules/iptables.py
index <HASH>..<HASH> 100644
--- a/salt/modules/iptables.py
+++ b/salt/modules/iptables.py
@@ -138,6 +138,31 @@ def save(filename=None):
return out
+def check(table='filter', chain=None, rule=None):
+ '''
+ Check for the existance of a rule in the table and chain
+
+ This function accepts a rule in a standard iptables command format,
+ starting with the chain. Trying to force users to adapt to a new
+ method of creating rules would be irritating at best, and we
+ already have a parser that can handle it.
+
+ CLI Example::
+
+ salt '*' iptables.check filter INPUT rule='-m state --state RELATED,ESTABLISHED -j ACCEPT'
+ '''
+ if not chain:
+ return 'Error: Chain needs to be specified'
+ if not rule:
+ return 'Error: Rule needs to be specified'
+
+ cmd = 'iptables -t {0} -C {1} {2}'.format(table, chain, rule)
+ out = __salt__['cmd.run'](cmd)
+ if not out:
+ return True
+ return out
+
+
def append(table='filter', chain=None, rule=None):
'''
Append a rule to the specified table/chain.
|
Add function to check for the existance of an iptables rule
|
saltstack_salt
|
train
|
3e522be86edbb1cc7f6cdf03d9b13a9fa02cbd9e
|
diff --git a/lib/rules/indent.js b/lib/rules/indent.js
index <HASH>..<HASH> 100644
--- a/lib/rules/indent.js
+++ b/lib/rules/indent.js
@@ -268,6 +268,16 @@ module.exports = {
) {
report(node, indent, nodeIndent);
}
+
+ if (node.type === "IfStatement" && node.alternate) {
+ const elseToken = sourceCode.getTokenBefore(node.alternate);
+
+ checkNodeIndent(elseToken, indent, excludeCommas);
+
+ if (!isNodeFirstInLine(node.alternate)) {
+ checkNodeIndent(node.alternate, indent, excludeCommas);
+ }
+ }
}
/**
@@ -278,14 +288,7 @@ module.exports = {
* @returns {void}
*/
function checkNodesIndent(nodes, indent, excludeCommas) {
- nodes.forEach(function(node) {
- if (node.type === "IfStatement" && node.alternate) {
- const elseToken = sourceCode.getTokenBefore(node.alternate);
-
- checkNodeIndent(elseToken, indent, excludeCommas);
- }
- checkNodeIndent(node, indent, excludeCommas);
- });
+ nodes.forEach(node => checkNodeIndent(node, indent, excludeCommas));
}
/**
diff --git a/tests/lib/rules/indent.js b/tests/lib/rules/indent.js
index <HASH>..<HASH> 100644
--- a/tests/lib/rules/indent.js
+++ b/tests/lib/rules/indent.js
@@ -1395,6 +1395,17 @@ ruleTester.run("indent", rule, {
"foo = bar.baz()\n" +
" .bip();",
options: [4, {MemberExpression: 1}]
+ },
+ {
+ code:
+ "if (foo) {\n" +
+ " bar();\n" +
+ "} else if (baz) {\n" +
+ " foobar();\n" +
+ "} else if (qux) {\n" +
+ " qux();\n" +
+ "}",
+ options: [2]
}
],
invalid: [
@@ -2435,6 +2446,79 @@ ruleTester.run("indent", rule, {
" .bar",
options: [2, { MemberExpression: 2 }],
errors: expectedErrors([[2, 4, 2, "Punctuator"], [3, 4, 2, "Punctuator"]])
+ },
+ {
+
+ // Indentation with multiple else statements: https://github.com/eslint/eslint/issues/6956
+
+ code:
+ "if (foo) bar();\n" +
+ "else if (baz) foobar();\n" +
+ " else if (qux) qux();",
+ output:
+ "if (foo) bar();\n" +
+ "else if (baz) foobar();\n" +
+ "else if (qux) qux();",
+ options: [2],
+ errors: expectedErrors([3, 0, 2, "Keyword"])
+ },
+ {
+ code:
+ "if (foo) bar();\n" +
+ "else if (baz) foobar();\n" +
+ " else qux();",
+ output:
+ "if (foo) bar();\n" +
+ "else if (baz) foobar();\n" +
+ "else qux();",
+ options: [2],
+ errors: expectedErrors([3, 0, 2, "Keyword"])
+ },
+ {
+ code:
+ "foo();\n" +
+ " if (baz) foobar();\n" +
+ " else qux();",
+ output:
+ "foo();\n" +
+ "if (baz) foobar();\n" +
+ "else qux();",
+ options: [2],
+ errors: expectedErrors([[2, 0, 2, "IfStatement"], [3, 0, 2, "Keyword"]])
+ },
+ {
+ code:
+ "if (foo) bar();\n" +
+ "else if (baz) foobar();\n" +
+ " else if (bip) {\n" +
+ " qux();\n" +
+ " }",
+ output:
+ "if (foo) bar();\n" +
+ "else if (baz) foobar();\n" +
+ "else if (bip) {\n" +
+ " qux();\n" + // (fixed on the next pass)
+ " }",
+ options: [2],
+ errors: expectedErrors([3, 0, 5, "Keyword"])
+ },
+ {
+ code:
+ "if (foo) bar();\n" +
+ "else if (baz) {\n" +
+ " foobar();\n" +
+ " } else if (boop) {\n" +
+ " qux();\n" +
+ " }",
+ output:
+ "if (foo) bar();\n" +
+ "else if (baz) {\n" +
+ " foobar();\n" +
+ "} else if (boop) {\n" +
+ " qux();\n" + // (fixed on the next pass)
+ " }",
+ options: [2],
+ errors: expectedErrors([[3, 2, 4, "ExpressionStatement"], [4, 0, 5, "BlockStatement"]])
}
]
});
|
Fix: false negative of `indent` with `else if` statements (fixes #<I>) (#<I>)
|
eslint_eslint
|
train
|
1b976454352d92680ef25cf9f196b48952f70581
|
diff --git a/test/test_hashers.py b/test/test_hashers.py
index <HASH>..<HASH> 100644
--- a/test/test_hashers.py
+++ b/test/test_hashers.py
@@ -16,8 +16,12 @@
from __future__ import unicode_literals
from collections import OrderedDict
+from unittest import skipUnless
+import passlib
from passlib import hash
+from pkg_resources import parse_version
+from pkg_resources import SetuptoolsVersion
from django.contrib.auth.hashers import check_password
from django.contrib.auth.hashers import make_password
@@ -231,6 +235,18 @@ class hex_sha512_test(TestCase, TestMixin):
hasher = hashers_passlib.hex_sha512()
+@skipUnless(parse_version(passlib.__version__) >= SetuptoolsVersion('1.7'),
+ 'argon2 is not supported in passlib 1.6')
+class argon2_test(TestConverterMixin, TestCase):
+ hasher = hashers_passlib.argon2()
+
+
+@skipUnless(parse_version(passlib.__version__) >= SetuptoolsVersion('1.7'),
+ 'scrypt is not supported in passlib 1.6')
+class scrypt_test(TestCase, TestMixin):
+ hasher = hashers_passlib.argon2()
+
+
class bcrypt_test(TestConverterMixin, TestCase):
hasher = 'django.contrib.auth.hashers.BCryptPasswordHasher'
converter = converters.bcrypt()
|
add tests for argon2/scrypt
|
mathiasertl_django-hashers-passlib
|
train
|
4b8ab797b4653d8764c687e73cb630c32ae8bb4b
|
diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
index <HASH>..<HASH> 100644
--- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
+++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
@@ -105,6 +105,15 @@ module ActionDispatch
opts = options.except(:action, :routing_type)
+ if options[:action] == 'new'
+ inflection = SINGULAR_ROUTE_KEY
+ else
+ inflection = ROUTE_KEY
+ end
+
+ prefix = action_prefix options
+ suffix = routing_type options
+
case record_or_hash_or_array
when Array
if record_or_hash_or_array.empty? || record_or_hash_or_array.any?(&:nil?)
@@ -114,29 +123,57 @@ module ActionDispatch
recipient = record_or_hash_or_array.shift
end
- record_list = record_or_hash_or_array.dup
- record = record_list.pop
+ method, args = handle_list record_or_hash_or_array,
+ prefix,
+ suffix,
+ inflection
when Hash
unless record_or_hash_or_array[:id]
raise ArgumentError, "Nil location provided. Can't build URI."
end
opts = record_or_hash_or_array.dup.merge!(opts)
- record_list = []
record = opts.delete(:id)
+
+ method, args = handle_model record,
+ prefix,
+ suffix,
+ inflection
+ when String, Symbol
+ args = []
+ method = prefix + "#{record_or_hash_or_array}_#{suffix}"
+ when Class
+ method, args = handle_class record_or_hash_or_array,
+ prefix,
+ suffix,
+ inflection
+
when nil
raise ArgumentError, "Nil location provided. Can't build URI."
else
-
- record_list = []
- record = record_or_hash_or_array
+ method, args = handle_model record_or_hash_or_array,
+ prefix,
+ suffix,
+ inflection
end
- if options[:action] == 'new'
- inflection = lambda { |name| name.singular_route_key }
+
+ if opts.empty?
+ recipient.send(method, *args)
else
- inflection = lambda { |name| name.route_key }
+ recipient.send(method, *args, opts)
end
+ end
+
+ # Returns the path component of a URL for the given record. It uses
+ # <tt>polymorphic_url</tt> with <tt>routing_type: :path</tt>.
+ def polymorphic_path(record_or_hash_or_array, options)
+ polymorphic_url(record_or_hash_or_array, options.merge(:routing_type => :path))
+ end
+
+ def handle_list(list, prefix, suffix, inflection)
+ record_list = list.dup
+ record = record_list.pop
args = []
@@ -168,21 +205,10 @@ module ActionDispatch
end
end
- route << routing_type(options)
-
- named_route = action_prefix(options) + route.join("_")
-
- if opts.empty?
- recipient.send(named_route, *args)
- else
- recipient.send(named_route, *args, opts)
- end
- end
+ route << suffix
- # Returns the path component of a URL for the given record. It uses
- # <tt>polymorphic_url</tt> with <tt>routing_type: :path</tt>.
- def polymorphic_path(record_or_hash_or_array, options = {})
- polymorphic_url(record_or_hash_or_array, options.merge(:routing_type => :path))
+ named_route = prefix + route.join("_")
+ [named_route, args]
end
%w(edit new).each do |action|
@@ -202,6 +228,38 @@ module ActionDispatch
end
private
+ ROUTE_KEY = lambda { |name| name.route_key }
+ SINGULAR_ROUTE_KEY = lambda { |name| name.singular_route_key }
+
+ def handle_model(record, prefix, suffix, inflection)
+ args = []
+
+ model = record.to_model
+ name = if record.persisted?
+ args << model
+ model.class.model_name.singular_route_key
+ else
+ inflection.call model.class.model_name
+ end
+
+ named_route = prefix + "#{name}_#{suffix}"
+
+ [named_route, args]
+ end
+
+ def handle_class(klass, prefix, suffix, inflection)
+ name = inflection.call klass.model_name
+ [prefix + "#{name}_#{suffix}", []]
+ end
+
+ def model_path_helper_call(record)
+ handle_model record, ''.freeze, "path".freeze, ROUTE_KEY
+ end
+
+ def class_path_helper_call(klass)
+ handle_class klass, ''.freeze, "path".freeze, ROUTE_KEY
+ end
+
def action_prefix(options)
options[:action] ? "#{options[:action]}_" : ''
end
@@ -212,4 +270,3 @@ module ActionDispatch
end
end
end
-
diff --git a/actionview/lib/action_view/routing_url_for.rb b/actionview/lib/action_view/routing_url_for.rb
index <HASH>..<HASH> 100644
--- a/actionview/lib/action_view/routing_url_for.rb
+++ b/actionview/lib/action_view/routing_url_for.rb
@@ -85,8 +85,12 @@ module ActionView
_back_url
when Array
polymorphic_path(options, options.extract_options!)
+ when Class
+ method = class_path_helper_call options
+ send method
else
- polymorphic_path(options)
+ method, args = model_path_helper_call options
+ send(method, *args)
end
end
|
break each polymorphic type to it's own method
|
rails_rails
|
train
|
9f49be9d5e879791c83170df85d0623b5f90307b
|
diff --git a/iktomi/forms/fields.py b/iktomi/forms/fields.py
index <HASH>..<HASH> 100644
--- a/iktomi/forms/fields.py
+++ b/iktomi/forms/fields.py
@@ -455,4 +455,3 @@ class FileField(Field):
return False
return True
-
diff --git a/iktomi/forms/widgets.py b/iktomi/forms/widgets.py
index <HASH>..<HASH> 100644
--- a/iktomi/forms/widgets.py
+++ b/iktomi/forms/widgets.py
@@ -126,23 +126,29 @@ class Select(Widget):
def get_options(self, value):
options = []
- if not self.multiple and (value == '' or not self.field.conv.required):
- options = [{'value': '',
- 'title': self.null_label,
- 'selected': value in (None, '')}]
+
# XXX ugly
choice_conv = self.field.conv
if isinstance(choice_conv, convs.ListOf):
choice_conv = choice_conv.conv
assert isinstance(choice_conv, convs.EnumChoice)
+ has_null_value = False
+
values = value if self.multiple else [value]
values = map(unicode, values)
for choice, label in choice_conv.options():
choice = unicode(choice)
+ has_null_value = has_null_value or choice == ''
options.append(dict(value=choice,
title=label,
selected=(choice in values)))
+
+ if not self.multiple and not has_null_value and \
+ (value == '' or not self.field.conv.required):
+ options.insert(0, {'value': '',
+ 'title': self.null_label,
+ 'selected': value in (None, '')})
return options
def prepare_data(self):
diff --git a/tests/forms/widgets.py b/tests/forms/widgets.py
index <HASH>..<HASH> 100644
--- a/tests/forms/widgets.py
+++ b/tests/forms/widgets.py
@@ -356,6 +356,25 @@ class TestSelect(TestFormClass):
self.assertEqual(options, [('1', 'first', False),
('2', 'second', False)])
+ def test_render_enum_boolean(self):
+ class F(Form):
+ fields = [
+ Field('name',
+ conv=convs.EnumChoice(conv=convs.Bool(),
+ required=True,
+ choices=[(False, u'no'),
+ (True, u'yes')]),
+ initial=False,
+ widget=self.widget())
+ ]
+
+ form = F(self.env)
+ render = form.get_field('name').widget.render()
+ html = self.parse(render)
+ options = self.get_options(html)
+ self.assertEqual(options, [('', 'no', True),
+ ('checked', 'yes', False)])
+
class TestCheckBoxSelect(TestSelect):
|
fixed a bug with null value in select choices
|
SmartTeleMax_iktomi
|
train
|
63bf8649cacf140911703e74c1f8506a3992a600
|
diff --git a/src/KrToolBaseClass.php b/src/KrToolBaseClass.php
index <HASH>..<HASH> 100644
--- a/src/KrToolBaseClass.php
+++ b/src/KrToolBaseClass.php
@@ -32,6 +32,7 @@ class KrToolBaseClass {
protected function outputException( Exception $e ) {
global $kgBase;
+ http_response_code( 500 );
$kgBase->addOut( $e->getMessage() . "\n" . $e->getTraceAsString() , 'pre' );
}
|
Return <I> in case of exception
|
Krinkle_toollabs-base
|
train
|
45f36c8eb5d5aa7fb6df6dccda5f6c0ac5666354
|
diff --git a/polyaxon_cli/cli/upload.py b/polyaxon_cli/cli/upload.py
index <HASH>..<HASH> 100644
--- a/polyaxon_cli/cli/upload.py
+++ b/polyaxon_cli/cli/upload.py
@@ -37,10 +37,12 @@ def upload(sync=True): # pylint:disable=assign-to-new-keyword
Printer.print_error(
'Could not upload code for project `{}`.'.format(project.name))
Printer.print_error('Error message `{}`.'.format(e))
- Printer.print_error('Check if you have access rights for this project and '
- 'that you are not uploading large files.'
- 'If you are running a notebook, '
- 'you should stop it before uploading.')
+ Printer.print_error(
+ 'Check the project exists, '
+ 'and that you have access rights, '
+ 'this could happen as well when uploading large files.'
+ 'If you are running a notebook and mounting the code to the notebook, '
+ 'you should stop it before uploading.')
sys.exit(1)
Printer.print_success('Files uploaded.')
except Exception as e:
|
Update list of possible errors when uploading code
|
polyaxon_polyaxon
|
train
|
31996062388371a938af0bcce1ea05989aff07e3
|
diff --git a/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskSubmissionTestEnvironment.java b/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskSubmissionTestEnvironment.java
index <HASH>..<HASH> 100644
--- a/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskSubmissionTestEnvironment.java
+++ b/flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskSubmissionTestEnvironment.java
@@ -44,7 +44,6 @@ import org.apache.flink.runtime.leaderretrieval.SettableLeaderRetrievalService;
import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups;
import org.apache.flink.runtime.rpc.MainThreadExecutable;
import org.apache.flink.runtime.rpc.RpcService;
-import org.apache.flink.runtime.rpc.RpcUtils;
import org.apache.flink.runtime.rpc.TestingRpcService;
import org.apache.flink.runtime.shuffle.ShuffleEnvironment;
import org.apache.flink.runtime.state.TaskExecutorLocalStateStoresManager;
@@ -277,7 +276,7 @@ class TaskSubmissionTestEnvironment implements AutoCloseable {
@Override
public void close() throws Exception {
- RpcUtils.terminateRpcEndpoint(taskExecutor, timeout);
+ testingRpcService.stopService().join();
timerService.stop();
|
[FLINK-<I>] Stop TaskSubmissionTestEnvironment.testingRpcService when closing the environment
This closes #<I>.
|
apache_flink
|
train
|
1d298ea5cfe63e56335b3bc0f401ce17c5f5f36f
|
diff --git a/core/dbt/graph/selector.py b/core/dbt/graph/selector.py
index <HASH>..<HASH> 100644
--- a/core/dbt/graph/selector.py
+++ b/core/dbt/graph/selector.py
@@ -338,20 +338,20 @@ class Graph:
ancestors_for = self.select_children(selected) | selected
return self.select_parents(ancestors_for) | ancestors_for
- def descendants(self, node, max_depth: int = None):
+ def descendants(self, node, max_depth: Optional[int] = None) -> Set[str]:
"""Returns all nodes reachable from `node` in `graph`"""
if not self.graph.has_node(node):
- raise nx.NetworkXError(f"The node {node} is not in the graph.")
+ raise InternalException(f'Node {node} not found in the graph!')
des = nx.single_source_shortest_path_length(G=self.graph,
source=node,
cutoff=max_depth)\
.keys()
return des - {node}
- def ancestors(self, node, max_depth: int = None):
+ def ancestors(self, node, max_depth: Optional[int] = None) -> Set[str]:
"""Returns all nodes having a path to `node` in `graph`"""
if not self.graph.has_node(node):
- raise nx.NetworkXError(f"The node {node} is not in the graph.")
+ raise InternalException(f'Node {node} not found in the graph!')
with nx.utils.reversed(self.graph):
anc = nx.single_source_shortest_path_length(G=self.graph,
source=node,
@@ -361,7 +361,7 @@ class Graph:
def select_children(self,
selected: Set[str],
- max_depth: int = None) -> Set[str]:
+ max_depth: Optional[int] = None) -> Set[str]:
descendants: Set[str] = set()
for node in selected:
descendants.update(self.descendants(node, max_depth=max_depth))
@@ -369,7 +369,7 @@ class Graph:
def select_parents(self,
selected: Set[str],
- max_depth: int = None) -> Set[str]:
+ max_depth: Optional[int] = None) -> Set[str]:
ancestors: Set[str] = set()
for node in selected:
ancestors.update(self.ancestors(node, max_depth=max_depth))
|
Added type annotations and errors types refactored
|
fishtown-analytics_dbt
|
train
|
fef0567746ade52943e4dfd6adfeb8341e015d02
|
diff --git a/uncompyle6/parsers/parse33.py b/uncompyle6/parsers/parse33.py
index <HASH>..<HASH> 100644
--- a/uncompyle6/parsers/parse33.py
+++ b/uncompyle6/parsers/parse33.py
@@ -12,8 +12,21 @@ class Python33Parser(Python32Parser):
def p_33on(self, args):
"""
# Python 3.3+ adds yield from.
- expr ::= yield_from
- yield_from ::= expr expr YIELD_FROM
+ expr ::= yield_from
+ yield_from ::= expr expr YIELD_FROM
+
+ # We do the grammar hackery below for semantics
+ # actions that want c_stmts_opt at index 1
+
+ iflaststmt ::= testexpr c_stmts_opt33
+ iflaststmtl ::= testexpr c_stmts_opt
+ c_stmts_opt33 ::= JUMP_BACK JUMP_ABSOLUTE c_stmts_opt
+ _ifstmts_jump ::= c_stmts_opt JUMP_FORWARD _come_from
+
+ # Python 3.3+ has more loop optimization that removes
+ # JUMP_FORWARD in some cases, and hence we also don't
+ # see COME_FROM
+ _ifstmts_jump ::= c_stmts_opt
"""
class Python33ParserSingle(Python33Parser, PythonParserSingle):
diff --git a/uncompyle6/parsers/parse34.py b/uncompyle6/parsers/parse34.py
index <HASH>..<HASH> 100644
--- a/uncompyle6/parsers/parse34.py
+++ b/uncompyle6/parsers/parse34.py
@@ -15,26 +15,12 @@ class Python34Parser(Python33Parser):
def p_misc34(self, args):
"""
- # Python 3.5+ optimizes the trailing two JUMPS away
+ # Python 3.4+ optimizes the trailing two JUMPS away
for_block ::= l_stmts
- iflaststmtl ::= testexpr c_stmts_opt
-
- _ifstmts_jump ::= c_stmts_opt JUMP_FORWARD _come_from
-
- # We do the grammar hackery below for semantics
- # actions that want c_stmts_opt at index 1
- iflaststmt ::= testexpr c_stmts_opt34
- c_stmts_opt34 ::= JUMP_BACK JUMP_ABSOLUTE c_stmts_opt
-
# Is this 3.4 only?
yield_from ::= expr GET_ITER LOAD_CONST YIELD_FROM
-
- # Python 3.4+ has more loop optimization that removes
- # JUMP_FORWARD in some cases, and hence we also don't
- # see COME_FROM
- _ifstmts_jump ::= c_stmts_opt
"""
class Python34ParserSingle(Python34Parser, PythonParserSingle):
pass
|
Some Python <I> grammar rules apply to Python <I>
|
rocky_python-uncompyle6
|
train
|
29223e17ac2ba7d686611c67affff49ffe814dce
|
diff --git a/modules/custom/mentions/src/Form/MentionsSettingsForm.php b/modules/custom/mentions/src/Form/MentionsSettingsForm.php
index <HASH>..<HASH> 100644
--- a/modules/custom/mentions/src/Form/MentionsSettingsForm.php
+++ b/modules/custom/mentions/src/Form/MentionsSettingsForm.php
@@ -7,7 +7,6 @@ use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\ContentEntityTypeInterface;
-use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@@ -15,7 +14,6 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
*/
class MentionsSettingsForm extends ConfigFormBase {
- use StringTranslationTrait;
/**
* The entity type manager service.
|
Issue #<I> by tekNorah: StringTranslationTrait define the same [error] property (#<I>)
|
goalgorilla_open_social
|
train
|
594448499b1248b5a742ff7ffbcbc82c92b4bbd2
|
diff --git a/forms/FieldList.php b/forms/FieldList.php
index <HASH>..<HASH> 100644
--- a/forms/FieldList.php
+++ b/forms/FieldList.php
@@ -267,10 +267,7 @@ class FieldList extends ArrayList {
if(is_a($parentPointer, 'TabSet')) {
// use $title on the innermost tab only
if ($k == $last_idx) {
- if (!isset($title)) {
- $title = $part;
- }
- $currentPointer = new Tab($part, $title);
+ $currentPointer = isset($title) ? new Tab($part, $title) : new Tab($part);
}
else {
$currentPointer = new TabSet($part);
|
BUGFIX: Don't try to set the title if it hasn't been set for us.
This enables the new code to pass the existing tests.
|
silverstripe_silverstripe-framework
|
train
|
5acfc42d9d3d2982b1d5eb3420449b01a431600f
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -75,11 +75,11 @@ class Griddle extends Component {
settingsComponentObjects,
selectors,
styleConfig: defaultStyleConfig,
+
pageProperties: {
currentPage: 1,
pageSize: 10
},
-
enableSettings: true,
textProperties: {
next: 'Next',
diff --git a/src/module.d.ts b/src/module.d.ts
index <HASH>..<HASH> 100644
--- a/src/module.d.ts
+++ b/src/module.d.ts
@@ -383,6 +383,7 @@ interface GriddleExtensibility {
interface GriddleInitialState {
enableSettings?: boolean;
+ pageProperties?: GriddlePageProperties;
sortMethod?: (data: any[], column: string, sortAscending?: boolean) => number;
textProperties?: {
next?: string,
@@ -402,7 +403,6 @@ export interface GriddleProps<T> extends GriddlePlugin, GriddleInitialState {
plugins?: GriddlePlugin[];
data?: T[];
sortProperties?: GriddleSortKey[];
- pageProperties?: GriddlePageProperties;
storeKey?: string;
}
diff --git a/src/utils/__tests__/initilizerTests.js b/src/utils/__tests__/initilizerTests.js
index <HASH>..<HASH> 100644
--- a/src/utils/__tests__/initilizerTests.js
+++ b/src/utils/__tests__/initilizerTests.js
@@ -7,7 +7,6 @@ import { getRowProperties } from '../rowUtils';
const expectedDefaultInitialState = {
data: [],
- pageProperties: {},
renderProperties: {
rowProperties: null,
columnProperties: {},
diff --git a/src/utils/initializer.js b/src/utils/initializer.js
index <HASH>..<HASH> 100644
--- a/src/utils/initializer.js
+++ b/src/utils/initializer.js
@@ -12,7 +12,6 @@ module.exports = function initializer(defaults) {
settingsComponentObjects,
selectors,
styleConfig: defaultStyleConfig,
- pageProperties: defaultPageProperties,
...defaultInitialState
} = defaults;
@@ -23,7 +22,6 @@ module.exports = function initializer(defaults) {
events: userEvents = {},
sortProperties = {},
styleConfig: userStyleConfig = {},
- pageProperties: userPageProperties,
components: userComponents,
renderProperties: userRenderProperties = {},
settingsComponentObjects: userSettingsComponentObjects,
@@ -61,7 +59,6 @@ module.exports = function initializer(defaults) {
...plugins.map(p => p.styleConfig),
userStyleConfig);
- const pageProperties = Object.assign({}, defaultPageProperties, userPageProperties);
// TODO: This should also look at the default and plugin initial state objects
const renderProperties = Object.assign({
@@ -76,7 +73,6 @@ module.exports = function initializer(defaults) {
userInitialState,
{
data,
- pageProperties,
renderProperties,
sortProperties,
styleConfig,
|
Avoid special treatment for pageProperties
|
GriddleGriddle_Griddle
|
train
|
40ffaa05eb92f219c1cdec811fa2e07e91d5d0e0
|
diff --git a/src/adapt/ops.js b/src/adapt/ops.js
index <HASH>..<HASH> 100644
--- a/src/adapt/ops.js
+++ b/src/adapt/ops.js
@@ -1157,7 +1157,7 @@ adapt.ops.OPSDocStore.prototype.parseOPSResource = function(response) {
if (index < sources.length) {
var source = sources[index++];
sph.startStylesheet(source.flavor);
- if (source.text) {
+ if (source.text !== null) {
return adapt.cssparse.parseStylesheetFromText(source.text, sph, source.url, source.classes, source.media);
} else {
return adapt.cssparse.parseStylesheetFromURL(source.url, sph, source.classes, source.media);
|
Avoid unnecessary and incorrect CSS parsing when a viewport meta element is present
- When the style sheet text is an empty string and not null, it should be parsed as a style sheet text.
|
vivliostyle_vivliostyle.js
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.