hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
623c7fa95d90d31f924c40bc40ad7fb4688063bb
diff --git a/simulator/simulator.go b/simulator/simulator.go index <HASH>..<HASH> 100644 --- a/simulator/simulator.go +++ b/simulator/simulator.go @@ -390,7 +390,7 @@ func (s *Service) findDatastore(query url.Values) (*Datastore, error) { ctx := context.Background() finder := find.NewFinder(s.client, false) - dc, err := finder.DatacenterOrDefault(ctx, query.Get("dcName")) + dc, err := finder.DatacenterOrDefault(ctx, query.Get("dcPath")) if err != nil { return nil, err }
Change key name according to Datacenter object
vmware_govmomi
train
8ab77a88ec4447526c1a785d832f4e9dc3d352f3
diff --git a/shap/plots/waterfall.py b/shap/plots/waterfall.py index <HASH>..<HASH> 100644 --- a/shap/plots/waterfall.py +++ b/shap/plots/waterfall.py @@ -12,7 +12,14 @@ from . import colors def waterfall_plot(expected_value, shap_values, features=None, feature_names=None, max_display=10, show=True): - """ Plots an explantion of a single prediction as a waterfall. + """ Plots an explantion of a single prediction as a waterfall plot. + + The SHAP value of a feature represents the impact of the evidence provided by that feature on the model's + output. The waterfall plot is designed to visually display how the SHAP values (evidence) of each feature + move the model output from our prior expectation under the background data distribution, to the final model + prediction given the evidence of all the features. Features are sorted by the magnitude of their SHAP values + with the smallest magnitude features grouped together at the bottom of the plot when the number of features + in the models exceeds the max_display parameter. Parameters ---------- @@ -45,6 +52,9 @@ def waterfall_plot(expected_value, shap_values, features=None, feature_names=Non "Try shap.waterfall_plot(explainer.expected_value, shap_values[0], X[0]) or " \ "for multi-output models try " \ "shap.waterfall_plot(explainer.expected_value[0], shap_values[0][0], X[0]).") + + if len(shap_values.shape) == 2: + raise Exception("The waterfall_plot can currently only plot a single explanation but a matrix of explanations was passed!") # unwrap pandas series if safe_isinstance(features, "pandas.core.series.Series"):
Add better docs to waterfall_plot, fix #<I>
slundberg_shap
train
6c44763e008a0f69d1f20852472fb9d89032691b
diff --git a/itests/itest_utils.py b/itests/itest_utils.py index <HASH>..<HASH> 100644 --- a/itests/itest_utils.py +++ b/itests/itest_utils.py @@ -2,6 +2,9 @@ import errno from functools import wraps import os import signal +import sys +import threading +import re import time import requests @@ -64,7 +67,14 @@ def get_marathon_connection_string(): return 'localhost:8080' else: service_port = get_service_internal_port('marathon') - return get_compose_service('marathon').get_container().get_local_port(service_port) + local_port = get_compose_service('marathon').get_container().get_local_port(service_port) + + # Check if we're at OSX. Use ip from DOCKER_HOST + if sys.platform == 'darwin': + m = re.match("(.*?)://(.*?):(\d+)", os.environ["DOCKER_HOST"]) + local_port = "{}:{}".format(m.group(2), local_port.split(":")[1]) + + return local_port def get_service_internal_port(service_name):
Make it possible to run itests at osx with docker-machine
thefactory_marathon-python
train
071c730371eb0151d4d3d511b354d618c57d8acc
diff --git a/telemetry/telemetry/util/find_dependencies.py b/telemetry/telemetry/util/find_dependencies.py index <HASH>..<HASH> 100644 --- a/telemetry/telemetry/util/find_dependencies.py +++ b/telemetry/telemetry/util/find_dependencies.py @@ -210,6 +210,12 @@ def ZipDependencies(paths, dependencies, options): gsutil_dependencies -= FindExcludedFiles( set(gsutil_dependencies), options) + # Also add upload.py to the archive from depot_tools, if it is available. + # This allows us to post patches without requiring a full depot_tools + # install. There's no real point in including upload.py if we do not + # also have gsutil, which is why this is inside the gsutil block. + gsutil_dependencies.add(os.path.join(gsutil_base_dir, 'upload.py')) + for path in gsutil_dependencies: path_in_archive = os.path.join( 'telemetry', os.path.relpath(util.GetTelemetryDir(), base_dir),
Add Rietveld's upload.py to the standalone telemetry archive By adding upload.py to the archive, we can submit patches to telemetry without requiring a full depot_tools checkout. This helps ensure that the standalone zip really is sufficient for telemetry development. R=<EMAIL>, <EMAIL> BUG=<I> Review URL: <URL>
catapult-project_catapult
train
54c24f8d0029ce32beb4cd403910fb83b62651f9
diff --git a/src/Query/Builder.php b/src/Query/Builder.php index <HASH>..<HASH> 100644 --- a/src/Query/Builder.php +++ b/src/Query/Builder.php @@ -265,6 +265,18 @@ class Builder } /** + * Alias for setting the base DN of the query. + * + * @param string $dn + * + * @return Builder + */ + public function in($dn) + { + return $this->setDn($dn); + } + + /** * Performs the specified query on the current LDAP connection. * * @param string $query
Added 'in' method on query builder
Adldap2_Adldap2
train
527943fe53fe1836e8011053bab8a2797efe1030
diff --git a/mistletoe/block_token.py b/mistletoe/block_token.py index <HASH>..<HASH> 100644 --- a/mistletoe/block_token.py +++ b/mistletoe/block_token.py @@ -400,7 +400,7 @@ class TableRow(BlockToken): """ def __init__(self, line, row_align=None): self.row_align = row_align or [None] - cells = line[1:-2].split('|') + cells = filter(None, line.strip().split('|')) self._children = (TableCell(cell.strip(), align) for cell, align in zip_longest(cells, self.row_align)) diff --git a/test/test_block_token.py b/test/test_block_token.py index <HASH>..<HASH> 100644 --- a/test/test_block_token.py +++ b/test/test_block_token.py @@ -251,6 +251,14 @@ class TestTableRow(unittest.TestCase): token.children mock.assert_has_calls([call('cell 1', None), call('cell 2', None)]) + def test_easy_table_row(self): + with patch('mistletoe.block_token.TableCell') as mock: + line = 'cell 1 | cell 2\n' + token = block_token.TableRow(line) + self.assertEqual(token.row_align, [None]) + token.children + mock.assert_has_calls([call('cell 1', None), call('cell 2', None)]) + class TestTableCell(TestToken): def test_match(self):
fixed: TableRow now supports table shorthand (#<I>)
miyuchina_mistletoe
train
5d62fed21040aca713d1542257725842c0cff4d1
diff --git a/core/lib/generators/refinery/cms/cms_generator.rb b/core/lib/generators/refinery/cms/cms_generator.rb index <HASH>..<HASH> 100644 --- a/core/lib/generators/refinery/cms/cms_generator.rb +++ b/core/lib/generators/refinery/cms/cms_generator.rb @@ -31,11 +31,11 @@ module Refinery next unless destination_path.join(env).file? gsub_file env, "config.assets.compile = false", "config.assets.compile = true", :verbose => false - end - insert_into_file "config/environments/production.rb", - " # Refinery has set config.assets.initialize_on_precompile = false by default.\n config.assets.initialize_on_precompile = false\n\n", - :after => "Application.configure do\n" + insert_into_file env, + " # Refinery has set config.assets.initialize_on_precompile = false by default.\n config.assets.initialize_on_precompile = false\n\n", + :after => "Application.configure do\n" if env == 'production' + end # Stop pretending if destination_path == Refinery.root
Use existing logic which checks for existence of the environment files first before trying to insert_into_file on a nonexistent file.
refinery_refinerycms
train
cd940cc375ef8feeaae00987314495fe426e71ae
diff --git a/index/firestorm/dict_updater_test.go b/index/firestorm/dict_updater_test.go index <HASH>..<HASH> 100644 --- a/index/firestorm/dict_updater_test.go +++ b/index/firestorm/dict_updater_test.go @@ -55,6 +55,9 @@ func TestDictUpdater(t *testing.T) { if err != nil { t.Fatal(err) } + if v == nil { + t.Fatal("unexpected dictionary value missing") + } dr, err := NewDictionaryRowKV([]byte(key), v) if err != nil { t.Fatal(err)
add another check to try to understand test failure on travis
blevesearch_bleve
train
c6711775233b0ba1ae65c590707e8ce3aabe34ab
diff --git a/src/AbstractPluginManager.php b/src/AbstractPluginManager.php index <HASH>..<HASH> 100644 --- a/src/AbstractPluginManager.php +++ b/src/AbstractPluginManager.php @@ -102,6 +102,25 @@ abstract class AbstractPluginManager extends ServiceManager } /** + * Register a service with the locator. + * + * Validates that the service object via validatePlugin() prior to + * attempting to register it. + * + * @param string $name + * @param mixed $service + * @param bool $shared + * @return AbstractPluginManager + * @throws Exception\InvalidServiceNameException + */ + public function setService($name, $service, $shared = true) + { + $this->validatePlugin($service); + parent::setService($name, $service, $shared); + return $this; + } + + /** * Attempt to create an instance via an invokable class * * Overrides parent implementation by passing $creationOptions to the
Refactored Log to use AbstractPluginManager - Removed WriterBroker and WriterLoader - Added WriterPluginManager - Modified Logger to use WriterPluginManager - Overrode setService() in AbstractPluginManager in order to validate the service before registering it.
mxc-commons_mxc-servicemanager
train
a7066c99beb9c5f302606a4d2c56e92f59500820
diff --git a/src/flask_allows/allows.py b/src/flask_allows/allows.py index <HASH>..<HASH> 100644 --- a/src/flask_allows/allows.py +++ b/src/flask_allows/allows.py @@ -51,9 +51,10 @@ class Allows(object): self.additional.push(Additional()) @app.after_request - def cleanup(*a, **k): + def cleanup(response): self.clear_all_overrides() self.clear_all_additional() + return response def requires(self, *requirements, **opts): """
Do not swallow response in cleanup handler
justanr_flask-allows
train
22fcbe90bb2bfd82453cfff4cdbbd7bd95ffcfdd
diff --git a/h2o-core/src/main/java/water/fvec/RollupStats.java b/h2o-core/src/main/java/water/fvec/RollupStats.java index <HASH>..<HASH> 100644 --- a/h2o-core/src/main/java/water/fvec/RollupStats.java +++ b/h2o-core/src/main/java/water/fvec/RollupStats.java @@ -108,6 +108,7 @@ class RollupStats extends Iced { else if( c.at8(i)==0 ) zs++; int os = c._len-zs-nans; // Ones _nzCnt = os; + _naCnt = nans; for( int i=0; i<Math.min(_mins.length,zs); i++ ) { min(0); max(0); } for( int i=0; i<Math.min(_mins.length,os); i++ ) { min(1); max(1); } _rows = zs+os; @@ -284,8 +285,7 @@ class RollupStats extends Iced { _bins = new long[_nbins]; for( int i=c.nextNZ(-1); i< c._len; i=c.nextNZ(i) ) { double d = c.atd(i); - if( Double.isNaN(d) ) continue; - _bins[idx(d)]++; + if( !Double.isNaN(d) ) _bins[idx(d)]++; } // Sparse? We skipped all the zeros; do them now if( c.isSparse() ) @@ -336,8 +336,8 @@ class RollupStats extends Iced { } addToPendingCount(1); new Histo(new H2OCallback<Histo>(this){ - @Override - public void callback(Histo histo) { + @Override public void callback(Histo histo) { + assert ArrayUtils.sum(histo._bins)==rows; _rs._bins = histo._bins; // Compute percentiles from histogram _rs._pctiles = new double[Vec.PERCENTILES.length];
Bug miscounting NAs in CBS chunks Just didn't set the _naCnt field. Add assertion to catch future such errors
h2oai_h2o-3
train
892fa580b2a3f2627d7f1ae2a51453d7348aedb2
diff --git a/competency/tests/external_test.php b/competency/tests/external_test.php index <HASH>..<HASH> 100644 --- a/competency/tests/external_test.php +++ b/competency/tests/external_test.php @@ -826,12 +826,10 @@ class core_competency_external_testcase extends externallib_advanced_testcase { 'competencyframeworkid' => $framework->id, 'sortorder' => 0 ); - // TODO: MDL-69700 - Analyse if the throw exception is happening - // in the correct place and decide what happens with the trailing - // code that is never executed. + $this->expectException(invalid_parameter_exception::class); + $this->expectExceptionMessage('Invalid external api parameter'); $result = external::create_competency($competency); - $result = (object) external_api::clean_returnvalue(external::create_competency_returns(), $result); } /** diff --git a/lib/tests/exporter_test.php b/lib/tests/exporter_test.php index <HASH>..<HASH> 100644 --- a/lib/tests/exporter_test.php +++ b/lib/tests/exporter_test.php @@ -103,20 +103,17 @@ class core_exporter_testcase extends advanced_testcase { $exporter = new core_testable_exporter($this->invaliddata, $this->validrelated); $output = $PAGE->get_renderer('core'); + // The exception message is a bit misleading, it actually indicates an expected property wasn't found. $this->expectException(coding_exception::class); + $this->expectExceptionMessage('Unexpected property stringAformat'); $result = $exporter->export($output); } public function test_invalid_related() { - global $PAGE; - // TODO: MDL-69700 - Analyse if the throw exception is happening - // in the correct place and decide what happens with the trailing - // code that is never executed. $this->expectException(coding_exception::class); + $this->expectExceptionMessage('Exporter class is missing required related data: (core_testable_exporter) ' . + 'simplestdClass => stdClass'); $exporter = new core_testable_exporter($this->validdata, $this->invalidrelated); - $output = $PAGE->get_renderer('core'); - - $result = $exporter->export($output); } public function test_invalid_related_all_cases() {
MDL-<I> tests: clarify expected exceptions in unit tests. Resolves some leftovers from MDL-<I>, see d<I>c<I>.
moodle_moodle
train
f66fb369ee4c8b891e9bea30d9ae18fe010ee55b
diff --git a/phylotoast/graph_util.py b/phylotoast/graph_util.py index <HASH>..<HASH> 100755 --- a/phylotoast/graph_util.py +++ b/phylotoast/graph_util.py @@ -7,11 +7,20 @@ try: import statsmodels.nonparametric.kde as kde except ImportError: importerrors.append('statsmodels') + +try: + import matplotlib as mpl +except ImportError as ie: + errors.append('matplotlib') + if len(importerrors) != 0: for item in importerrors: print 'Import Error. Please install missing module:', item sys.exit() +from matplotlib.ticker import FuncFormatter, MaxNLocator, MultipleLocator +import matplotlib.pyplot as plt + def plot_kde(data, ax, title=None, color='r', fill_bt=True): """ @@ -41,3 +50,46 @@ def plot_kde(data, ax, title=None, color='r', fill_bt=True): if title is not None: t = ax.set_title(title) t.set_y(1.05) + +def ggplot2_style(ax): + """ + Styles an axes to appear like ggplot2 + Must be called after all plot and axis manipulation operations have been + carried out (needs to know final tick spacing) + """ + #set the style of the major and minor grid lines, filled blocks + ax.grid(True, 'major', color='w', linestyle='-', linewidth=1.4) + ax.grid(True, 'minor', color='0.92', linestyle='-', linewidth=0.7) + ax.patch.set_facecolor('0.85') + ax.set_axisbelow(True) + + #set minor tick spacing to 1/2 of the major ticks + ax.xaxis.set_minor_locator(MultipleLocator( (plt.xticks()[0][1]-plt.xticks()[0][0]) / 2.0 )) + ax.yaxis.set_minor_locator(MultipleLocator( (plt.yticks()[0][1]-plt.yticks()[0][0]) / 2.0 )) + + #remove axis border + for child in ax.get_children(): + if isinstance(child, mpl.spines.Spine): + child.set_alpha(0) + + #restyle the tick lines + for line in ax.get_xticklines() + ax.get_yticklines(): + line.set_markersize(5) + line.set_color("gray") + line.set_markeredgewidth(1.4) + + #remove the minor tick lines + for line in ax.xaxis.get_ticklines(minor=True) + ax.yaxis.get_ticklines(minor=True): + line.set_markersize(0) + + #only show bottom left ticks, pointing out of axis + mpl.rcParams['xtick.direction'] = 'out' + mpl.rcParams['ytick.direction'] = 'out' + ax.xaxis.set_ticks_position('bottom') + ax.yaxis.set_ticks_position('left') + + + if ax.legend_ <> None: + lg = ax.legend_ + lg.get_frame().set_linewidth(0) + lg.get_frame().set_alpha(0.5) \ No newline at end of file
Adds method rstyle() to graph_util. This method takes a matplotlib Axis object and applies various styling parameters to make the resulting plot look similar to the default style in the R library ggplot2.
smdabdoub_phylotoast
train
f048e612a3905f34931127360bdd2def19a5e582
diff --git a/bootstrap.php b/bootstrap.php index <HASH>..<HASH> 100644 --- a/bootstrap.php +++ b/bootstrap.php @@ -11,45 +11,47 @@ use Symfony\Polyfill\Php72 as p; -if (PHP_VERSION_ID < 70200) { - if (!defined('PHP_FLOAT_DIG')) { - define('PHP_FLOAT_DIG', 15); - } - if (!defined('PHP_FLOAT_EPSILON')) { - define('PHP_FLOAT_EPSILON', 2.2204460492503E-16); - } - if (!defined('PHP_FLOAT_MIN')) { - define('PHP_FLOAT_MIN', 2.2250738585072E-308); - } - if (!defined('PHP_FLOAT_MAX')) { - define('PHP_FLOAT_MAX', 1.7976931348623157E+308); - } - if (!defined('PHP_OS_FAMILY')) { - define('PHP_OS_FAMILY', p\Php72::php_os_family()); - } +if (PHP_VERSION_ID >= 70200) { + return; +} + +if (!defined('PHP_FLOAT_DIG')) { + define('PHP_FLOAT_DIG', 15); +} +if (!defined('PHP_FLOAT_EPSILON')) { + define('PHP_FLOAT_EPSILON', 2.2204460492503E-16); +} +if (!defined('PHP_FLOAT_MIN')) { + define('PHP_FLOAT_MIN', 2.2250738585072E-308); +} +if (!defined('PHP_FLOAT_MAX')) { + define('PHP_FLOAT_MAX', 1.7976931348623157E+308); +} +if (!defined('PHP_OS_FAMILY')) { + define('PHP_OS_FAMILY', p\Php72::php_os_family()); +} - if ('\\' === DIRECTORY_SEPARATOR && !function_exists('sapi_windows_vt100_support')) { - function sapi_windows_vt100_support($stream, $enable = null) { return p\Php72::sapi_windows_vt100_support($stream, $enable); } - } - if (!function_exists('stream_isatty')) { - function stream_isatty($stream) { return p\Php72::stream_isatty($stream); } - } - if (!function_exists('utf8_encode')) { - function utf8_encode($s) { return p\Php72::utf8_encode($s); } - } - if (!function_exists('utf8_decode')) { - function utf8_decode($s) { return p\Php72::utf8_decode($s); } - } - if (!function_exists('spl_object_id')) { - function spl_object_id($s) { return p\Php72::spl_object_id($s); } - } - if (!function_exists('mb_ord')) { - function mb_ord($s, $enc = null) { return p\Php72::mb_ord($s, $enc); } - } - if (!function_exists('mb_chr')) { - function mb_chr($code, $enc = null) { return p\Php72::mb_chr($code, $enc); } - } - if (!function_exists('mb_scrub')) { - function mb_scrub($s, $enc = null) { $enc = null === $enc ? mb_internal_encoding() : $enc; return mb_convert_encoding($s, $enc, $enc); } - } +if ('\\' === DIRECTORY_SEPARATOR && !function_exists('sapi_windows_vt100_support')) { + function sapi_windows_vt100_support($stream, $enable = null) { return p\Php72::sapi_windows_vt100_support($stream, $enable); } +} +if (!function_exists('stream_isatty')) { + function stream_isatty($stream) { return p\Php72::stream_isatty($stream); } +} +if (!function_exists('utf8_encode')) { + function utf8_encode($s) { return p\Php72::utf8_encode($s); } +} +if (!function_exists('utf8_decode')) { + function utf8_decode($s) { return p\Php72::utf8_decode($s); } +} +if (!function_exists('spl_object_id')) { + function spl_object_id($s) { return p\Php72::spl_object_id($s); } +} +if (!function_exists('mb_ord')) { + function mb_ord($s, $enc = null) { return p\Php72::mb_ord($s, $enc); } +} +if (!function_exists('mb_chr')) { + function mb_chr($code, $enc = null) { return p\Php72::mb_chr($code, $enc); } +} +if (!function_exists('mb_scrub')) { + function mb_scrub($s, $enc = null) { $enc = null === $enc ? mb_internal_encoding() : $enc; return mb_convert_encoding($s, $enc, $enc); } }
Fix declaring extra constants when `intl` is loaded
symfony_polyfill-php72
train
c069eb4310c32e1fa711ea121eeac44e206cc167
diff --git a/ChangeLog b/ChangeLog index <HASH>..<HASH> 100644 --- a/ChangeLog +++ b/ChangeLog @@ -6,6 +6,7 @@ Change log for the astng package * include patch from Marien Zwart fixing some test / py 2.5 * fix #3651: crash when callable as defaut arg * fix #3670: subscription inference crash in some cases + * fix #3673: Lambda instance has no attribute 'pytype' 2007-02-22 -- 0.17.0 * api change to be able to infer using a context (used to infer function call diff --git a/scoped_nodes.py b/scoped_nodes.py index <HASH>..<HASH> 100644 --- a/scoped_nodes.py +++ b/scoped_nodes.py @@ -428,6 +428,7 @@ Lambda.format_args = FunctionNG.format_args.im_func Lambda.default_value = FunctionNG.default_value.im_func Lambda.mularg_class = FunctionNG.mularg_class.im_func Lambda.type = 'function' +Lambda.pytype = FunctionNG.pytype.im_func # Class ###################################################################### diff --git a/test/unittest_scoped_nodes.py b/test/unittest_scoped_nodes.py index <HASH>..<HASH> 100644 --- a/test/unittest_scoped_nodes.py +++ b/test/unittest_scoped_nodes.py @@ -146,6 +146,14 @@ class FunctionNodeTC(TestCase): ## self.assertEquals([str(term) for term in method.returns()], ## ["Const('toto')", "Const(None)"]) + def test_lambda_pytype(self): + data = ''' +def f(): + g = lambda: None + ''' + astng = abuilder.string_build(data, __name__, __file__) + g = list(astng['f'].ilookup('g'))[0] + self.failUnlessEqual(g.pytype(), '__builtin__.function') class ClassNodeTC(TestCase):
#<I>: Lambda instance has no attribute 'pytype'
PyCQA_astroid
train
57b8ce837f85e9990d85bf391963acec81378a22
diff --git a/plugins/CorePluginsAdmin/Controller.php b/plugins/CorePluginsAdmin/Controller.php index <HASH>..<HASH> 100644 --- a/plugins/CorePluginsAdmin/Controller.php +++ b/plugins/CorePluginsAdmin/Controller.php @@ -229,7 +229,7 @@ class Controller extends Plugin\ControllerAdmin if (isset($plugin['info']) && isset($plugin['info']['authors'])) { foreach ($plugin['info']['authors'] as $author) { - if (in_array(strtolower($author['name']), array('piwik', 'innocraft', 'matomo-org'))) { + if (in_array(strtolower($author['name']), array('piwik', 'innocraft', 'matomo', 'matomo-org'))) { $plugin['isOfficialPlugin'] = true; break; }
Fix AnonymousPiwikUsageMeasurement is shown as "third-party" (#<I>) This is because it is comparing here author name instead of owner... We will eventually need to change this to owner in the next version.
matomo-org_matomo
train
4c48486ac240a51a571700fae1f23473caa94216
diff --git a/addon/models/resource.js b/addon/models/resource.js index <HASH>..<HASH> 100644 --- a/addon/models/resource.js +++ b/addon/models/resource.js @@ -138,13 +138,33 @@ const Resource = Ember.Object.extend({ This is not a replace operation, but rather support for editing as a set. + Calling `updateRelationship` will call the service to persist the changes, + via it's `patchRelationship` method. Since the default `catch` for this + method is to rollback the relations, an optional `callback` function can be + used to handle the error response. + @method updateRelationship @param {String} relation @param {Array|String|null} ids + @param {Function} errorCallback `function (error) {}` */ - updateRelationship(relation, ids) { + updateRelationship(relation, ids, errorCallback) { + let related = this.get(relation); + let rollback; + if (related.kind === 'hasOne') { + rollback = related.get('id'); + } else if (related.kind === 'hasMany') { + rollback = related.mapBy('id'); + } this._updateRelationshipsData(relation, ids); - return this.get('service').patchRelationship(this, relation); + return this.get('service').patchRelationship(this, relation).catch(function (error) { + this._updateRelationshipsData(relation, rollback); + if (typeof callback === 'function') { + errorCallback(error); + } else { + Ember.Logger.error(error); + } + }.bind(this)); }, /** @@ -199,7 +219,7 @@ const Resource = Ember.Object.extend({ /** Adds related resource identifier object to the relationship data. - Also sets the `content` of the related (computed property's) proxy object. + Also sets or adds to the `content` of the related proxy object. - For has-many relations the related identifier object is added to the resource linkage data array. @@ -224,7 +244,10 @@ const Resource = Ember.Object.extend({ if (Array.isArray(data)) { data.push(identifier); if (resource) { - this.get(related).pushObject(resource); + let resources = this.get(related); + if (!resources.contains(resource)) { + resources.pushObject(resource); + } } } else { data = identifier; @@ -260,10 +283,11 @@ const Resource = Ember.Object.extend({ break; } } - let type = pluralize(related); - let owner = (typeof getOwner === 'function') ? getOwner(this) : this.container; - let resource = owner.lookup(`service:${type}`).cacheLookup(id); - this.get(related).removeObject(resource); + let resources = this.get(related); + let idx = resources.mapBy('id').indexOf(id); + if (idx > -1) { + resources.removeAt(idx); + } } else if (typeof relation === 'object') { relation.data = null; this.set(`${related}.content`, null); diff --git a/tests/unit/models/resource-test.js b/tests/unit/models/resource-test.js index <HASH>..<HASH> 100644 --- a/tests/unit/models/resource-test.js +++ b/tests/unit/models/resource-test.js @@ -296,7 +296,9 @@ test('#removeRelationships', function(assert) { }); test('#updateRelationship', function(assert) { - let serviceOp = this.sandbox.spy(); + let serviceOp = this.sandbox.spy(function() { + return Ember.RSVP.Promise.resolve(null); + }); let post = this.container.lookup('model:post').create({ id: '1', attributes: {title: 'Wyatt Earp', excerpt: 'Was a gambler.'}, relationships: {
Add rollback behavior for resource#updateRelationship - Catches promise failure for service#patchRelationship and resets relation id(s) - Refactor relationship assignment for adding/removing relations
pixelhandler_ember-jsonapi-resources
train
e233f7c10c9e34c77f75dd89a0fb2b13cb3852b0
diff --git a/src/main/java/javascalautils/concurrent/FutureImpl.java b/src/main/java/javascalautils/concurrent/FutureImpl.java index <HASH>..<HASH> 100644 --- a/src/main/java/javascalautils/concurrent/FutureImpl.java +++ b/src/main/java/javascalautils/concurrent/FutureImpl.java @@ -242,7 +242,7 @@ final class FutureImpl<T> implements Future<T> { // block for either the time to pass or the Future gets completed if (!latch.await(duration, timeUnit)) { - throw new TimeoutException("Timeout waiting for Future to complete"); + throw new TimeoutException("Timeout waiting ["+duration+"] ms for Future to complete"); } //The future is now complete, return ourselves
Changed logging when timeout in Future.ready
pnerg_java-scala-util
train
879911810f86aacf3a95ff25351d40cf2d47f3f4
diff --git a/tests/framework/db/CommandTest.php b/tests/framework/db/CommandTest.php index <HASH>..<HASH> 100644 --- a/tests/framework/db/CommandTest.php +++ b/tests/framework/db/CommandTest.php @@ -6,6 +6,7 @@ use yii\caching\FileCache; use yii\db\Connection; use yii\db\DataReader; use yii\db\Expression; +use yii\db\Schema; /** * @group db @@ -310,16 +311,48 @@ SQL; ], $record); } - /* - public function testUpdate() + public function testCreateTable() { + $db = $this->getConnection(); + $db->createCommand("DROP TABLE IF EXISTS testCreateTable;")->execute(); + + $db->createCommand()->createTable('testCreateTable', ['id' => Schema::TYPE_PK, 'bar' => Schema::TYPE_INTEGER])->execute(); + $db->createCommand()->insert('testCreateTable', ['bar' => 1])->execute(); + $records = $db->createCommand('SELECT [[id]], [[bar]] FROM {{testCreateTable}};')->queryAll(); + $this->assertEquals([ + ['id' => 1, 'bar' => 1], + ], $records); } - public function testDelete() + public function testAlterTable() { + if ($this->driverName === 'sqlite'){ + $this->markTestSkipped('Sqlite does not support alterTable'); + } + + $db = $this->getConnection(); + $db->createCommand("DROP TABLE IF EXISTS testAlterTable;")->execute(); + + $db->createCommand()->createTable('testAlterTable', ['id' => Schema::TYPE_PK, 'bar' => Schema::TYPE_INTEGER])->execute(); + $db->createCommand()->insert('testAlterTable', ['bar' => 1])->execute(); + + $db->createCommand()->alterColumn('testAlterTable', 'bar', Schema::TYPE_STRING)->execute(); + + $db->createCommand()->insert('testAlterTable', ['bar' => 'hello'])->execute(); + $records = $db->createCommand('SELECT [[id]], [[bar]] FROM {{testAlterTable}};')->queryAll(); + $this->assertEquals([ + ['id' => 1, 'bar' => 1], + ['id' => 2, 'bar' => 'hello'], + ], $records); } - public function testCreateTable() + + /* + public function testUpdate() + { + } + + public function testDelete() { } @@ -347,10 +380,6 @@ SQL; { } - public function testAlterColumn() - { - } - public function testAddForeignKey() { }
added test for createTable and alterTable test for issue #<I> close #<I>
yiisoft_yii2
train
b761bdcb2e8043333027ef23748d58d0d96247fe
diff --git a/Private/Polyfony/Security.php b/Private/Polyfony/Security.php index <HASH>..<HASH> 100755 --- a/Private/Polyfony/Security.php +++ b/Private/Polyfony/Security.php @@ -11,9 +11,10 @@ namespace Polyfony; use Polyfony\Store\Cookie as Cook; +use Polyfony\Store\Session as Session; class Security { - + // default is not granted protected static $_granted = false; protected static $_account = null; @@ -138,6 +139,8 @@ class Security { self::$_account = $account; // set the most basic authentication block as being true/passed self::$_granted = true; + // if we have an url in the session, redirect to it (and remove it) + !Session::has('previously_requested_url') ?: self::redirectToThePreviouslyRequestedUrl(); } } @@ -150,9 +153,18 @@ class Security { !$logout ?: Cook::remove(Config::get('security','cookie')); // we will redirect to the login page !$redirect ?: Response::setRedirect(Config::get('router','login_route'), 3); + // save the desired url for further redirection later on + Session::put('previously_requested_url', Request::getUrl()); // trhow a polyfony exception that by itself will stop the execution with maybe a nice exception handler Throw new Exception($message, $code); } + + protected static function redirectToThePreviouslyRequestedUrl() :void { + // define the redirection + Response::setRedirect(Session::get('previously_requested_url')); + // remove the temporary url + Session::remove('previously_requested_url'); + } // internal method for generating unique signatures public static function getSignature($mixed) :string { diff --git a/Private/Polyfony/Security/Accounts.php b/Private/Polyfony/Security/Accounts.php index <HASH>..<HASH> 100644 --- a/Private/Polyfony/Security/Accounts.php +++ b/Private/Polyfony/Security/Accounts.php @@ -149,6 +149,11 @@ class Accounts extends \Polyfony\Record { return in_array($module, $this->get('modules_array')); } + public function setPassword(string $plaintext_password) :self { + return $this->set([ + 'password'=>Sec::getPassword($plaintext_password) + ]); + } } diff --git a/composer.json b/composer.json index <HASH>..<HASH> 100755 --- a/composer.json +++ b/composer.json @@ -2,7 +2,7 @@ "name":"polyfony-inc/polyfony", "description":"Polyfony is a simple and powerfull PHP micro-framework", "keywords": ["lightweight", "fast", "php", "framework"], - "version":"2.3.19", + "version":"2.3.20", "license":"GPL-3.0-only", "type":"project", "authors":[
Security : two comfort features added Fixes #<I> (password hashing simplified) Fixes #<I> (automatic redirection after login)
polyfony-inc_polyfony
train
2ad898f8301403b11a64b72109cf22b489a87e78
diff --git a/lib/nodejs/scapi-webserver.js b/lib/nodejs/scapi-webserver.js index <HASH>..<HASH> 100644 --- a/lib/nodejs/scapi-webserver.js +++ b/lib/nodejs/scapi-webserver.js @@ -78,10 +78,10 @@ webserver.listen = function(host, port, schost, scport) { io.sockets.on('connection', function(socket) { socket.on('call', function (data) { scapi.call(data.path, data.args) - .then(function(result) { + .then(function(response) { socket.emit('reply', { 'request_id': data.request_id, - 'result': result + 'result': response.result }); }, function(err) { socket.emit('scapi_error', {
fix: send API result to websocket
crucialfelix_supercolliderjs
train
2f84178e6fd183539a85cb2d08c173595f011c7f
diff --git a/poetry/puzzle/provider.py b/poetry/puzzle/provider.py index <HASH>..<HASH> 100644 --- a/poetry/puzzle/provider.py +++ b/poetry/puzzle/provider.py @@ -353,14 +353,6 @@ class Provider: package = Package(package_name, package_version) - if dependency.name != package.name: - # For now, the dependency's name must match the actual package's name - raise RuntimeError( - "The dependency name for {} does not match the actual package's name: {}".format( - dependency.name, package.name - ) - ) - package.description = package_summary for req in reqs: @@ -378,6 +370,14 @@ class Provider: if python_requires: package.python_versions = python_requires + if dependency.name != package.name: + # For now, the dependency's name must match the actual package's name + raise RuntimeError( + "The dependency name for {} does not match the actual package's name: {}".format( + dependency.name, package.name + ) + ) + package.source_type = "directory" package.source_url = dependency.path.as_posix() diff --git a/tests/console/commands/test_add.py b/tests/console/commands/test_add.py index <HASH>..<HASH> 100644 --- a/tests/console/commands/test_add.py +++ b/tests/console/commands/test_add.py @@ -1,5 +1,6 @@ import sys +import pytest from cleo.testers import CommandTester from tests.helpers import get_dependency @@ -173,6 +174,27 @@ Package operations: 2 installs, 0 updates, 0 removals assert len(installer.installs) == 2 +def test_add_git_constraint_with_poetry_bad_name(app, repo, installer): + command = app.find("add") + tester = CommandTester(command) + + repo.add_package(get_package("pendulum", "1.4.4")) + + with pytest.raises(RuntimeError) as e: + tester.execute( + [ + ("command", command.get_name()), + ("name", ["demox"]), + ("--git", "https://github.com/demo/pyproject-demo.git"), + ] + ) + expected = ( + "The dependency name for demox does not match the actual package's name: demo" + ) + assert str(e.value) == expected + assert len(installer.installs) == 0 + + def test_add_file_constraint_wheel(app, repo, installer): command = app.find("add") tester = CommandTester(command) diff --git a/tests/puzzle/test_provider.py b/tests/puzzle/test_provider.py index <HASH>..<HASH> 100644 --- a/tests/puzzle/test_provider.py +++ b/tests/puzzle/test_provider.py @@ -251,7 +251,8 @@ def test_search_for_directory_setup_read_setup_with_no_dependencies(provider, mo def test_search_for_directory_poetry(provider): dependency = DirectoryDependency( - "demo", Path(__file__).parent.parent / "fixtures" / "project_with_extras" + "project-with-extras", + Path(__file__).parent.parent / "fixtures" / "project_with_extras", ) package = provider.search_for_directory(dependency)[0] @@ -267,7 +268,8 @@ def test_search_for_directory_poetry(provider): def test_search_for_directory_poetry_with_extras(provider): dependency = DirectoryDependency( - "demo", Path(__file__).parent.parent / "fixtures" / "project_with_extras" + "project-with-extras", + Path(__file__).parent.parent / "fixtures" / "project_with_extras", ) dependency.extras.append("extras_a")
Enforce package name for poetry projects from directory source (#<I>)
sdispater_poetry
train
607eb922c389849c34578bfeccc5b28a0c904f56
diff --git a/lib/runner.js b/lib/runner.js index <HASH>..<HASH> 100644 --- a/lib/runner.js +++ b/lib/runner.js @@ -246,7 +246,6 @@ Runner.prototype.hook = function(name, fn){ function next(i) { var hook = hooks[i]; if (!hook) return fn(); - if (self.failures && suite.bail()) return fn(); self.currentRunnable = hook; hook.ctx.currentTest = self.test; diff --git a/test/runner.js b/test/runner.js index <HASH>..<HASH> 100644 --- a/test/runner.js +++ b/test/runner.js @@ -181,6 +181,20 @@ describe('Runner', function(){ }) }) + describe('.hook(name, fn)', function(){ + it('should execute hooks after failed test if suite bail is true', function(done){ + runner.fail({}); + suite.bail(true); + suite.afterEach(function(){ + suite.afterAll(function() { + done(); + }) + }); + runner.hook('afterEach', function(){}); + runner.hook('afterAll', function(){}); + }) + }) + describe('.fail(test, err)', function(){ it('should increment .failures', function(){ runner.failures.should.equal(0);
after hooks now being called on failed tests when using bail, fixes #<I>
mochajs_mocha
train
01c36ffed268624a512939ceb5d8cd12f3c1d2e8
diff --git a/lib/fluent/plugin/in_tail.rb b/lib/fluent/plugin/in_tail.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/plugin/in_tail.rb +++ b/lib/fluent/plugin/in_tail.rb @@ -261,8 +261,8 @@ class TailInput < Input @io = io @pe = pe @receive_lines = receive_lines - @buffer = '' - @iobuf = '' + @buffer = ''.force_encoding('ASCII-8BIT') + @iobuf = ''.force_encoding('ASCII-8BIT') end attr_reader :io
in_tail: set ASCII-8BIT encoding for io buffers
fluent_fluentd
train
73e8954239647aae59bbfc33cfc5729e539d9997
diff --git a/src/main/java/org/jboss/netty/channel/local/LocalAddress.java b/src/main/java/org/jboss/netty/channel/local/LocalAddress.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/jboss/netty/channel/local/LocalAddress.java +++ b/src/main/java/org/jboss/netty/channel/local/LocalAddress.java @@ -101,4 +101,9 @@ public final class LocalAddress extends SocketAddress implements Comparable<Loca public String toString() { return getId(); } + + // Just in case someone serializes this class .. + private Object readResolve() { + return getInstance(getId()); + } }
Proper Java serialization support for LocalAddress
netty_netty
train
e019441cf05bfe96ea706b22a0de280fa9742957
diff --git a/PPI/Templating/Smarty/Extension/AssetsExtension.php b/PPI/Templating/Smarty/Extension/AssetsExtension.php index <HASH>..<HASH> 100644 --- a/PPI/Templating/Smarty/Extension/AssetsExtension.php +++ b/PPI/Templating/Smarty/Extension/AssetsExtension.php @@ -29,6 +29,16 @@ class AssetsExtension extends BaseAssetsExtension protected $assetsHelper = null; /** + * A key/value pair of functions to remap to help comply with PSR standards + * + * @var array + */ + protected $funRemap = array( + 'getAssetUrl_block' => 'getAssetUrlBlock', + 'getAssetUrl_modifier' => 'getAssetUrlModifier', + ); + + /** * Constructor. * * @param AssetsHelper $assetsHelper @@ -41,6 +51,21 @@ class AssetsExtension extends BaseAssetsExtension } /** + * The magic call method triggers before throwing an exception + * + * @param string $method The method you are looking for + * @param array $params The params you wish to pass to your method + * + * @return mixed + */ + public function __call($method, array $params = array()) { + if(isset($this->funRemap[$method])) { + return call_user_func_array(array($this, $this->funRemap[$method]), $params); + } + throw new \BadMethodCallException('Method ' . $method . ' does not exist'); + } + + /** * Returns the public path of an asset. * * Absolute paths (i.e. http://...) are returned unmodified.
Use PHP magic to fix smarty method calls
ppi_framework
train
bb21abf651a4c8375ef15f730991f742761540d9
diff --git a/debug.js b/debug.js index <HASH>..<HASH> 100644 --- a/debug.js +++ b/debug.js @@ -132,4 +132,6 @@ function coerce(val) { // persist -if (window.localStorage) debug.enable(localStorage.debug); +try { + if (window.localStorage) debug.enable(localStorage.debug); +} catch(e){}
Catch localStorage security error when cookies are blocked (Chrome) If cookies are disabled on Chrome, `window.localStorage` throws an error `Uncaught Error: SecurityError: DOM Exception <I>`
visionmedia_debug
train
c4244291b4ba55f765418386cdac566e9a59633a
diff --git a/distutils/archive_util.py b/distutils/archive_util.py index <HASH>..<HASH> 100644 --- a/distutils/archive_util.py +++ b/distutils/archive_util.py @@ -121,7 +121,7 @@ def make_tarball( # compression using `compress` if compress == 'compress': - warn("'compress' will be deprecated.", PendingDeprecationWarning) + warn("'compress' is deprecated.", DeprecationWarning) # the option varies depending on the platform compressed_name = archive_name + compress_ext[compress] if sys.platform == 'win32': diff --git a/distutils/command/register.py b/distutils/command/register.py index <HASH>..<HASH> 100644 --- a/distutils/command/register.py +++ b/distutils/command/register.py @@ -66,9 +66,9 @@ class register(PyPIRCCommand): def check_metadata(self): """Deprecated API.""" warn( - "distutils.command.register.check_metadata is deprecated, \ - use the check command instead", - PendingDeprecationWarning, + "distutils.command.register.check_metadata is deprecated; " + "use the check command instead", + DeprecationWarning, ) check = self.distribution.get_command_obj('check') check.ensure_finalized() diff --git a/distutils/tests/test_archive_util.py b/distutils/tests/test_archive_util.py index <HASH>..<HASH> 100644 --- a/distutils/tests/test_archive_util.py +++ b/distutils/tests/test_archive_util.py @@ -195,7 +195,7 @@ class ArchiveUtilTestCase(support.TempdirManager, support.LoggingSilencer): tmpdir = self._create_files() base_name = os.path.join(self.mkdtemp(), 'archive') - # using compress and testing the PendingDeprecationWarning + # using compress and testing the DeprecationWarning old_dir = os.getcwd() os.chdir(tmpdir) try:
Convert PendingDeprecationWarnings to DeprecationWarnings.
pypa_setuptools
train
4fbe3a42178cbd88678d8c6d0ff73e7a38641b3f
diff --git a/test/test_cuda_functions.py b/test/test_cuda_functions.py index <HASH>..<HASH> 100644 --- a/test/test_cuda_functions.py +++ b/test/test_cuda_functions.py @@ -84,4 +84,4 @@ def test_benchmark_times(): dev = cuda.CudaFunctions(0) args = [1, 2] time = dev.benchmark(test_func, args, (1,2), (1,2), True) - assert time.length == 7 + assert len(time) == 7 diff --git a/test/test_opencl_functions.py b/test/test_opencl_functions.py index <HASH>..<HASH> 100644 --- a/test/test_opencl_functions.py +++ b/test/test_opencl_functions.py @@ -66,7 +66,7 @@ def test_benchmark_times(): return type('Event', (object,), {'wait': lambda self: 0, 'profile': profile()})() time = dev.benchmark(test_func, args, (1,2,3), (1,2,3), True) - assert time.length == 7 + assert len(time) == 7 def test_run_kernel(): skip_if_no_opencl()
Forgot you don't have length in Python.
benvanwerkhoven_kernel_tuner
train
ee816200b622191d5353f6a96d01b265b4c7d50f
diff --git a/src/tex.js b/src/tex.js index <HASH>..<HASH> 100644 --- a/src/tex.js +++ b/src/tex.js @@ -1,3 +1,5 @@ +var raw = String.raw; + function style(href) { return new Promise(function(resolve, reject) { var link = document.createElement("link"); @@ -18,11 +20,9 @@ export default function(require, resource) { var katex = values[0], tex = renderer(); function renderer(options) { - return function(strings) { - var string = strings[0] + "", i = 0, n = arguments.length; - while (++i < n) string += arguments[i] + "" + strings[i]; + return function() { var root = document.createElement("div"); - katex.render(string, root, options); + katex.render(raw.apply(String, arguments), root, options); return root.removeChild(root.firstChild); }; }
Use String.raw for tex.
observablehq_stdlib
train
8fbb4c9c3f20c9120679830dfdc931f7191551f3
diff --git a/system/Config/BaseConfig.php b/system/Config/BaseConfig.php index <HASH>..<HASH> 100644 --- a/system/Config/BaseConfig.php +++ b/system/Config/BaseConfig.php @@ -59,12 +59,14 @@ class BaseConfig /** * Will attempt to get environment variables with names * that match the properties of the child class. + * + * The "shortPrefix" is the lowercase-only config class name. */ public function __construct() { $properties = array_keys(get_object_vars($this)); $prefix = get_class($this); - $shortPrefix = strtolower(substr($prefix, strrpos($prefix, '\\') + 1)); + $shortPrefix = strtolower(substr($prefix, strrpos($prefix, '\\') )); foreach ($properties as $property) { diff --git a/system/Config/DotEnv.php b/system/Config/DotEnv.php index <HASH>..<HASH> 100644 --- a/system/Config/DotEnv.php +++ b/system/Config/DotEnv.php @@ -106,6 +106,7 @@ class DotEnv $this->setVariable($line); } } + } //-------------------------------------------------------------------- diff --git a/tests/system/Config/BaseConfigTest.php b/tests/system/Config/BaseConfigTest.php index <HASH>..<HASH> 100644 --- a/tests/system/Config/BaseConfigTest.php +++ b/tests/system/Config/BaseConfigTest.php @@ -36,6 +36,24 @@ class BaseConfigTest extends CIUnitTestCase //-------------------------------------------------------------------- + public function testEnvironmentOverrides() + { + $dotenv = new DotEnv($this->fixturesFolder, '.env', 'z'); + $dotenv->load(); + + $config = new \SimpleConfig(); + + $this->assertEquals('pow', $config->alpha); + $this->assertEquals('kazaam', $config->bravo); + $this->assertEquals('', $config->charlie); + $this->assertEquals('hubbahubba', $config->delta); + $this->assertEquals(false, $config->echo); + $this->assertEquals(true, $config->foxtrot); + $this->assertEquals(18, $config->golf); + } + + //-------------------------------------------------------------------- + public function testPrefixedValues() { $dotenv = new DotEnv($this->fixturesFolder, '.env'); @@ -68,6 +86,8 @@ class BaseConfigTest extends CIUnitTestCase $config = new \SimpleConfig(); $this->assertEquals('simpleton', $config->simple['name']); + $this->assertEquals('foo', $config->first); + $this->assertEquals('bar', $config->second); } //-------------------------------------------------------------------- diff --git a/tests/system/Config/fixtures/.env b/tests/system/Config/fixtures/.env index <HASH>..<HASH> 100644 --- a/tests/system/Config/fixtures/.env +++ b/tests/system/Config/fixtures/.env @@ -6,4 +6,11 @@ NULL= SimpleConfig.onedeep=baz SimpleConfig.default.name=ci4 -simple.name=simpleton \ No newline at end of file +simple.name=simpleton + +# for environment override testing +SimpleConfig.alpha=pow +SimpleConfig.bravo=kazaam +SimpleConfig.charlie= +simpleconfig.delta=hubbahubba +simpleconfig.foxtrot="true" \ No newline at end of file diff --git a/tests/system/Config/fixtures/SimpleConfig.php b/tests/system/Config/fixtures/SimpleConfig.php index <HASH>..<HASH> 100644 --- a/tests/system/Config/fixtures/SimpleConfig.php +++ b/tests/system/Config/fixtures/SimpleConfig.php @@ -2,22 +2,28 @@ class SimpleConfig extends \CodeIgniter\Config\BaseConfig { + public $QZERO; public $QZEROSTR; public $QEMPTYSTR; public $QFALSE; - public $first = 'foo'; public $second = 'bar'; - public $FOO; public $onedeep; - public $default = [ 'name' => null ]; - public $simple = [ 'name' => null ]; + // properties for environment over-ride testing + public $alpha = 'one'; + public $bravo = 'two'; + public $charlie = 'three'; + public $delta = 'four'; + public $echo = ''; + public $foxtrot = 'false'; + public $golf = 18; + }
Fixed & tested BaseConfig's handling of shortPrefix
codeigniter4_CodeIgniter4
train
b9c948ec1df79e3a29d925f94ccbf4336d6a489f
diff --git a/lxd/network_acls.go b/lxd/network_acls.go index <HASH>..<HASH> 100644 --- a/lxd/network_acls.go +++ b/lxd/network_acls.go @@ -7,7 +7,7 @@ import ( "github.com/gorilla/mux" - "github.com/lxc/lxd/lxd/cluster/request" + clusterRequest "github.com/lxc/lxd/lxd/cluster/request" "github.com/lxc/lxd/lxd/network/acl" "github.com/lxc/lxd/lxd/project" "github.com/lxc/lxd/lxd/response" @@ -435,7 +435,7 @@ func networkACLPut(d *Daemon, r *http.Request) response.Response { } } - clientType := request.UserAgentClientType(r.Header.Get("User-Agent")) + clientType := clusterRequest.UserAgentClientType(r.Header.Get("User-Agent")) err = netACL.Update(&req, clientType) if err != nil {
lxd/network/acls: use clusterRequest alias for lxd/cluster/request package
lxc_lxd
train
e9cf489b542edf105131721365965a87df7e10d6
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index <HASH>..<HASH> 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -43,7 +43,7 @@ repos: hooks: - id: doc8 - repo: https://github.com/adrienverge/yamllint.git - rev: v1.26.0 + rev: v1.26.1 hooks: - id: yamllint exclude: > @@ -54,7 +54,7 @@ repos: types: [file, yaml] entry: yamllint --strict - repo: https://github.com/pre-commit/mirrors-isort - rev: v5.7.0 + rev: v5.8.0 hooks: - id: isort args: @@ -65,8 +65,8 @@ repos: hooks: - id: black language_version: python3 -- repo: https://gitlab.com/pycqa/flake8.git - rev: 3.8.4 +- repo: https://github.com/pycqa/flake8.git + rev: 3.9.0 hooks: - id: flake8 language_version: python3 diff --git a/docs/conf.py b/docs/conf.py index <HASH>..<HASH> 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -84,7 +84,20 @@ master_doc = 'index' # General substitutions. project = 'Ansible Lint Documentation' -copyright = "2013-2020 Ansible, Inc" # pylint: disable=redefined-builtin +copyright = "2013-2021 Ansible, Inc" # pylint: disable=redefined-builtin + +github_url = "https://github.com" +github_repo_org = "ansible" +github_repo_name = "ansible-lint" +github_repo_slug = f"{github_repo_org}/{github_repo_name}" +github_repo_url = f"{github_url}/{github_repo_slug}" + +extlinks = { + "issue": (f"{github_repo_url}/issues/%s", "#"), + "pr": (f"{github_repo_url}/pull/%s", "PR #"), + "commit": (f"{github_repo_url}/commit/%s", ""), + "gh": (f"{github_url}/%s", "GitHub: "), +} # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. @@ -154,6 +167,29 @@ rst_epilog = """ html_theme_path = ['../_themes'] html_theme = 'sphinx_ansible_theme' + +html_theme_options = { + "collapse_navigation": False, + "analytics_id": "UA-128382387-1", + "style_nav_header_background": "#5bbdbf", + "style_external_links": True, + # 'canonical_url': "https://docs.ansible.com/ansible/latest/", + 'vcs_pageview_mode': 'edit', + "navigation_depth": 3, +} + +html_context = { + 'display_github': 'True', + 'github_user': 'ansible-community', + 'github_repo': 'ansible-lint', + 'github_version': 'master/docs/', + 'current_version': version, + 'latest_version': 'latest', + # list specifically out of order to make latest work + 'available_versions': ('latest', 'stable'), + 'css_files': (), # overrides to the standard theme +} + html_short_title = 'Ansible Lint Documentation' # The style sheet to use for HTML and HTML Help pages. A file of that name diff --git a/src/ansiblelint/utils.py b/src/ansiblelint/utils.py index <HASH>..<HASH> 100644 --- a/src/ansiblelint/utils.py +++ b/src/ansiblelint/utils.py @@ -689,9 +689,9 @@ def parse_yaml_linenumbers(lintable: Lintable) -> AnsibleBaseYAMLObject: # the line number where the previous token has ended (plus empty lines) line = loader.line node = Composer.compose_node(loader, parent, index) # type: ignore - node.__line__ = line + 1 if not isinstance(node, yaml.nodes.Node): raise RuntimeError("Unexpected yaml data.") + setattr(node, '__line__', line + 1) return node def construct_mapping(
Fixed docs edit links (#<I>) Fixed: #<I>
ansible_ansible-lint
train
9a8541d2e9d666877ee9133b91a04ed898b12f5d
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ * EntityMetaInfo and scanner - support JPA plugin * Update to act-asm-5.0.3 for precise line number in error reporting * Improve built-in service performance by make them as nonblock when possible +* `NullPointerException` after app reloaded from an ASM error in dev mode #509 * Error page not displayed if asm error raised during scanning phase #508 * `@SessionVariable` binding failure #506 * `@DefaultValue` not working for primitive types #504 diff --git a/src/main/java/act/app/ActionContext.java b/src/main/java/act/app/ActionContext.java index <HASH>..<HASH> 100644 --- a/src/main/java/act/app/ActionContext.java +++ b/src/main/java/act/app/ActionContext.java @@ -988,7 +988,7 @@ public class ActionContext extends ActContext.Base<ActionContext> implements Des app().eventBus().emit(new SessionWillDissolveEvent(this)); try { setCsrfCookieAndRenderArgs(); - sessionManager.dissolveState(session(), flash(), resp()); + sessionManager().dissolveState(session(), flash(), resp()); // dissolveFlash(); // dissolveSession(); state = State.SESSION_DISSOLVED; @@ -1141,14 +1141,20 @@ public class ActionContext extends ActContext.Base<ActionContext> implements Des private void resolveSession(H.Request req) { preCheckCsrf(); - //this.session = Act.sessionManager().resolveSession(this); - session = sessionManager.resolveSession(req); + session = sessionManager().resolveSession(req); checkCsrf(session); } private void resolveFlash(H.Request req) { //this.flash = Act.sessionManager().resolveFlash(this); - flash = sessionManager.resolveFlash(req); + flash = sessionManager().resolveFlash(req); + } + + private SessionManager sessionManager() { + if (null == sessionManager) { + sessionManager = app().sessionManager(); + } + return sessionManager; } // private void dissolveSession() { diff --git a/src/main/java/act/xio/NetworkHandler.java b/src/main/java/act/xio/NetworkHandler.java index <HASH>..<HASH> 100644 --- a/src/main/java/act/xio/NetworkHandler.java +++ b/src/main/java/act/xio/NetworkHandler.java @@ -106,7 +106,7 @@ public class NetworkHandler extends DestroyableBase { if (Act.isDev()) { try { boolean updated = app.checkUpdates(false); - if (updated) { + if (updated && !app.hasBlockIssue()) { app.jobManager().on(SysEventId.POST_START, new Runnable() { @Override public void run() {
#<I> `NullPointerException` after app reloaded from an ASM error in dev mode
actframework_actframework
train
75d7c26e57375220bdcaa42d533f86bd1150efc5
diff --git a/wallet/setup.go b/wallet/setup.go index <HASH>..<HASH> 100644 --- a/wallet/setup.go +++ b/wallet/setup.go @@ -35,6 +35,7 @@ import ( "github.com/btcsuite/btcwallet/waddrmgr" "github.com/btcsuite/btcwallet/wallet" "github.com/btcsuite/btcwallet/walletdb" + _ "github.com/btcsuite/btcwallet/walletdb/bdb" ) var (
import walletdb/bdb for side effects (registers driver)
lightningnetwork_lnd
train
179a6d9741341e99ed148f91ddb41d4a91018820
diff --git a/webkit_server.py b/webkit_server.py index <HASH>..<HASH> 100644 --- a/webkit_server.py +++ b/webkit_server.py @@ -432,7 +432,7 @@ class Server(object): def kill(self): """ Kill the process. """ self._server.kill() - self._server.wait() + self._server.communicate() def connect(self): """ Returns a new socket connection to this server. """
Use communicate() to ensure standard file descriptors are closed This internally calls wait() but also ensures that any file descriptors for stdin, stdout, and stderr are closed. If we don't do this we'll leak file descriptors. For long running processes that start & stop a WebKit server many times this can result in an eventual crash due to hitting the max open files limit on the underlying system.
niklasb_webkit-server
train
58018006c0d92ba3c57df691d0e2cd1cce43e5f2
diff --git a/syn/types/a/base.py b/syn/types/a/base.py index <HASH>..<HASH> 100644 --- a/syn/types/a/base.py +++ b/syn/types/a/base.py @@ -182,6 +182,9 @@ class Type(object): raise NotImplementedError def find_ne(self, other, **kwargs): + if self == other: + return + from .ne import Value if type(self.obj) is not type(other): return Value("different types ({} =/= {})". diff --git a/syn/types/a/mapping.py b/syn/types/a/mapping.py index <HASH>..<HASH> 100644 --- a/syn/types/a/mapping.py +++ b/syn/types/a/mapping.py @@ -1,7 +1,19 @@ import collections from syn.base_utils import rand_dict, get_fullname, tuple_prepend -from .base import Type, serialize, hashable +from .base import Type, serialize, hashable, rstr, estr from .numeric import Int +from .sequence import list_enumval +from .set import set_enumval +from .ne import Value + +#------------------------------------------------------------------------------- +# Utilities + +def dict_enumval(x, **kwargs): + keys = list(set_enumval(x, **kwargs)) + values = list_enumval(x, **kwargs) + N = min(len(keys), len(values)) + return dict(zip(keys[:N], values[:N])) #------------------------------------------------------------------------------- # Mapping @@ -10,16 +22,75 @@ from .numeric import Int class Mapping(Type): type = collections.Mapping + def __init__(self, *args, **kwargs): + super(Set, self).__init__(*args, **kwargs) + self.visit_buffer = [] + self.visit_iter = iter(self.obj) + + @classmethod + def _enumeration_value(cls, x, **kwargs): + return dict_enumval(x, **kwargs) + + def estr(self, **kwargs): + parts = ["{}: {}".format(estr(key, **kwargs), estr(value, **kwargs)) + for key, value in self.obj.items()] + ret = '{' + ', '.join(parts) + '}' + ret = '{}({})'.format(get_typename(self.obj), ret) + return escape_for_eval(ret) + + def _find_ne(self, other, **kwargs): + # TODO: return FindNE object here + keys = set(self.obj.keys()) + okeys = set(other.keys()) + + if keys != okeys: + diffs = keys.difference(okeys).union(okeys.difference(keys)) + return Value('key differences: {}'.format(rstr(diffs))) + + for key, value in self.obj.items(): + oval = other[key] + if key != value: + return Value('key {}: {} != {}'.format(key, value, oval)) + def _hashable(self, **kwargs): tup = tuple((hashable(key, **kwargs), hashable(value, **kwargs)) for key, value in self.obj.items()) return tuple_prepend(get_fullname(self.obj), tup) + def _rstr(self, **kwargs): + # TODO: add pretty option + parts = ["{}: {}".format(rstr(key, **kwargs), rstr(value, **kwargs)) + for key, value in self.obj.items()] + ret = '{' + ', '.join(parts) + '}' + return ret + def _serialize(self, dct, **kwargs): for key, value in self.obj.items(): dct[key] = serialize(value) + def _visit(self, k, **kwargs): + # Don't use the buffer if you are modifying the mapping in between + # _visit calls + use_buffer = kwargs.get('use_buffer', True) + if use_buffer: + N = len(self.visit_buffer) + if 0 <= k < N: + key = self.visit_buffer[k] + else: + idx_diff = k - (N - 1) + for item in islice(self.visit_iter, idx_diff): + self.visit_buffer.append(item) + key = self.visit_buffer[k] + else: + keys = list(self.obj) + key = keys[k] + + yield key, self.obj[key] + + def _visit_len(self, **kwargs): + return len(self.obj) + #------------------------------------------------------------------------------- # Mappings
Adding (untestEd) dict operations; some tweaks
mbodenhamer_syn
train
4b9b159d4a10b2aba342f64dab1309da23d4089a
diff --git a/lib/ice_cube/rule.rb b/lib/ice_cube/rule.rb index <HASH>..<HASH> 100644 --- a/lib/ice_cube/rule.rb +++ b/lib/ice_cube/rule.rb @@ -26,8 +26,8 @@ module IceCube rule end - def to_yaml - to_hash.to_yaml + def to_yaml(options = {}) + to_hash.to_yaml(options) end def self.from_yaml(str) diff --git a/lib/ice_cube/schedule.rb b/lib/ice_cube/schedule.rb index <HASH>..<HASH> 100644 --- a/lib/ice_cube/schedule.rb +++ b/lib/ice_cube/schedule.rb @@ -33,13 +33,13 @@ module IceCube end # Convert the schedule to yaml, reverse of Schedule.from_yaml - def to_yaml + def to_yaml(options = {}) hash = to_hash hash[:start_date] = TimeUtil.serializable_time(hash[:start_date]) hash[:rdates] = hash[:rdates].map { |t| TimeUtil.serializable_time(t) } hash[:exdates] = hash[:exdates].map { |t| TimeUtil.serializable_time(t) } hash[:end_time] = TimeUtil.serializable_time(hash[:end_time]) - hash.to_yaml + hash.to_yaml(options) end # Create a schedule from a hash created by instance.to_hash diff --git a/spec/examples/to_yaml_spec.rb b/spec/examples/to_yaml_spec.rb index <HASH>..<HASH> 100644 --- a/spec/examples/to_yaml_spec.rb +++ b/spec/examples/to_yaml_spec.rb @@ -185,4 +185,12 @@ describe IceCube::Schedule, 'to_yaml' do IceCube::Schedule.from_yaml(schedule.to_yaml).duration.should == 3600 end + it 'should be able to be serialized to yaml as part of a hash' do + schedule = IceCube::Schedule.new Time.now + hash = { :schedule => schedule } + lambda do + hash.to_yaml + end.should_not raise_error + end + end
Fixed a to_yaml bug - thanks casetaintor [#7 state:resolved]
seejohnrun_ice_cube
train
507bfd1e0c48afaf4eab3e4ba1b52e9c94069bca
diff --git a/sprinter/lib.py b/sprinter/lib.py index <HASH>..<HASH> 100644 --- a/sprinter/lib.py +++ b/sprinter/lib.py @@ -60,10 +60,14 @@ def get_formula_class(formula, environment): def call(command, stdin=None, env=os.environ, cwd=None, shell=False, output_log_level=logging.INFO, logger=LOGGER): """ Better, smarter call logic """ args = command if shell else whitespace_smart_split(command) + kw = {} if not shell and not which(args[0]): raise CommandMissingException(args[0]) + if shell: + kw['shell'] = True + kw['executable'] = '/bin/bash' process = subprocess.Popen(args, stdin=PIPE, stdout=PIPE, stderr=STDOUT, - env=env, cwd=cwd, shell=shell) + env=env, cwd=cwd, **kw) output = process.communicate(input=stdin)[0] logger.log(output_log_level, output) return (process.returncode, output)
Reverting back to /bin/bash for now
toumorokoshi_sprinter
train
b1b7730402bd9269a57879175ba5f3cbf9d4a04a
diff --git a/statistics/fmsketch.go b/statistics/fmsketch.go index <HASH>..<HASH> 100644 --- a/statistics/fmsketch.go +++ b/statistics/fmsketch.go @@ -170,6 +170,7 @@ func DecodeFMSketch(data []byte) (*FMSketch, error) { return nil, errors.Trace(err) } fm := FMSketchFromProto(p) + fm.maxSize = 10000 // TODO: add this attribute to PB and persist it instead of using a fixed number(executor.maxSketchSize) return fm, nil } diff --git a/statistics/handle/handle.go b/statistics/handle/handle.go index <HASH>..<HASH> 100644 --- a/statistics/handle/handle.go +++ b/statistics/handle/handle.go @@ -821,7 +821,15 @@ func (h *Handle) TableStatsFromStorage(tableInfo *model.TableInfo, physicalID in table = table.Copy() } table.Pseudo = false - rows, _, err := reader.read("select table_id, is_index, hist_id, distinct_count, version, null_count, tot_col_size, stats_ver, flag, correlation, last_analyze_pos from mysql.stats_histograms where table_id = %?", physicalID) + + rows, _, err := reader.read("select modify_count, count from mysql.stats_meta where table_id = %?", physicalID) + if err != nil || len(rows) == 0 { + return nil, err + } + table.ModifyCount = rows[0].GetInt64(0) + table.Count = rows[0].GetInt64(1) + + rows, _, err = reader.read("select table_id, is_index, hist_id, distinct_count, version, null_count, tot_col_size, stats_ver, flag, correlation, last_analyze_pos from mysql.stats_histograms where table_id = %?", physicalID) // Check deleted table. if err != nil || len(rows) == 0 { return nil, nil diff --git a/statistics/handle/handle_test.go b/statistics/handle/handle_test.go index <HASH>..<HASH> 100644 --- a/statistics/handle/handle_test.go +++ b/statistics/handle/handle_test.go @@ -762,6 +762,42 @@ func (s *testStatsSuite) TestBuildGlobalLevelStats(c *C) { c.Assert(len(result.Rows()), Equals, 20) } +func (s *testStatsSuite) TestGlobalStatsData(c *C) { + defer cleanEnv(c, s.store, s.do) + tk := testkit.NewTestKit(c, s.store) + tk.MustExec("use test") + tk.MustExec("drop table if exists t") + tk.MustExec(` +create table t ( + a int, + key(a) +) +partition by range (a) ( + partition p0 values less than (10), + partition p1 values less than (20) +)`) + tk.MustExec("set @@tidb_partition_prune_mode='dynamic-only'") + tk.MustExec("insert into t values (1), (5), (null), (11), (15)") + c.Assert(s.do.StatsHandle().DumpStatsDeltaToKV(handle.DumpAll), IsNil) + tk.MustExec("analyze table t") + + tk.MustQuery("select modify_count, count from mysql.stats_meta order by table_id asc").Check( + testkit.Rows("0 5", "0 3", "0 2")) // global row-count = sum(partition row-count) + + // distinct, null_count, tot_col_size should be the sum of their values in partition-stats, and correlation should be 0 + tk.MustQuery("select distinct_count, null_count, tot_col_size, correlation from mysql.stats_histograms where is_index=0 order by table_id asc").Check( + testkit.Rows("4 1 4 0", "2 1 2 1", "2 0 2 1")) + + tk.MustQuery("show stats_buckets where is_index=0").Check( + testkit.Rows("test t global a 0 0 2 1 1 5 0", "test t global a 0 1 4 1 5 15 0", + "test t p0 a 0 0 1 1 1 1 0", "test t p0 a 0 1 2 1 5 5 0", + "test t p1 a 0 0 1 1 11 11 0", "test t p1 a 0 1 2 1 15 15 0")) + tk.MustQuery("show stats_buckets where is_index=1").Check( + testkit.Rows("test t global a 1 0 2 1 1 5 0", "test t global a 1 1 4 1 5 15 0", + "test t p0 a 1 0 1 1 1 1 0", "test t p0 a 1 1 2 1 5 5 0", + "test t p1 a 1 0 1 1 11 11 0", "test t p1 a 1 1 2 1 15 15 0")) +} + func (s *testStatsSuite) TestExtendedStatsDefaultSwitch(c *C) { defer cleanEnv(c, s.store, s.do) tk := testkit.NewTestKit(c, s.store)
statistics: add more tests to check accurateness of global-stats (#<I>)
pingcap_tidb
train
41c8ee7a3583f82267ca3d81e597ed968fc6e5f4
diff --git a/app/concerns/web_request_concern.rb b/app/concerns/web_request_concern.rb index <HASH>..<HASH> 100644 --- a/app/concerns/web_request_concern.rb +++ b/app/concerns/web_request_concern.rb @@ -9,6 +9,10 @@ module WebRequestConcern errors.add(:base, "user_agent must be a string") unless options['user_agent'].is_a?(String) end + if options['disable_ssl_verification'].present? and not [true, false].include? options['disable_ssl_verification'] + errors.add(:base, "if provided, disable_ssl_verification must be a boolean") + end + unless headers(options['headers']).is_a?(Hash) errors.add(:base, "if provided, headers must be a hash") end @@ -21,7 +25,13 @@ module WebRequestConcern end def faraday - @faraday ||= Faraday.new { |builder| + faraday_options = { + ssl: { + verify: !options['disable_ssl_verification'] + } + } + + @faraday ||= Faraday.new(faraday_options) { |builder| builder.headers = headers if headers.length > 0 builder.headers[:user_agent] = user_agent diff --git a/spec/concerns/web_request_concern_spec.rb b/spec/concerns/web_request_concern_spec.rb index <HASH>..<HASH> 100644 --- a/spec/concerns/web_request_concern_spec.rb +++ b/spec/concerns/web_request_concern_spec.rb @@ -19,6 +19,18 @@ describe WebRequestConcern do faraday = web_request.faraday expect(faraday.builder.handlers).to include(FaradayMiddleware::FollowRedirects) end + + it 'should enable SSL verification by default' do + web_request = WebRequestConcernTest.new() + faraday = web_request.faraday + expect(faraday.ssl.verify).to eq(true) + end + + it 'should disable SSL verification if disable_ssl_verification option is true' do + web_request = WebRequestConcernTest.new(options: { disable_ssl_verification: true }) + faraday = web_request.faraday + expect(faraday.ssl.verify).to eq(false) + end end describe '#validate_web_request_options!' do @@ -71,5 +83,19 @@ describe WebRequestConcern do expect(web_request.errors[:base]).to_not be_empty end end + + describe 'disable_ssl_verification' do + it 'should be a boolean' do + web_request = WebRequestConcernTest.new(options: { disable_ssl_verification: true } ) + web_request.validate_web_request_options! + expect(web_request.errors[:base]).to be_empty + end + + it 'should be invalid if not a boolean' do + web_request = WebRequestConcernTest.new(options: { disable_ssl_verification: 42 } ) + web_request.validate_web_request_options! + expect(web_request.errors[:base]).to_not be_empty + end + end end end
[#<I>] Add disable_ssl_verification option to WebRequestConcern This allows the user to disable Faraday's verification of the site's SSL certificate.
huginn_huginn
train
ff5e28319d9f663d3fbf3084b5a58c32db208dd1
diff --git a/modules_v3/stories/module.php b/modules_v3/stories/module.php index <HASH>..<HASH> 100644 --- a/modules_v3/stories/module.php +++ b/modules_v3/stories/module.php @@ -307,6 +307,7 @@ class stories_WT_Module extends WT_Module implements WT_Module_Block, WT_Module_ ->addInlineJavascript(' jQuery("#story_table").dataTable({ "sDom": \'<"H"pf<"dt-clear">irl>t<"F"pl>\', + '.WT_I18N::datatablesI18N().', "bAutoWidth":false, "bPaginate": true, "sPaginationType": "full_numbers", @@ -383,6 +384,7 @@ class stories_WT_Module extends WT_Module implements WT_Module_Block, WT_Module_ ->addInlineJavascript(' jQuery("#story_table").dataTable({ "sDom": \'<"H"pf<"dt-clear">irl>t<"F"pl>\', + '.WT_I18N::datatablesI18N().', "bAutoWidth":false, "bPaginate": true, "sPaginationType": "full_numbers",
Bug #<I> - Missing I<I>N in stories module Edit
fisharebest_webtrees
train
3388a73b4738aff3ad722f3809303f3edc34d39f
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -445,11 +445,12 @@ NwBuilder.prototype.copyNwjs = function () { var options = {}; if(['nw', 'nwjs.app', 'nw.exe'].indexOf(destFile) !== -1){ - // ignore nwjs.app/Contents/Resources/*.lproj, otherwise the app name will show as nwjs.app in - // Finder + // ignore nwjs.app/Contents/Resources/*.lproj/InfoPlist.strings, + // otherwise the app name will show as nwjs.app in Finder. + // *.lproj directory itself needs to be kept to support multiple locales. if(destFile === 'nwjs.app'){ options.filter = function(filepath){ - return !/nwjs\.app\/Contents\/Resources\/[^.]+\.lproj(\/|$)/.test(filepath); + return !/nwjs\.app\/Contents\/Resources\/[^.]+\.lproj\/InfoPlist\.strings$/.test(filepath); }; } // rename executable to app name
fix(platform): add osx multiple locale support (#<I>)
nwjs-community_nw-builder
train
f2d04ca39383d367bbc897398f9f9412d1edf300
diff --git a/core/middlewares/clarify.js b/core/middlewares/clarify.js index <HASH>..<HASH> 100644 --- a/core/middlewares/clarify.js +++ b/core/middlewares/clarify.js @@ -252,6 +252,11 @@ module.exports.process = function(req, res, next) { var specID = specUtils.getSpecIDFromUrl(parsedPath.pathToSpec); var specHasHTMLAPIData = !!parseHTMLData.getByID(specID); + trackStats.page({ + pageName: 'clarify', + sessionID: trackStats.getSessionID(req) + }); + if (!specInfo) { res.send('Clarify did not found any information about requested spec, please check URL or update file-tree restarting the app.'); return; @@ -314,11 +319,6 @@ module.exports.process = function(req, res, next) { html = msg; } - trackStats.page({ - pageName: 'clarify', - sessionID: trackStats.getSessionID(req) - }); - res.send(html); }).fail(function(err) { var msg = 'ERROR: Could not find requested or default template for Clarify';
#<I>: log all clarify calls, including failed ones
sourcejs_Source
train
ca6c8b2a716ab74bbb500bcf4bdb37a476f8ddce
diff --git a/packages/blueprint-mongodb/lib/resource-controller.js b/packages/blueprint-mongodb/lib/resource-controller.js index <HASH>..<HASH> 100644 --- a/packages/blueprint-mongodb/lib/resource-controller.js +++ b/packages/blueprint-mongodb/lib/resource-controller.js @@ -285,7 +285,7 @@ module.exports = ResourceController.extend ({ }) .then (data => { if (options.populate) { - return populateHelper.populateModels (data); + return Promise.resolve (this.getPopulateOptions (req)).then (options => populateHelper.populateModels (data, options)); } else { return {[this.controller.plural]: data}; @@ -336,6 +336,10 @@ module.exports = ResourceController.extend ({ prepareResponse (req, res, result) { return result; + }, + + getPopulateOptions (req) { + return null; } }); }, @@ -390,7 +394,7 @@ module.exports = ResourceController.extend ({ }) .then (data => { if (options.populate) { - return populateHelper.populateModel (data); + return Promise.resolve (this.getPopulateOptions (req)).then (options => populateHelper.populateModel (data, options)); } else { return {[this.controller.name]: data}; @@ -433,6 +437,10 @@ module.exports = ResourceController.extend ({ prepareResponse (req, res, result) { return result; + }, + + getPopulateOptions (req) { + return {}; } }); }, @@ -763,7 +771,7 @@ module.exports = ResourceController.extend ({ }) .then (data => { if (directives.populate) { - return populateHelper.populateModels (data); + return Promise.resolve (this.getPopulateOptions (req)).then (options => populateHelper.populateModels (data, options)); } else { return {[this.controller.plural]: data}; @@ -813,6 +821,10 @@ module.exports = ResourceController.extend ({ prepareResponse (req, res, result) { return result; + }, + + getPopulateOptions (req) { + return {}; } }); },
feat: allow you to configure propulate options from controller actions
onehilltech_blueprint
train
6e058825f302f0afa24e9115cc8163c2247d6ec1
diff --git a/lib/Firelit/Request.php b/lib/Firelit/Request.php index <HASH>..<HASH> 100644 --- a/lib/Firelit/Request.php +++ b/lib/Firelit/Request.php @@ -159,7 +159,7 @@ class Request extends Singleton { public function __get($name) { - if (isset($this->$name)) return $this->$name; + if (property_exists($this, $name)) return $this->$name; throw new \Exception('The property "'. $name .'" is not valid.');
Allow a value to be null without throwing an exception
firelit_firelit-framework
train
cb45d22afa2b06ef4a42f206c580b351334b3db0
diff --git a/composer.json b/composer.json index <HASH>..<HASH> 100644 --- a/composer.json +++ b/composer.json @@ -36,7 +36,7 @@ "hhvm": "<3.18" }, "require-dev": { - "johnkary/phpunit-speedtrap": "^1.0.1", + "johnkary/phpunit-speedtrap": "^1.0.1 || ^2.0 || ^3.0", "justinrainbow/json-schema": "^5.0", "keradus/cli-executor": "^1.0", "mikey179/vfsStream": "^1.6", diff --git a/src/Fixer/ControlStructure/IncludeFixer.php b/src/Fixer/ControlStructure/IncludeFixer.php index <HASH>..<HASH> 100644 --- a/src/Fixer/ControlStructure/IncludeFixer.php +++ b/src/Fixer/ControlStructure/IncludeFixer.php @@ -62,7 +62,7 @@ include_once("sample4.php"); private function clearIncludies(Tokens $tokens, array $includies) { - foreach (array_reverse($includies) as $includy) { + foreach ($includies as $includy) { if ($includy['end'] && !$tokens[$includy['end']]->isGivenKind(T_CLOSE_TAG)) { $afterEndIndex = $tokens->getNextNonWhitespace($includy['end']); if (null === $afterEndIndex || !$tokens[$afterEndIndex]->isComment()) { @@ -80,19 +80,10 @@ include_once("sample4.php"); $this->removeWhitespaceAroundIfPossible($tokens, $braces['close']); $tokens->clearTokenAndMergeSurroundingWhitespace($braces['open']); $tokens->clearTokenAndMergeSurroundingWhitespace($braces['close']); - - $nextSiblingIndex = $tokens->getNonEmptySibling($includy['begin'], 1); - if (!$tokens[$nextSiblingIndex]->isWhitespace()) { - $tokens->insertAt($nextSiblingIndex, new Token(array(T_WHITESPACE, ' '))); - } } } - $nextIndex = $includy['begin'] + 1; - - while ($tokens->isEmptyAt($nextIndex)) { - ++$nextIndex; - } + $nextIndex = $tokens->getNonEmptySibling($includy['begin'], 1); if ($tokens[$nextIndex]->isWhitespace()) { $tokens[$nextIndex] = new Token(array(T_WHITESPACE, ' ')); @@ -132,10 +123,12 @@ include_once("sample4.php"); } } - $includies[] = $includy; + $includies[$index] = $includy; } } + krsort($includies); + return $includies; } diff --git a/tests/Fixer/ControlStructure/IncludeFixerTest.php b/tests/Fixer/ControlStructure/IncludeFixerTest.php index <HASH>..<HASH> 100644 --- a/tests/Fixer/ControlStructure/IncludeFixerTest.php +++ b/tests/Fixer/ControlStructure/IncludeFixerTest.php @@ -61,6 +61,36 @@ final class IncludeFixerTest extends AbstractFixerTestCase '<?php include $a;', '<?php include ( $a ) ;', ), + array( + '<?php +require_once "test1.php"; +include_once "test2.php"; +require "test3.php"; +include "test4.php";', + '<?php +require_once("test1.php"); +include_once("test2.php"); +require("test3.php"); +include("test4.php");', + ), + array( + '<?php +require_once #1 +#2 +#3 +"test1.php"#4 +#5 +#6 +;', + '<?php +require_once #1 +(#2 +#3 +"test1.php"#4 +)#5 +#6 +;', + ), ); foreach (array('require', 'require_once', 'include', 'include_once') as $statement) {
DX: allow for more phpunit-speedtrap versions to support more PHPUnit versions
FriendsOfPHP_PHP-CS-Fixer
train
60ec6920d93b13afdf557dab5f176603c65e1f6a
diff --git a/sources/scalac/symtab/Type.java b/sources/scalac/symtab/Type.java index <HASH>..<HASH> 100644 --- a/sources/scalac/symtab/Type.java +++ b/sources/scalac/symtab/Type.java @@ -1316,6 +1316,30 @@ public class Type implements Modifiers, Kinds, TypeTags, EntryTags { } } + /** + * Clones a type i.e. returns a new type where all symbols in + * MethodTypes and PolyTypes have been cloned. This method + * performs no substitution on the type of the cloned symbols. + * Typically, the type of those symbols will be fixed later by + * applying some Map.applyParams method to the returned type. + */ + public Type cloneTypeNoSubst(SymbolCloner cloner) { + switch (this) { + + case MethodType(Symbol[] vparams, Type result): + Symbol[] clones = cloner.cloneSymbols(vparams); + return Type.MethodType(clones, result.cloneTypeNoSubst(cloner)); + + case PolyType(Symbol[] tparams, Type result): + Symbol[] clones = cloner.cloneSymbols(tparams); + return Type.PolyType(clones, result.cloneTypeNoSubst(cloner)); + + default: + return this; + } + } + + // Comparisons ------------------------------------------------------------------ /** Is this type a subtype of that type?
- Added method cloneTypeNoSubst
scala_scala
train
d8b13338b2e80bbb5e30ec65e4aafde7c4c30c6a
diff --git a/tests/test-logger-interface-compliant.php b/tests/test-logger-interface-compliant.php index <HASH>..<HASH> 100644 --- a/tests/test-logger-interface-compliant.php +++ b/tests/test-logger-interface-compliant.php @@ -15,6 +15,7 @@ use IronBound\DB\Query\Simple_Query; use IronBound\DBLogger\Logger; use IronBound\DBLogger\Table; use Psr\Log\LoggerInterface; +use Psr\Log\Test\DummyTest; use Psr\Log\Test\LoggerInterfaceTest; /** @@ -122,7 +123,7 @@ class Test_Logger_Interface_Compliant extends LoggerInterfaceTest { 'string' => 'Foo', 'int' => 0, 'float' => 0.5, - 'nested' => array('with object' => new DummyTest), + 'nested' => array('with object' => new DummyTest()), 'object' => new \DateTime, //'resource' => fopen('php://memory', 'r'), );
Fix fatal error due to class not existing.
iron-bound-designs_IronBound-DB-Logger
train
a8f0e134f94bc0dfb9c0489eecc6493496ae74fd
diff --git a/src/EventExport/Format/HTML/WebArchiveFileWriter.php b/src/EventExport/Format/HTML/WebArchiveFileWriter.php index <HASH>..<HASH> 100644 --- a/src/EventExport/Format/HTML/WebArchiveFileWriter.php +++ b/src/EventExport/Format/HTML/WebArchiveFileWriter.php @@ -54,7 +54,8 @@ abstract class WebArchiveFileWriter implements FileWriterInterface return $tmpDir; } - protected function copyAssets($tmpDir) { + protected function copyAssets($tmpDir) + { $assets = $this->mountManager->listContents('assets:///', true); foreach ($assets as $asset) { @@ -73,7 +74,8 @@ abstract class WebArchiveFileWriter implements FileWriterInterface * @param string $tmpDir * @return MountManager */ - protected function initMountManager($tmpDir) { + protected function initMountManager($tmpDir) + { return new MountManager( [ 'tmp' => new Filesystem( @@ -97,7 +99,8 @@ abstract class WebArchiveFileWriter implements FileWriterInterface * The path of the temporary directory, relative to the 'tmp://' mounted * filesystem. */ - protected function createTemporaryArchiveDirectory() { + protected function createTemporaryArchiveDirectory() + { $exportDir = uniqid('html-export'); $path = 'tmp://' . $exportDir; $this->mountManager->createDir($path); @@ -111,7 +114,8 @@ abstract class WebArchiveFileWriter implements FileWriterInterface * @param string $dir * @return string */ - protected function expandTmpPath($tmpPath) { + protected function expandTmpPath($tmpPath) + { return $this->tmpDir . '/' . $tmpPath; } @@ -119,7 +123,8 @@ abstract class WebArchiveFileWriter implements FileWriterInterface * @param string $dir * @param \Traversable $events */ - protected function writeHtml($dir, $events) { + protected function writeHtml($dir, $events) + { $filePath = $dir . '/index.html'; $this->htmlFileWriter->write( $this->expandTmpPath($filePath),
III-<I>: Fix coding standard violations
cultuurnet_udb3-php
train
e11f53e370e634dc271a18056cd158204971d561
diff --git a/cqlengine/tests/query/test_updates.py b/cqlengine/tests/query/test_updates.py index <HASH>..<HASH> 100644 --- a/cqlengine/tests/query/test_updates.py +++ b/cqlengine/tests/query/test_updates.py @@ -173,12 +173,13 @@ class QueryUpdateTests(BaseCassEngTestCase): self.assertEqual(obj.text_list, ["foo", "bar"]) def test_list_prepend_updates(self): + """ Prepend two things since order is reversed by default by CQL """ partition = uuid4() cluster = 1 TestQueryUpdateModel.objects.create( partition=partition, cluster=cluster, text_list=["foo"]) TestQueryUpdateModel.objects( partition=partition, cluster=cluster).update( - text_list__prepend=['bar']) + text_list__prepend=['bar', 'baz']) obj = TestQueryUpdateModel.objects.get(partition=partition, cluster=cluster) - self.assertEqual(obj.text_list, ["bar", "foo"]) + self.assertEqual(obj.text_list, ["bar", "baz", "foo"])
Updates the prepend to list test to make sure order is preserved when multiple items are prepended
cqlengine_cqlengine
train
96ea71f369f6e94241dc14647c21f1243e52cb6c
diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index <HASH>..<HASH> 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -403,7 +403,7 @@ class _Client(object): if is_transaction: if "profile" in event_opt: event_opt["profile"]["transaction_id"] = event_opt["event_id"] - event_opt["profile"]["version_name"] = event_opt["release"] + event_opt["profile"]["version_name"] = event_opt.get("release", "") envelope.add_profile(event_opt.pop("profile")) envelope.add_transaction(event_opt) else:
Handle no release when uploading profiles (#<I>) * Handle no release when uploading profiles * Using get method instead of try block
getsentry_sentry-python
train
bc6003923e2bce194b30b4437b8354a567a37d95
diff --git a/src/dijon.js b/src/dijon.js index <HASH>..<HASH> 100644 --- a/src/dijon.js +++ b/src/dijon.js @@ -8,7 +8,7 @@ var dijon = { * @constant * @type String */ - VERSION : '0.5.0' + VERSION : '0.5.1' };//dijon
bumped to <I>
creynders_dijon
train
b74f891c2749b01dc5b2710eb657436a89404ec1
diff --git a/src/org/mockito/internal/Incubating.java b/src/org/mockito/internal/Incubating.java index <HASH>..<HASH> 100644 --- a/src/org/mockito/internal/Incubating.java +++ b/src/org/mockito/internal/Incubating.java @@ -9,7 +9,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** - * Indicates the type or method is work in progress and might change. + * Indicates the type or method is <strong>work in progress</strong> and might change. */ @Retention(RetentionPolicy.RUNTIME) public @interface Incubating { diff --git a/src/org/mockito/internal/configuration/ClassPathLoader.java b/src/org/mockito/internal/configuration/ClassPathLoader.java index <HASH>..<HASH> 100644 --- a/src/org/mockito/internal/configuration/ClassPathLoader.java +++ b/src/org/mockito/internal/configuration/ClassPathLoader.java @@ -4,6 +4,11 @@ */ package org.mockito.internal.configuration; +import org.mockito.configuration.IMockitoConfiguration; +import org.mockito.exceptions.misusing.MockitoConfigurationException; +import org.mockito.internal.creation.CglibMockMaker; +import org.mockito.plugins.MockMaker; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; @@ -15,10 +20,6 @@ import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.ServiceConfigurationError; -import org.mockito.configuration.IMockitoConfiguration; -import org.mockito.exceptions.misusing.MockitoConfigurationException; -import org.mockito.internal.creation.CglibMockMaker; -import org.mockito.plugins.MockMaker; public class ClassPathLoader { private static final MockMaker mockMaker = findPlatformMockMaker(); @@ -78,7 +79,7 @@ public class ClassPathLoader { Enumeration<URL> resources; try { - resources = loader.getResources("META-INF/services/" + service.getName()); + resources = loader.getResources("mockito-extensions/" + service.getName()); } catch (IOException e) { throw new ServiceConfigurationError("Failed to load " + service, e); }
issue <I> : now load configuration file from classpath:mockito-extensions instead of classpath:META-INF/services, this due to the fact that ApkBuilder on Android discard resources located under META-INF.
mockito_mockito
train
f01db440456738546dabce91f99d1d4778273acd
diff --git a/alignak/scheduler.py b/alignak/scheduler.py index <HASH>..<HASH> 100644 --- a/alignak/scheduler.py +++ b/alignak/scheduler.py @@ -1875,10 +1875,10 @@ class Scheduler(object): # pylint: disable=R0902 h.passive_checks_enabled and not h.active_checks_enabled] statsmgr.gauge('freshness.hosts-count', len(hosts)) items.extend(hosts) - logger.info("Freshness check is enabled for %d hosts", len(hosts)) + logger.debuginfo("Freshness check is enabled for %d hosts", len(hosts)) hosts = [h for h in self.hosts if h.check_freshness and h.freshness_expired] - logger.info("Freshness still expired for %d hosts", len(hosts)) + logger.debug("Freshness still expired for %d hosts", len(hosts)) for h in hosts: h.last_chk = now self.add(h.get_check_result_brok()) @@ -1902,11 +1902,11 @@ class Scheduler(object): # pylint: disable=R0902 s.passive_checks_enabled and not s.active_checks_enabled] statsmgr.gauge('freshness.services-count', len(services)) items.extend(services) - logger.info("Freshness check is enabled for %d services", len(services)) + logger.debug("Freshness check is enabled for %d services", len(services)) services = [s for s in self.services if not self.hosts[s.host].freshness_expired and s.check_freshness and s.freshness_expired] - logger.info("Freshness still expired for %d services", len(services)) + logger.debug("Freshness still expired for %d services", len(services)) for s in services: s.last_chk = now self.add(s.get_check_result_brok())
Clean some extraneous log (avoid being too verbose)
Alignak-monitoring_alignak
train
72f19c07330b32211e0b8bdfdfb1d9d010d2d7ff
diff --git a/eventsourcingtests/test_stored_events.py b/eventsourcingtests/test_stored_events.py index <HASH>..<HASH> 100644 --- a/eventsourcingtests/test_stored_events.py +++ b/eventsourcingtests/test_stored_events.py @@ -211,8 +211,9 @@ class StoredEventRepositoryTestCase(unittest.TestCase): self.assertEqual(stored_events[18].event_attrs, retrieved_events[0].event_attrs) # Check the stored event iterator can get all the events. - # Todo: Move this to a separate test? - start_time = datetime.datetime.now() + # Todo: Move this test of the SimpleStoredEventIterator to a separate test case? + # Todo: Write a test case for ThreadedStoredEventIterator. + # start_time = datetime.datetime.now() page_size = 50 iterator = SimpleStoredEventIterator(stored_event_repo, stored_entity_id, page_size=page_size) retrieved_events = list(iterator) @@ -225,11 +226,11 @@ class StoredEventRepositoryTestCase(unittest.TestCase): self.assertEqual(stored_event1.event_attrs, retrieved_events[0].event_attrs) self.assertEqual(stored_events[-1].event_attrs, retrieved_events[-1].event_attrs) - duration = (datetime.datetime.now() - start_time).total_seconds() + # duration = (datetime.datetime.now() - start_time).total_seconds() # print("Total duration: {}".format(duration)) - average_item_duration = duration / len(retrieved_events) + # average_item_duration = duration / len(retrieved_events) # print("Average item duration: {}".format(average_item_duration)) # print("Average item rate: {}".format(1.0 / average_item_duration)) - self.assertLess(average_item_duration, 0.0005) + # self.assertLess(average_item_duration, 0.0005)
Removed run time check from test.
johnbywater_eventsourcing
train
3738358135dba55d120053f111cf6258419746fd
diff --git a/activejob/lib/active_job/test_helper.rb b/activejob/lib/active_job/test_helper.rb index <HASH>..<HASH> 100644 --- a/activejob/lib/active_job/test_helper.rb +++ b/activejob/lib/active_job/test_helper.rb @@ -55,7 +55,7 @@ module ActiveJob # assert_enqueued_jobs 2 # end # - # If a block is passed, that block should cause the specified number of + # If a block is passed, that block will cause the specified number of # jobs to be enqueued. # # def test_jobs_again @@ -77,14 +77,23 @@ module ActiveJob # HelloJob.perform_later('jeremy') # end # end - def assert_enqueued_jobs(number, only: nil) + # + # The number of times a job is enqueued to a specific queue can also be asserted. + # + # def test_logging_job + # assert_enqueued_jobs 2, queue: 'default' do + # LoggingJob.perform_later + # HelloJob.perform_later('elfassy') + # end + # end + def assert_enqueued_jobs(number, only: nil, queue: nil) if block_given? - original_count = enqueued_jobs_size(only: only) + original_count = enqueued_jobs_size(only: only, queue: queue) yield - new_count = enqueued_jobs_size(only: only) + new_count = enqueued_jobs_size(only: only, queue: queue) assert_equal number, new_count - original_count, "#{number} jobs expected, but #{new_count - original_count} were enqueued" else - actual_count = enqueued_jobs_size(only: only) + actual_count = enqueued_jobs_size(only: only, queue: queue) assert_equal number, actual_count, "#{number} jobs expected, but #{actual_count} were enqueued" end end @@ -323,11 +332,16 @@ module ActiveJob performed_jobs.clear end - def enqueued_jobs_size(only: nil) - if only - enqueued_jobs.count { |job| Array(only).include?(job.fetch(:job)) } - else - enqueued_jobs.count + def enqueued_jobs_size(only: nil, queue: nil) + enqueued_jobs.count do |job| + job_class = job.fetch(:job) + if only + next false unless Array(only).include?(job_class) + end + if queue + next false unless queue.to_s == job.fetch(:queue, job_class.queue_name) + end + true end end diff --git a/activejob/test/cases/test_helper_test.rb b/activejob/test/cases/test_helper_test.rb index <HASH>..<HASH> 100644 --- a/activejob/test/cases/test_helper_test.rb +++ b/activejob/test/cases/test_helper_test.rb @@ -110,6 +110,27 @@ class EnqueuedJobsTest < ActiveJob::TestCase end end + def test_assert_enqueued_jobs_with_only_and_queue_option + assert_nothing_raised do + assert_enqueued_jobs 1, only: HelloJob, queue: :some_queue do + HelloJob.set(queue: :some_queue).perform_later + HelloJob.set(queue: :other_queue).perform_later + LoggingJob.perform_later + end + end + end + + def test_assert_enqueued_jobs_with_queue_option + assert_nothing_raised do + assert_enqueued_jobs 2, queue: :default do + HelloJob.perform_later + LoggingJob.perform_later + HelloJob.set(queue: :other_queue).perform_later + LoggingJob.set(queue: :other_queue).perform_later + end + end + end + def test_assert_enqueued_jobs_with_only_option_and_none_sent error = assert_raise ActiveSupport::TestCase::Assertion do assert_enqueued_jobs 1, only: HelloJob do
assert_enqueued_jobs with queue option
rails_rails
train
acc120e312065ece06c01717a3b4704d6cd82876
diff --git a/djangoratings/managers.py b/djangoratings/managers.py index <HASH>..<HASH> 100644 --- a/djangoratings/managers.py +++ b/djangoratings/managers.py @@ -1,23 +1,30 @@ from django.db.models import Manager +from django.db.models.query import QuerySet + from django.contrib.contenttypes.models import ContentType import itertools -class VoteManager(Manager): - def delete_from_ip_address(self, ip_address): +class VoteQuerySet(QuerySet): + def delete(self, *args, **kwargs): + """Handles updating the related `votes` and `score` fields attached to the model.""" # XXX: circular import from fields import RatingField - qs = self.get_query_set().filter(ip_address=ip_address) + qs = self.distinct().values_list('content_type', 'object_id').order_by('content_type') to_update = [] - for content_type, objects in itertools.groupby(qs.distinct().values_list('content_type', 'object_id').order_by('content_type'), key=lambda x: x[0]): + for content_type, objects in itertools.groupby(qs, key=lambda x: x[0]): ct = ContentType.objects.get(pk=content_type) to_update.extend(list(ct.model_class().objects.filter(pk__in=list(objects)[0]))) - - qs.delete() - + + super(VoteQuerySet, self).delete(*args, **kwargs) + # TODO: this could be improved for obj in to_update: for field in getattr(obj, '_djangoratings', []): getattr(obj, field.name)._update() - obj.save() \ No newline at end of file + obj.save() + +class VoteManager(Manager): + def get_query_set(self): + return VoteQuerySet(self.model) \ No newline at end of file diff --git a/djangoratings/tests.py b/djangoratings/tests.py index <HASH>..<HASH> 100644 --- a/djangoratings/tests.py +++ b/djangoratings/tests.py @@ -46,7 +46,8 @@ class RatingTestCase(unittest.TestCase): self.assertRaises(IPLimitReached, instance.rating2.add, score=2, user=user2, ip_address='127.0.0.3') - Vote.objects.delete_from_ip_address('127.0.0.3') + # Test deletion hooks + Vote.objects.filter(ip_address='127.0.0.3').delete() instance = RatingTestModel.objects.get(pk=instance.pk)
Delete hook on Vote now works properly. Removed delete_form_ip_address method as it was redundant
dcramer_django-ratings
train
8de93e6197069199b610cc602ca33bace113d7a2
diff --git a/core/roboconf-target-docker/src/main/java/net/roboconf/target/docker/internal/DockerMachineConfigurator.java b/core/roboconf-target-docker/src/main/java/net/roboconf/target/docker/internal/DockerMachineConfigurator.java index <HASH>..<HASH> 100644 --- a/core/roboconf-target-docker/src/main/java/net/roboconf/target/docker/internal/DockerMachineConfigurator.java +++ b/core/roboconf-target-docker/src/main/java/net/roboconf/target/docker/internal/DockerMachineConfigurator.java @@ -242,6 +242,7 @@ public class DockerMachineConfigurator implements MachineConfigurator { // Start the build. // This will block the current thread until the creation is complete. + this.logger.fine( "Asking Docker to build the image from our Dockerfile." ); response = this.dockerClient.buildImageCmd( dockerfile ).withTag( imageId ).exec(); // Reading the stream does not take time as everything is sent at once by Docker. @@ -255,7 +256,6 @@ public class DockerMachineConfigurator implements MachineConfigurator { // No need to get the real image ID... Docker has it. // Besides, we search images by both IDs and tags. - } catch( Exception e ) { throw new TargetException( e );
#<I> Redeployment of a Docker instance
roboconf_roboconf-platform
train
bd401e7e5d166f9aa1e0a978f4cd2789e6959afc
diff --git a/pysat/tests/classes/cls_instrument_access.py b/pysat/tests/classes/cls_instrument_access.py index <HASH>..<HASH> 100644 --- a/pysat/tests/classes/cls_instrument_access.py +++ b/pysat/tests/classes/cls_instrument_access.py @@ -110,24 +110,24 @@ class InstAccessTests(object): # than date in this case. self.testInst.load(date=no_data_d) - # Confirm by checking against caplog that metadata was - # not assigned. - captured = caplog.text + # Confirm by checking against caplog that metadata was + # not assigned. + captured = caplog.text - assert captured.find("Metadata was not assigned as there") >= 0 + assert captured.find("Metadata was not assigned as there") >= 0 - # Generate string to verify proper no data message - output_str = '{platform} {name} {tag} {inst_id}' - output_str = output_str.format(platform=self.testInst.platform, - name=self.testInst.name, - tag=self.testInst.tag, - inst_id=self.testInst.inst_id) - output_str = ''.join(("No ", output_str)) + # Generate string to verify proper no data message + output_str = '{platform} {name} {tag} {inst_id}' + output_str = output_str.format(platform=self.testInst.platform, + name=self.testInst.name, + tag=self.testInst.tag, + inst_id=self.testInst.inst_id) + output_str = ''.join(("No ", output_str)) - # Remove any extra spaces. Follows code in _instrument. - output_str = " ".join(output_str.split()) + # Remove any extra spaces. Follows code in _instrument. + output_str = " ".join(output_str.split()) - assert captured.find(output_str) >= 0 + assert captured.find(output_str) >= 0 return
STY: Reduce area checked by logging
rstoneback_pysat
train
b879cfaaa9a657550922e58fdf98450074ef517a
diff --git a/lib/instrumental/agent.rb b/lib/instrumental/agent.rb index <HASH>..<HASH> 100644 --- a/lib/instrumental/agent.rb +++ b/lib/instrumental/agent.rb @@ -343,11 +343,17 @@ module Instrumental end end rescue Exception => err - logger.error "Instrumental Error: #{err}" - logger.error err.backtrace.join("\n") + if err.is_a?(EOFError) + # nop + elsif Errno::ECONNREFUSED + logger.error "unable to connect to Instrumental." + else + logger.error "Instrumental Error: #{err}" + logger.error err.backtrace.join("\n") + end if @allow_reconnect == false || (command_options && command_options[:allow_reconnect] == false) - logger.error "Not trying to reconnect" + logger.info "Not trying to reconnect" return end if command_and_args
Hide normal disconnect exception from logs, simplify connection refused message.
Instrumental_instrumental_agent-ruby
train
6f8373d29f52fb38148865ed42fc6208b5fb48f7
diff --git a/molecule/command/converge.py b/molecule/command/converge.py index <HASH>..<HASH> 100644 --- a/molecule/command/converge.py +++ b/molecule/command/converge.py @@ -133,7 +133,7 @@ class Converge(base.Base): yaml.dump(ansible_env, default_flow_style=False, indent=2)) - util.debug('ANSIBLE PLAYBOOK', str(ansible.ansible)) + util.debug('ANSIBLE PLAYBOOK', str(ansible._ansible)) util.print_info("Starting Ansible Run ...") status, output = ansible.execute(hide_errors=hide_errors)
Correct a converge --debug bug (#<I>) Found a bug with the <I> release where --debug was returning a failure. Fixes: #<I>
ansible_molecule
train
f5d644733b4e0fddaaa5083c223279c998acbdb5
diff --git a/lib/OpenLayers/Layer.js b/lib/OpenLayers/Layer.js index <HASH>..<HASH> 100644 --- a/lib/OpenLayers/Layer.js +++ b/lib/OpenLayers/Layer.js @@ -226,6 +226,9 @@ OpenLayers.Layer.prototype = { } } this.initResolutions(); + + this.inRange = this.calculateInRange(); + }, /**
once we have set the layer's resolutions array, we can set its inRange git-svn-id: <URL>
openlayers_openlayers
train
f7175d2d290864a71375a284b12fd7b2a0b25411
diff --git a/addon/utils/e3-interpolate.js b/addon/utils/e3-interpolate.js index <HASH>..<HASH> 100644 --- a/addon/utils/e3-interpolate.js +++ b/addon/utils/e3-interpolate.js @@ -15,13 +15,16 @@ const {keys} = Object; */ export default function interpolate(hashA, hashB, percent = 0) { var resHash = {}; + keys(hashA).forEach(key => { let a = hashA[key]; let b = hashB[key]; if(isArray(a)) { - resHash[key] = a.map((aVal, index) => { - return interpolatePrimitives(aVal, b[index], percent); - }); + // TODO: we need to guarantee the array lengths in some way. :-\ + resHash[key] = interpolateArray(a, b, percent); + // resHash[key] = a.map((aVal, index) => { + // return interpolatePrimitives(aVal, b[index], percent); + // }); } else { resHash[key] = interpolatePrimitives(a, b, percent); } @@ -30,6 +33,18 @@ export default function interpolate(hashA, hashB, percent = 0) { return resHash; } +function interpolateArray(arrA, arrB, percent) { + let length = Math.max(arrA.length, arrB.length); + let result = []; + for (let i = 0; i < length; i++) { + let valA = arrA[i] || 0; + let valB = arrB[i] || 0; + result.push(interpolatePrimitives(valA, valB, percent)); + }; + + return result; +} + function interpolatePrimitives(valA, valB, percent) { // Determine the type of valA. // TODO: Support more than just numbers. diff --git a/tests/unit/utils/e3-interpolate-test.js b/tests/unit/utils/e3-interpolate-test.js index <HASH>..<HASH> 100644 --- a/tests/unit/utils/e3-interpolate-test.js +++ b/tests/unit/utils/e3-interpolate-test.js @@ -18,3 +18,10 @@ test('add array of values interpolation', function(assert) { var result = e3Interpolate(a, b, 0.5); assert.deepEqual(result, {x: [10,10,10]}); }); + +test('array of values interpolation with different lengths', function(assert) { + let a = {x: []}; + let b = {x: [20, 10, 0]}; + var result = e3Interpolate(a, b, 0.5); + assert.deepEqual(result, {x: [10,5,0]}); +});
Interpolate Mixed-length Arrays
RavelLaw_e3
train
01a0d400b14d960b2deb3ba35f7a056de7653c78
diff --git a/zounds/core/axis.py b/zounds/core/axis.py index <HASH>..<HASH> 100644 --- a/zounds/core/axis.py +++ b/zounds/core/axis.py @@ -71,7 +71,8 @@ class ArrayWithUnits(np.ndarray): @classmethod def zeros(cls, example): - return cls.from_example(np.zeros(example.shape), example) + return cls.from_example( + np.zeros(example.shape, dtype=example.dtype), example) def sum(self, axis=None, dtype=None, **kwargs): result = super(ArrayWithUnits, self).sum(axis, dtype, **kwargs) diff --git a/zounds/core/test_core.py b/zounds/core/test_core.py index <HASH>..<HASH> 100644 --- a/zounds/core/test_core.py +++ b/zounds/core/test_core.py @@ -187,6 +187,13 @@ class CoreTests(unittest2.TestCase): self.assertSequenceEqual(arr.dimensions, arr2.dimensions) np.testing.assert_allclose(arr2, 0) + def test_zeros_dtype(self): + arr = ArrayWithUnits( + np.zeros((100, 10), dtype=np.complex128), + [ContrivedDimension(10), ContrivedDimension2(10)]) + arr2 = ArrayWithUnits.zeros(arr) + self.assertEqual(arr.dtype, arr2.dtype) + def test_size_is_not_modified_on_example_dimensions(self): arr = ArrayWithUnits( np.zeros((100, 10)),
Fix bug whereby ArrayWithUnits.zeros did not match dtype
JohnVinyard_zounds
train
65ab38dde2851dd8a590c4a0ccc967ba86f64bb1
diff --git a/python/src/wslink/backends/aiohttp/__init__.py b/python/src/wslink/backends/aiohttp/__init__.py index <HASH>..<HASH> 100644 --- a/python/src/wslink/backends/aiohttp/__init__.py +++ b/python/src/wslink/backends/aiohttp/__init__.py @@ -113,7 +113,7 @@ def create_webserver(server_config): routes = [] for route, server_protocol in ws_routes.items(): - protocol_handler = WslinkHandler(server_protocol) + protocol_handler = WslinkHandler(server_protocol, web_app) ws_routes[route] = protocol_handler routes.append( aiohttp_web.get(_fix_path(route), protocol_handler.handleWsRequest) @@ -153,13 +153,34 @@ def create_webserver(server_config): class WslinkHandler(object): - def __init__(self, protocol=None): + def __init__(self, protocol=None, web_app=None): self.serverProtocol = protocol + self.web_app = web_app self.functionMap = {} self.attachmentsReceived = {} self.attachmentsRecvQueue = [] self.connections = {} + # Build the rpc method dictionary, assuming we were given a serverprotocol + if self.getServerProtocol(): + protocolList = self.getServerProtocol().getLinkProtocols() + protocolList.append(self.getServerProtocol()) + for protocolObject in protocolList: + protocolObject.init( + self.publish, + self.addAttachment, + lambda: schedule_coroutine(0, _stop_server, self.web_app), + ) + test = lambda x: inspect.ismethod(x) or inspect.isfunction(x) + for k in inspect.getmembers(protocolObject.__class__, test): + proc = k[1] + if "_wslinkuris" in proc.__dict__: + uri_info = proc.__dict__["_wslinkuris"][0] + if "uri" in uri_info: + uri = uri_info["uri"] + self.functionMap[uri] = (protocolObject, proc) + pub.publishManager.registerProtocol(self) + def setServerProtocol(self, protocol): self.serverProtocol = protocol @@ -176,6 +197,8 @@ class WslinkHandler(object): code=aiohttp.WSCloseCode.GOING_AWAY, message="Server shutdown" ) + pub.publishManager.unregisterProtocol(self) + async def handleWsRequest(self, request): aiohttp_app = request.app @@ -192,7 +215,7 @@ class WslinkHandler(object): await current_ws.prepare(request) - await self.onConnect(request) + await self.onConnect() async for msg in current_ws: await self.onMessage(msg, client_id) @@ -209,32 +232,11 @@ class WslinkHandler(object): return current_ws - async def onConnect(self, request): - aiohttp_app = request.app - - # Build the rpc method dictionary. self.serverProtocol isn't set until connected. - if not self.getServerProtocol(): - return - protocolList = self.getServerProtocol().getLinkProtocols() - protocolList.append(self.getServerProtocol()) - for protocolObject in protocolList: - protocolObject.init( - self.publish, - self.addAttachment, - lambda: schedule_coroutine(0, _stop_server, aiohttp_app), - ) - test = lambda x: inspect.ismethod(x) or inspect.isfunction(x) - for k in inspect.getmembers(protocolObject.__class__, test): - proc = k[1] - if "_wslinkuris" in proc.__dict__: - uri_info = proc.__dict__["_wslinkuris"][0] - if "uri" in uri_info: - uri = uri_info["uri"] - self.functionMap[uri] = (protocolObject, proc) - pub.publishManager.registerProtocol(self) + async def onConnect(self): + pass async def onClose(self): - pub.publishManager.unregisterProtocol(self) + pass async def handleSystemMessage(self, rpcid, methodName, args, client_id): rpcList = rpcid.split(":")
fix(publish): Only send publish msgs to each client once
Kitware_wslink
train
fa0f1a6e42420b504e95e3727ec816ccd79e0f9e
diff --git a/test/common.js b/test/common.js index <HASH>..<HASH> 100644 --- a/test/common.js +++ b/test/common.js @@ -1,7 +1,7 @@ /* global unexpected:true, expect:true, expectWithUnexpectedMagicPen:true, weknowhow, jasmine */ /* eslint no-unused-vars: "off" */ var unexpected = - typeof window === 'undefined' + typeof window === 'undefined' || !window.weknowhow ? require('../lib/').clone() : window.weknowhow.expect.clone();
Protect against the wrong include being taken on jest.
unexpectedjs_unexpected
train
a1e8dff0573178f6ae2a26d97afc52e95d1d2afb
diff --git a/MAVProxy/modules/lib/mp_menu.py b/MAVProxy/modules/lib/mp_menu.py index <HASH>..<HASH> 100644 --- a/MAVProxy/modules/lib/mp_menu.py +++ b/MAVProxy/modules/lib/mp_menu.py @@ -10,6 +10,8 @@ from MAVProxy.modules.lib import mp_util from MAVProxy.modules.lib import multiproc import platform +idmap = {} + class MPMenuGeneric(object): '''a MP menu separator''' def __init__(self): @@ -76,8 +78,15 @@ class MPMenuItem(MPMenuGeneric): '''id used to identify the returned menu items uses a 16 bit signed integer. We allocate these on use, and use __getstate__ to avoid them crossing processs boundaries''' if getattr(self, '_id', None) is None: - from MAVProxy.modules.lib.wx_loader import wx - self._id = wx.NewId() + global idmap + import os + key_tuple = (os.getpid(), self.name, self.returnkey) + if key_tuple in idmap: + self._id = idmap[key_tuple] + else: + from MAVProxy.modules.lib.wx_loader import wx + self._id = wx.NewId() + idmap[key_tuple] = self._id return self._id def _append(self, menu):
prevent creation of new IDs for re-creation of menus
ArduPilot_MAVProxy
train
da44ca815653a8e2ea9a79436aa052d1856b9c4d
diff --git a/lib/chore/job.rb b/lib/chore/job.rb index <HASH>..<HASH> 100644 --- a/lib/chore/job.rb +++ b/lib/chore/job.rb @@ -2,6 +2,8 @@ require 'chore/hooks' module Chore module Job + Chore::CLI.register_option 'publisher', '--publisher PUBLISHER', 'Set a global publisher to be used for all jobs' + class RejectMessageException < Exception # Throw a RejectMessageException from your job to signal that the message should be rejected. # The semantics of +reject+ are queue implementation dependent. @@ -24,11 +26,10 @@ module Chore # # Pass a hash of options to queue_options the included class's use of Chore::Job - # +opts+ has a couple of required options. + # +opts+ has just the one required option. # * +:name+: which should map to the name of the queue this job should be published to. - # * +:publisher+: the publisher to use for this job. def queue_options(opts = {}) - @chore_options = (@chore_options || DEFAULT_OPTIONS).merge(opts) + @chore_options = (@chore_options || DEFAULT_OPTIONS).merge(opts_from_cli).merge(opts) required_options.each do |k| raise ArgumentError.new("#{self.to_s} :#{k} is a required option for Chore::Job") unless @chore_options[k] end @@ -39,13 +40,17 @@ module Chore # queue_options params. # def required_options - [:name,:publisher] + [:name, :publisher] end def options #:nodoc: @chore_options ||= queue_options end + def opts_from_cli + @from_cli ||= (Chore.config.marshal_dump.select {|k,v| required_options.include? k } || {}) + end + # # Execute the current job. We create an instance of the job to do the perform # as this allows the jobs themselves to do initialization that might require access diff --git a/spec/chore/job_spec.rb b/spec/chore/job_spec.rb index <HASH>..<HASH> 100644 --- a/spec/chore/job_spec.rb +++ b/spec/chore/job_spec.rb @@ -46,4 +46,24 @@ describe Chore::Job do TestJob.perform_async(*args) end end + + describe 'publisher configured via config file' do + before do + Chore.configure do |c| + c.publisher = Chore::Publisher + end + + class NoPublisherJob + include Chore::Job + queue_options :name => "test_queue" + + def perform + end + end + end + + it 'should have the default publisher' do + NoPublisherJob.options[:publisher].should == Chore::Publisher + end + end end diff --git a/spec/chore/worker_spec.rb b/spec/chore/worker_spec.rb index <HASH>..<HASH> 100644 --- a/spec/chore/worker_spec.rb +++ b/spec/chore/worker_spec.rb @@ -89,7 +89,7 @@ describe Chore::Worker do it 'should process after message hooks with success or failure' do Watcher::Publisher::Statsd.stub(:new) Chore.config.statsd = {} - Chore::Tapjoy::register_tapjoy_handlers! + Chore::Tapjoy::Monitoring.register_tapjoy_handlers! work = [] work << Chore::UnitOfWork.new('1', Chore::JsonEncoder.encode(job), consumer) work << Chore::UnitOfWork.new('2', Chore::JsonEncoder.encode(breaking_job), consumer)
adding ability to set default publisher in config file
Tapjoy_chore
train
ad06d72c0230e06a11bbb521260243036a776320
diff --git a/themes-book/pressbooks-book/functions.php b/themes-book/pressbooks-book/functions.php index <HASH>..<HASH> 100644 --- a/themes-book/pressbooks-book/functions.php +++ b/themes-book/pressbooks-book/functions.php @@ -86,6 +86,9 @@ function pb_enqueue_scripts() { if ( ! is_file( $fullpath ) ) { \Pressbooks\Container::get( 'Sass' )->updateWebBookStyleSheet(); } + if ( \Pressbooks\Container::get( 'Sass' )->isCurrentThemeCompatible( 1 ) ) { + wp_enqueue_style( 'pressbooks/base', PB_PLUGIN_URL . 'themes-book/pressbooks-book/style.css', false, '1.7.0', 'screen, print' ); + } wp_enqueue_style( 'pressbooks/theme', \Pressbooks\Container::get( 'Sass' )->urlToUserGeneratedCss() . '/style.css', false, null, 'screen, print' ); } else { wp_enqueue_style( 'pressbooks/theme', get_stylesheet_directory_uri() . '/style.css', false, null, 'screen, print' );
Load base theme for old themes.
pressbooks_pressbooks
train
7fa25ab8fb54aa7423283f67b8622b67bac8cdc8
diff --git a/lib/active_delegate/attributes.rb b/lib/active_delegate/attributes.rb index <HASH>..<HASH> 100644 --- a/lib/active_delegate/attributes.rb +++ b/lib/active_delegate/attributes.rb @@ -215,22 +215,11 @@ module ActiveDelegate if needs_type_cast?(attr_name) cast_type = attribute_cast_type(attr_name) + redefine_attribute_methods(attrib, attr_name, cast_type, attr_assoc, attr_cattr) - @model.class_eval do - class_eval <<-EOM, __FILE__, __LINE__ + 1 - def #{attrib} - assoc_value = send(:#{attr_assoc}).try(:#{attr_name}) || self.class.try(:#{attr_cattr}) - ActiveRecord::Type.lookup(:#{cast_type}).cast(assoc_value) - end - - def #{attrib}=(value) - assoc_record = send(:#{attr_assoc}) - assoc_value = ActiveRecord::Type.lookup(:#{cast_type}).cast(value) - assoc_value = assoc_record.class.type_for_attribute('#{attr_name}').cast(assoc_value) - - assoc_record.send(:#{attr_name}=, assoc_value) - end - EOM + localized_attributes.each do |loc_attr_name| + loc_attrib = prefix_attribute(loc_attr_name) + redefine_attribute_methods(loc_attrib, loc_attr_name, cast_type, attr_assoc, attr_cattr) end end end @@ -286,5 +275,25 @@ module ActiveDelegate joins(attr_assoc).where.not(attr_table => { attr_name => names }) end end + + # Redefine attribute methods + def redefine_attribute_methods(attrib, attr_name, cast_type, attr_assoc, attr_cattr) + @model.class_eval do + class_eval <<-EOM, __FILE__, __LINE__ + 1 + def #{attrib} + assoc_value = send(:#{attr_assoc}).try(:#{attr_name}) || self.class.try(:#{attr_cattr}) + ActiveRecord::Type.lookup(:#{cast_type}).cast(assoc_value) + end + + def #{attrib}=(value) + assoc_record = send(:#{attr_assoc}) + assoc_value = ActiveRecord::Type.lookup(:#{cast_type}).cast(value) + assoc_value = assoc_record.class.type_for_attribute('#{attr_name}').cast(assoc_value) + + assoc_record.send(:#{attr_name}=, assoc_value) + end + EOM + end + end end end
add support for localized attributes type casting
hardpixel_active-delegate
train
0e260a079f2cdc54a1479eb366e5defd08bc1900
diff --git a/openquake/hazardlib/source/rupture.py b/openquake/hazardlib/source/rupture.py index <HASH>..<HASH> 100644 --- a/openquake/hazardlib/source/rupture.py +++ b/openquake/hazardlib/source/rupture.py @@ -48,8 +48,11 @@ classes = {} # initialized in .init() def to_checksum(cls1, cls2): - s = '%s,%s' % (cls1.__name__, cls2.__name__) - return zlib.adler32(s.encode('ascii')) + """ + Convert a pair of classes into a numeric code (uint32) + """ + names = '%s,%s' % (cls1.__name__, cls2.__name__) + return zlib.adler32(names.encode('ascii')) @with_slots
Added a docstring [skip CI]
gem_oq-engine
train
65ea33e427e20c7177a110b3c4df4a8875e300e3
diff --git a/tools/run_tests/xds_k8s_test_driver/framework/xds_k8s_testcase.py b/tools/run_tests/xds_k8s_test_driver/framework/xds_k8s_testcase.py index <HASH>..<HASH> 100644 --- a/tools/run_tests/xds_k8s_test_driver/framework/xds_k8s_testcase.py +++ b/tools/run_tests/xds_k8s_test_driver/framework/xds_k8s_testcase.py @@ -349,7 +349,7 @@ class SecurityXdsKubernetesTestCase(XdsKubernetesTestCase): # Confirm regular TLS: server local cert == client remote cert self.assertNotEmpty(client_tls.remote_certificate, msg="(mTLS) Client remote certificate is missing") - if cls.check_local_certs: + if self.check_local_certs: self.assertNotEmpty( server_tls.local_certificate, msg="(mTLS) Server local certificate is missing") @@ -362,7 +362,7 @@ class SecurityXdsKubernetesTestCase(XdsKubernetesTestCase): # mTLS: server remote cert == client local cert self.assertNotEmpty(server_tls.remote_certificate, msg="(mTLS) Server remote certificate is missing") - if cls.check_local_certs: + if self.check_local_certs: self.assertNotEmpty( client_tls.local_certificate, msg="(mTLS) Client local certificate is missing") @@ -385,7 +385,7 @@ class SecurityXdsKubernetesTestCase(XdsKubernetesTestCase): # Regular TLS: server local cert == client remote cert self.assertNotEmpty(client_tls.remote_certificate, msg="(TLS) Client remote certificate is missing") - if cls.check_local_certs: + if self.check_local_certs: self.assertNotEmpty(server_tls.local_certificate, msg="(TLS) Server local certificate is missing") self.assertEqual(
xds-k8s Fix NameError name 'cls' is not defined (#<I>)
grpc_grpc
train
e730cf5491a3972380c9f2e93cae12129ea9e757
diff --git a/lib/ronin/platform/extension.rb b/lib/ronin/platform/extension.rb index <HASH>..<HASH> 100644 --- a/lib/ronin/platform/extension.rb +++ b/lib/ronin/platform/extension.rb @@ -72,7 +72,11 @@ module Ronin # end # def Extension.load(name,&block) - Extension.new(name) { |ext| ext.include(name,&block) } + ext = Extension.new(name) + ext.include(name) + + block.call(ext) if block + return ext end #
Fix Extension.load. * Since Extension#initialize instance_evals blocks.
ronin-ruby_ronin
train
7980665e1f7f097a9123878369bc589a08337551
diff --git a/salt/utils/args.py b/salt/utils/args.py index <HASH>..<HASH> 100644 --- a/salt/utils/args.py +++ b/salt/utils/args.py @@ -24,13 +24,7 @@ def condition_input(args, kwargs): ''' ret = [] for arg in args: - # XXX: We might need to revisit this code when we move to Py3 - # since long's are int's in Py3 - if (six.PY3 and isinstance(arg, six.integer_types)) or \ - (six.PY2 and isinstance(arg, long)): # pylint: disable=incompatible-py3-code - ret.append(str(arg)) - else: - ret.append(arg) + ret.append(arg) if isinstance(kwargs, dict) and kwargs: kw_ = {'__kwarg__': True} for key, val in six.iteritems(kwargs):
Do not reformat strings into ints in py3 when collecting args (#<I>) Fixes failing client kwarg test under py3
saltstack_salt
train
09e62762d1419420117a97d79dbaeb710441bf14
diff --git a/hazelcast/src/main/java/com/hazelcast/spi/impl/operationservice/impl/InvocationMonitor.java b/hazelcast/src/main/java/com/hazelcast/spi/impl/operationservice/impl/InvocationMonitor.java index <HASH>..<HASH> 100644 --- a/hazelcast/src/main/java/com/hazelcast/spi/impl/operationservice/impl/InvocationMonitor.java +++ b/hazelcast/src/main/java/com/hazelcast/spi/impl/operationservice/impl/InvocationMonitor.java @@ -61,9 +61,9 @@ public class InvocationMonitor { private final ExecutionService executionService; private final InvocationMonitorThread monitorThread; private final ILogger logger; - @Probe(name = "invocations.backupTimeouts", level = MANDATORY) + @Probe(name = "backupTimeouts", level = MANDATORY) private final SwCounter backupTimeoutsCount = newSwCounter(); - @Probe(name = "invocations.normalTimeouts", level = MANDATORY) + @Probe(name = "normalTimeouts", level = MANDATORY) private final SwCounter normalTimeoutsCount = newSwCounter(); public InvocationMonitor(InvocationRegistry invocationRegistry, ILogger logger, GroupProperties props, @@ -76,7 +76,7 @@ public class InvocationMonitor { this.slowInvocationThresholdMs = initSlowInvocationThresholdMs(props); this.monitorThread = new InvocationMonitorThread(hzThreadGroup); - metricsRegistry.scanAndRegister(this, "operation"); + metricsRegistry.scanAndRegister(this, "operation.invocations"); monitorThread.start(); }
Minor naming cleanup with probe names in invocationmonitor
hazelcast_hazelcast
train
463d9ecda872f9df9644920103fcbfa4b6aef06f
diff --git a/tornado/httputil.py b/tornado/httputil.py index <HASH>..<HASH> 100644 --- a/tornado/httputil.py +++ b/tornado/httputil.py @@ -320,7 +320,11 @@ def parse_body_arguments(content_type, body, arguments, files): with the parsed contents. """ if content_type.startswith("application/x-www-form-urlencoded"): - uri_arguments = parse_qs_bytes(native_str(body), keep_blank_values=True) + try: + uri_arguments = parse_qs_bytes(native_str(body), keep_blank_values=True) + except Exception as e: + gen_log.warning('Invalid x-www-form-urlencoded body: %s', e) + uri_arguments = {} for name, values in uri_arguments.items(): if values: arguments.setdefault(name, []).extend(values) diff --git a/tornado/test/httpserver_test.py b/tornado/test/httpserver_test.py index <HASH>..<HASH> 100644 --- a/tornado/test/httpserver_test.py +++ b/tornado/test/httpserver_test.py @@ -344,6 +344,21 @@ class HTTPServerTest(AsyncHTTPTestCase): self.assertEqual(200, response.code) self.assertEqual(json_decode(response.body), {}) + def test_malformed_body(self): + # parse_qs is pretty forgiving, but it will fail on python 3 + # if the data is not utf8. On python 2 parse_qs will work, + # but then the recursive_unicode call in EchoHandler will + # fail. + if str is bytes_type: + return + with ExpectLog(gen_log, 'Invalid x-www-form-urlencoded body'): + response = self.fetch( + '/echo', method="POST", + headers={'Content-Type': 'application/x-www-form-urlencoded'}, + body=b'\xe9') + self.assertEqual(200, response.code) + self.assertEqual(b'{}', response.body) + class HTTPServerRawTest(AsyncHTTPTestCase): def get_app(self):
Catch exceptions from parse_qs_bytes in POST bodies and log them. This is consistent with error handling for multipart/form-data. parse_qs is very liberal, but the conversion to unicode on python 3 may fail. This is most common for binary data sent from clients where x-www-form-urlencoded is the default, which is not actually intended to be interpreted as arguments. Closes #<I>.
tornadoweb_tornado
train
d6a99617982e923974a67aa5258eea0011e7640a
diff --git a/src/Malenki/Math/Stats/ParametricTest/TTest/OneSample.php b/src/Malenki/Math/Stats/ParametricTest/TTest/OneSample.php index <HASH>..<HASH> 100644 --- a/src/Malenki/Math/Stats/ParametricTest/TTest/OneSample.php +++ b/src/Malenki/Math/Stats/ParametricTest/TTest/OneSample.php @@ -33,6 +33,13 @@ class OneSample implements \Countable protected $float_sigma_pop = null; protected $float_t = null; + public function __get($name) + { + if(in_array($name, array('count', 'clear', 'sigma2', 't'))){ + return $this->$name(); + } + } + public function __construct($mean = null) { if(!is_null($mean)){ diff --git a/tests/Stats/ParametricTest/TTest/OneSampleTest.php b/tests/Stats/ParametricTest/TTest/OneSampleTest.php index <HASH>..<HASH> 100644 --- a/tests/Stats/ParametricTest/TTest/OneSampleTest.php +++ b/tests/Stats/ParametricTest/TTest/OneSampleTest.php @@ -65,6 +65,22 @@ class OneSampleTest extends PHPUnit_Framework_TestCase $t->populationMean(null); } + public function testGettingCountShouldSuccess() + { + $t = new OneSample(); + $t + ->populationMean(4.7) + ->set( + array( + 5, 5.5, 4.5, 5, 5, 6, 5, 5, 4.5, 5, 5, 4.5, 4.5, 5.5, 4, 5, 5, 5.5, 4.5, 5.5, 5, 5.5 + ) + ); + + $this->assertEquals(22, $t->count()); + $this->assertEquals(22, $t->count); + $this->assertCount(22, $t); + } + public function testGettingSigma2ShouldSuccess() { $t = new OneSample(); @@ -77,6 +93,7 @@ class OneSampleTest extends PHPUnit_Framework_TestCase ); $this->assertEquals(0.214, round($t->sigma2(), 3)); + $this->assertEquals(0.214, round($t->sigma2, 3)); } public function testGettingStdDevShouldSuccess() @@ -105,5 +122,6 @@ class OneSampleTest extends PHPUnit_Framework_TestCase ); $this->assertEquals(3.04, round($t->t(), 2)); + $this->assertEquals(3.04, round($t->t, 2)); } }
T-Test One Sample: added some magic getters
malenkiki_math
train
fd3e5092f1ec20f08abecef7028b0899587061d5
diff --git a/test/BootstrapMixinSpec.js b/test/BootstrapMixinSpec.js index <HASH>..<HASH> 100644 --- a/test/BootstrapMixinSpec.js +++ b/test/BootstrapMixinSpec.js @@ -85,15 +85,6 @@ describe('BootstrapMixin', function () { }); }); - it('should return "btn-title"', function () { - let instance = ReactTestUtils.renderIntoDocument( - <Component bsClass='button'> - content - </Component> - ); - assert.equal(instance.prefixClass('title'), 'btn-title'); - }); - describe('Custom styles', function () { it('should validate OK custom styles added via "addStyle()"', function () {
Rename and move out test for 'prefixClass()' method
react-bootstrap_react-bootstrap
train
3fe2c73dd04f7769a9d9673236cb94b79ac45659
diff --git a/modules/caddyhttp/matchers.go b/modules/caddyhttp/matchers.go index <HASH>..<HASH> 100644 --- a/modules/caddyhttp/matchers.go +++ b/modules/caddyhttp/matchers.go @@ -325,6 +325,11 @@ func (m MatchPath) Match(r *http.Request) bool { lowerPath := strings.ToLower(unescapedPath) + // Clean the path, merges doubled slashes, etc. + // This ensures maliciously crafted requests can't bypass + // the path matcher. See #4407 + lowerPath = path.Clean(lowerPath) + // see #2917; Windows ignores trailing dots and spaces // when accessing files (sigh), potentially causing a // security risk (cry) if PHP files end up being served @@ -332,11 +337,6 @@ func (m MatchPath) Match(r *http.Request) bool { // being matched by *.php to be treated as PHP scripts lowerPath = strings.TrimRight(lowerPath, ". ") - // Clean the path, merges doubled slashes, etc. - // This ensures maliciously crafted requests can't bypass - // the path matcher. See #4407 - lowerPath = path.Clean(lowerPath) - // Cleaning may remove the trailing slash, but we want to keep it if lowerPath != "/" && strings.HasSuffix(r.URL.Path, "/") { lowerPath = lowerPath + "/"
caddyhttp: Fix `MatchPath` sanitizing (#<I>) This is a followup to #<I>, in response to a report on the forums: <URL>
mholt_caddy
train
e7ca598797ec10553946030e5f1574430c3471fd
diff --git a/beets/mediafile.py b/beets/mediafile.py index <HASH>..<HASH> 100644 --- a/beets/mediafile.py +++ b/beets/mediafile.py @@ -326,7 +326,11 @@ class Image(object): self.data = data self.desc = desc if isinstance(type, int): - type = list(ImageType)[type] + try: + type = list(ImageType)[type] + except IndexError: + log.warn("ignoring unknown image type index {}", type) + type = ImageType.other self.type = type @property
Fixed IndexError on reading embedded cover art with invalid cover type Original: beetbox/beets@b<I>
beetbox_mediafile
train
0cf8bb435fc2e01905a5f3002f779ab68cdae25a
diff --git a/src/Psalm/Visitor/DependencyFinderVisitor.php b/src/Psalm/Visitor/DependencyFinderVisitor.php index <HASH>..<HASH> 100644 --- a/src/Psalm/Visitor/DependencyFinderVisitor.php +++ b/src/Psalm/Visitor/DependencyFinderVisitor.php @@ -153,7 +153,6 @@ class DependencyFinderVisitor extends PhpParser\NodeVisitorAbstract implements P } $fq_classlike_name = ClassChecker::getAnonymousClassName($node, $this->file_path); - $fq_classlike_name_lc = strtolower($fq_classlike_name); } else { $fq_classlike_name = ($this->aliases->namespace ? $this->aliases->namespace . '\\' : '') . $node->name; $fq_classlike_name_lc = strtolower($fq_classlike_name); @@ -931,7 +930,6 @@ class DependencyFinderVisitor extends PhpParser\NodeVisitorAbstract implements P $this->improveParamsFromDocblock( $storage, $docblock_info->params, - $template_types, $stmt ); } @@ -1017,7 +1015,6 @@ class DependencyFinderVisitor extends PhpParser\NodeVisitorAbstract implements P /** * @param array<int, array{type:string,name:string,line_number:int}> $docblock_params * @param FunctionLikeStorage $storage - * @param array<string, string>|null $template_types * @param PhpParser\Node\FunctionLike $function * * @return void @@ -1025,7 +1022,6 @@ class DependencyFinderVisitor extends PhpParser\NodeVisitorAbstract implements P private function improveParamsFromDocblock( FunctionLikeStorage $storage, array $docblock_params, - $template_types, PhpParser\Node\FunctionLike $function ) { $base = $this->fq_classlike_names
Remove more unused code found by Psalm
vimeo_psalm
train
887860c307c11171900d684c3870b7159559c6d6
diff --git a/src/FelixOnline/Core/CliGlue.php b/src/FelixOnline/Core/CliGlue.php index <HASH>..<HASH> 100644 --- a/src/FelixOnline/Core/CliGlue.php +++ b/src/FelixOnline/Core/CliGlue.php @@ -83,7 +83,7 @@ class CliGlue implements GlueInterface { $runHelp = false; if($request['CountArguments'] == 0) { - $this->climate->error('This command does not exist (try running help).'); + $this->climate->error('Please specify a command. (try running help.)'); return 65; // EX_DATAERR per BSD sysexits.h } @@ -100,17 +100,63 @@ class CliGlue implements GlueInterface { } else { if(!array_key_exists($method, $this->routes)) { // no routes msg - $this->climate->error('This command does not exist.'); + $this->climate->error('This command does not exist. (Try running help.)'); return 65; // EX_DATAERR per BSD sysexits.h } } if($runHelp) { - // help - $climate = $this->climate; - $climate->bold('CLI Command Reference'); - $climate->out('The following commands have been defined.'); - $climate->table($this->routes); + $app = App::getInstance(); + $appName = $app->getOption('app_name'); + $appVer = $app->getOption('app_version'); + + if($request['CountArguments'] == 1) { + // general help + $climate = $this->climate; + $climate->bold('CLI Command Reference - '.$appName.' '.$appVer); + $climate->out('The following commands have been defined.'); + $climate->nl(); + + if($app->getOption('production')) { + $routes = array(); + foreach($this->routes as $route) { + $routes[] = array( + 'Command' => $route['Command'], + 'Description' => $route['Description'] + ); + } + $climate->table($routes); + } else { + $climate->table($this->routes); + } + + $climate->nl(); + $climate->out('For usage information for a command, run <bold>help <command></bold>.'); + } else { + $helpMethod = $request['Arguments'][1]; + + if($helpMethod == 'help') { + $this->climate->description('Displays details on installed commands and their usage.'); + + $climate = $this->climate; + } else { + if(!array_key_exists($helpMethod, $this->routes)) { + // no routes msg + $this->climate->error('This command does not exist. (Try running help.)'); + return 65; // EX_DATAERR per BSD sysexits.h + } + + $this->climate->description($this->routes[$helpMethod]['Description']); + + $class = new $this->routes[$helpMethod]['Class']($this->climate); + $classMethod = $this->routes[$helpMethod]['Method']; + + // Special case of array(), true just sets up climate with parameters and returns + $climate = $class->$classMethod(array(), true); + } + + $climate->usage(); + } return 64; // EX_USAGE per BSD sysexits.h } @@ -121,7 +167,7 @@ class CliGlue implements GlueInterface { $response = $class->$classMethod($request['Arguments']); } catch(\Exception $e) { // last resort - $this->climate->error('Fatal error: '.$e->getMessage()); + $this->climate->error($e->getMessage().' (Try <bold>help '.$method.'</bold> for usage.)'); $response = 70; // EX_SOFTWARE per BSD sysexits.h }
Tweak help and add command usage
FelixOnline_BaseApp
train
ac110853fc0f9dec59a627b59aff959eac9c8e38
diff --git a/spec/fake_app/rails_app.rb b/spec/fake_app/rails_app.rb index <HASH>..<HASH> 100644 --- a/spec/fake_app/rails_app.rb +++ b/spec/fake_app/rails_app.rb @@ -26,6 +26,7 @@ class CustomException < StandardError; end Rambulance.setup do |config| config.rescue_responses = { + 'TypeError' => :bad_request, 'CustomException' => :not_found } end
Fix for Rails <I> I probably should drop support for Rails <I>...
yuki24_rambulance
train
803c26f9c70b4081f2fb8830d0d2ba6c586d35a6
diff --git a/src/view/ThemeManager.js b/src/view/ThemeManager.js index <HASH>..<HASH> 100644 --- a/src/view/ThemeManager.js +++ b/src/view/ThemeManager.js @@ -53,7 +53,7 @@ define(function (require, exports, module) { if(cm) { ThemeView.setDocumentMode(cm); - if(force === false) { + if(!force) { ThemeView.updateThemes(cm); refreshEditor(cm); } @@ -250,7 +250,7 @@ define(function (require, exports, module) { $(EditorManager).on("activeEditorChange", function() { - refresh(true); + refresh(); });
Fixed issue with unnecessary reload of themes when opening a new document
adobe_brackets
train
a0d882d3607dcbf72f665ba9b7770571b302793e
diff --git a/springy.js b/springy.js index <HASH>..<HASH> 100644 --- a/springy.js +++ b/springy.js @@ -367,7 +367,7 @@ Layout.requestAnimationFrame = __bind(window.requestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element) { - window.setTimeout(callback, interval); + window.setTimeout(callback, 10); }, window);
Fallback requestAnimationFrame has a <I>ms setTimeout
dhotson_springy
train
4ec569a6588e24038ac5fb5d234c6ccff1c911d5
diff --git a/lib/middleware/services/index.js b/lib/middleware/services/index.js index <HASH>..<HASH> 100644 --- a/lib/middleware/services/index.js +++ b/lib/middleware/services/index.js @@ -12,10 +12,10 @@ module.exports = function (options) { var servicesList = options.services || []; var serviceRoutePrefix = options.prefix || '__'; + var config = options.config || {}; return function (req, res, next) { - if (!req.config) return next(); // TODO: don't really need this?? - + // var tracker = options.tracker; @@ -51,7 +51,7 @@ module.exports = function (options) { req.service = { name: name, - config: req.config[name], + config: config[name], path: prefixless(req.url) }; diff --git a/lib/stacker.js b/lib/stacker.js index <HASH>..<HASH> 100644 --- a/lib/stacker.js +++ b/lib/stacker.js @@ -22,6 +22,7 @@ module.exports = function stacker (app, options) { return function (req, res, next) { // TODO: convert configure middleware to just be a method here + // TODO: only run these middlewares if "req.config" exists var pack = stacked(); var config = req.config || {}; @@ -33,6 +34,7 @@ module.exports = function stacker (app, options) { pack.use(services({ services: app.services, prefix: app.servicesRoutePrefix, + config: req.config // tracker: settings.Tracker(config) })); diff --git a/test/middleware/services.js b/test/middleware/services.js index <HASH>..<HASH> 100644 --- a/test/middleware/services.js +++ b/test/middleware/services.js @@ -169,7 +169,11 @@ describe('services middleware', function () { service1: service1, service2: service2 }, - prefix: '__' + prefix: '__', + config: { + 'service1': 'service1', + 'service2': 'service2' + } })); request(app)
refactor: pass in app config for services. Ref #<I>
firebase_superstatic
train
9adf2148322547d36dd90045647122a4ea649661
diff --git a/python/mxnet/libinfo.py b/python/mxnet/libinfo.py index <HASH>..<HASH> 100644 --- a/python/mxnet/libinfo.py +++ b/python/mxnet/libinfo.py @@ -96,10 +96,18 @@ def find_include_path(): logging.warning("MXNET_INCLUDE_PATH '%s' doesn't exist", incl_from_env) curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) - incl_path = os.path.join(curr_path, '../../include/') - if not os.path.isdir(incl_path): - raise RuntimeError('Cannot find the MXNet include path.\n') - return incl_path + # include path in pip package + pip_incl_path = os.path.join(curr_path, 'include/') + if os.path.isdir(pip_incl_path): + return pip_incl_path + else: + # include path if build from source + src_incl_path = os.path.join(curr_path, '../../include/') + if os.path.isdir(src_incl_path): + return src_incl_path + else: + raise RuntimeError('Cannot find the MXNet include path in either ' + pip_incl_path + + ' or ' + src_incl_path + '\n') # current version
Get the correct include path in pip package (#<I>) * add find_include_path API * address reviewer comment * change return type from list to string * add unit test * address reviewer comment * address reviewer comment * address reviewer comment * address reviewer comment * fix include path problem in pip package * add comment * fix lint error * address reviewer comment * address reviewer comment
apache_incubator-mxnet
train
fafb2135a038bf8e21be72ab113dadfe7adaec9b
diff --git a/glue/ligolw/ilwd.py b/glue/ligolw/ilwd.py index <HASH>..<HASH> 100644 --- a/glue/ligolw/ilwd.py +++ b/glue/ligolw/ilwd.py @@ -218,6 +218,30 @@ def get_ilwdchar_class(tbl_name, col_name): table_name, column_name = key index_offset = len("%s:%s:" % key) + def __conform__(self, protocol): + # The presence of this method allows + # ilwdchar sub-classes to be inserted + # directly into SQLite databases as + # strings. See + # + # http://www.python.org/dev/peps/pep-0246 + # + # for more information. + # + # NOTE: GvR has rejected that PEP, so this + # mechanism is obsolete. Be prepared to + # fix this, replacing it with whatever + # replaces it. + # + # NOTE: The return should be inside an "if + # protocol is sqlite3.PrepareProtocol:" + # conditional, but that would require + # importing sqlite3 which would break this + # module on FC4 boxes, and I'm not going to + # spend time fixing something that's + # obsolete anyway. + return unicode(self) + ilwdchar_class_cache[key] = cached_ilwdchar_class return cached_ilwdchar_class
Fix PR<I>: register_to_xmldoc raises error when trying to insert a process. This fixes it by teaching ilwdchar sub-classes how to adapt themselves to an sqlite3-compatible format following PEP-<I>. That PEP has been rejected, so this is an interim solution only.
gwastro_pycbc-glue
train
870b045fedbe8eb8964ecfa17ba1575db6780caf
diff --git a/src/python/pants/backend/python/goals/pytest_runner.py b/src/python/pants/backend/python/goals/pytest_runner.py index <HASH>..<HASH> 100644 --- a/src/python/pants/backend/python/goals/pytest_runner.py +++ b/src/python/pants/backend/python/goals/pytest_runner.py @@ -44,8 +44,10 @@ from pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest from pants.engine.addresses import UnparsedAddressInputs from pants.engine.fs import ( AddPrefix, + CreateDigest, Digest, DigestSubset, + Directory, GlobMatchErrorBehavior, MergeDigests, PathGlobs, @@ -157,6 +159,10 @@ async def setup_pytest_for_target( ), ) + extra_output_directory_digest_request = Get( + Digest, CreateDigest([Directory(_EXTRA_OUTPUT_DIR)]) + ) + prepared_sources_request = Get( PythonSourceFiles, PythonSourceFilesRequest(all_targets, include_files=True) ) @@ -191,12 +197,14 @@ async def setup_pytest_for_target( prepared_sources, field_set_source_files, config_digest, + extra_output_directory_digest, ) = await MultiGet( pytest_pex_request, requirements_pex_request, prepared_sources_request, field_set_source_files_request, config_digest_request, + extra_output_directory_digest_request, ) pytest_runner_pex = await Get( @@ -217,6 +225,7 @@ async def setup_pytest_for_target( coverage_config.digest, prepared_sources.source_files.snapshot.digest, config_digest, + extra_output_directory_digest, *(binary.digest for binary in assets), ) ),
Ensure the extra-output directory exists. (#<I>) Since we ask the directory to be collected as an output we need to ensure its there, even if empty. Follow-up to #<I> to fix remote caching.
pantsbuild_pants
train
1458faf431c3b132e6f3ed6b761ddbcc5d8981e0
diff --git a/org/postgresql/jdbc2/EscapedFunctions.java b/org/postgresql/jdbc2/EscapedFunctions.java index <HASH>..<HASH> 100644 --- a/org/postgresql/jdbc2/EscapedFunctions.java +++ b/org/postgresql/jdbc2/EscapedFunctions.java @@ -3,7 +3,7 @@ * Copyright (c) 2004-2005, PostgreSQL Global Development Group * * IDENTIFICATION -* $PostgreSQL: pgjdbc/org/postgresql/jdbc2/EscapedFunctions.java,v 1.3 2005/01/14 01:20:20 oliver Exp $ +* $PostgreSQL: pgjdbc/org/postgresql/jdbc2/EscapedFunctions.java,v 1.4 2005/01/18 21:33:17 oliver Exp $ * *------------------------------------------------------------------------- */ @@ -67,11 +67,12 @@ public class EscapedFunctions { public final static String SPACE="space"; public final static String SUBSTRING="substring"; public final static String UCASE="ucase"; - // soundex and difference are implemented on the server side by + // soundex is implemented on the server side by // the contrib/fuzzystrmatch module. We provide a translation // for this in the driver, but since we don't want to bother with run - // time detection of this module's installation we don't report these - // methods as supported in DatabaseMetaData. + // time detection of this module's installation we don't report this + // method as supported in DatabaseMetaData. + // difference is currently unsupported entirely. // date time function names public final static String CURDATE="curdate"; @@ -350,19 +351,6 @@ public class EscapedFunctions { return buf.append(')').toString(); } - /** difference to levenshtein translation */ - public static String sqldifference(List parsedArgs) throws SQLException{ - StringBuffer buf = new StringBuffer(); - buf.append("levenshtein("); - if (parsedArgs.size()!=2){ - throw new PSQLException(GT.tr("{0} function takes two and only two arguments.","difference"), - PSQLState.SYNTAX_ERROR); - } - buf.append(parsedArgs.get(0)).append(",").append(parsedArgs.get(1)); - return buf.append(")").toString(); - } - - /** curdate to current_date translation */ public static String sqlcurdate(List parsedArgs) throws SQLException{ if (parsedArgs.size()!=0){
Don't map the escaped difference function to levenshtein because that's not the same thing.
pgjdbc_pgjdbc
train
3965acf174cadceef0b0ca2cd2662282748b45f3
diff --git a/eth/tools/fixtures/normalization.py b/eth/tools/fixtures/normalization.py index <HASH>..<HASH> 100644 --- a/eth/tools/fixtures/normalization.py +++ b/eth/tools/fixtures/normalization.py @@ -24,6 +24,7 @@ from eth_utils import ( is_hex, is_integer, is_string, + is_text, to_bytes, to_canonical_address, to_dict, @@ -66,10 +67,10 @@ def normalize_int(value): def normalize_bytes(value): - if is_hex(value) or len(value) == 0: - return decode_hex(value) - elif is_bytes(value): + if is_bytes(value): return value + elif is_text(value) and is_hex(value): + return decode_hex(value) else: raise TypeError("Value must be either a string or bytes object")
Fix Minor Bugs in Tools (#<I>) * Fix Minor Bugs in Tools * Fix Minor Bugs in Tools * Fix Minor Bugs in Tools
ethereum_py-evm
train
383d9ebbe9f42cef408879d9bab3ab633f8495be
diff --git a/tests/ProxyManagerTest/Functional/BaseLazyLoadingPerformanceTest.php b/tests/ProxyManagerTest/Functional/BaseLazyLoadingPerformanceTest.php index <HASH>..<HASH> 100644 --- a/tests/ProxyManagerTest/Functional/BaseLazyLoadingPerformanceTest.php +++ b/tests/ProxyManagerTest/Functional/BaseLazyLoadingPerformanceTest.php @@ -151,6 +151,7 @@ abstract class BaseLazyLoadingPerformanceTest extends BasePerformanceTest $this->startCapturing(); foreach ($instances as $instance) { + /** @noinspection PhpExpressionResultUnusedInspection */ isset($instance->$property); } @@ -160,6 +161,7 @@ abstract class BaseLazyLoadingPerformanceTest extends BasePerformanceTest $this->startCapturing(); foreach ($proxies as $proxy) { + /** @noinspection PhpExpressionResultUnusedInspection */ isset($proxy->$property); }
Suppressing performance test unused expressions
Ocramius_ProxyManager
train
3c6baf067535b716ea2b9f1bf83dfb75847b5290
diff --git a/src/extensibility/Package.js b/src/extensibility/Package.js index <HASH>..<HASH> 100644 --- a/src/extensibility/Package.js +++ b/src/extensibility/Package.js @@ -434,7 +434,7 @@ define(function (require, exports, module) { */ function installUpdate(path, nameHint) { return install(path, nameHint, true).always(function () { - brackets.fs.unlink(path); + brackets.fs.unlink(path, function () { }); }); }
Minor fix so that installed zip files are deleted.
adobe_brackets
train
74a6171b53b1029279597ebae27df6780cff5cae
diff --git a/simulation.py b/simulation.py index <HASH>..<HASH> 100644 --- a/simulation.py +++ b/simulation.py @@ -6,6 +6,7 @@ import toolz _TABLES = {} _COLUMNS = {} +_MODELS = {} def clear_sim(): @@ -15,6 +16,7 @@ def clear_sim(): """ _TABLES.clear() _COLUMNS.clear() + _MODELS.clear() class _DataFrameWrapper(object): @@ -71,6 +73,23 @@ class _DataFrameWrapper(object): return df + def update_col(self, column_name, series): + """ + Add or replace a column in the underlying DataFrame. + + Parameters + ---------- + column_name : str + Column to add or replace. + series : pandas.Series or sequence + Column data. + + """ + self._frame[column_name] = series + + def __setitem__(self, key, value): + return self.update_col(key, value) + class _TableFuncWrapper(object): """ @@ -170,6 +189,26 @@ class _SeriesWrapper(object): return self._column +class _ModelFuncWrapper(object): + """ + Wrap a model function for dependency injection. + + Parameters + ---------- + model_name : str + func : callable + + """ + def __init__(self, model_name, func): + self.name = model_name + self._func = func + self._arg_list = inspect.getargspec(func).args + + def __call__(self): + kwargs = {t: get_table(t) for t in self._arg_list} + return self._func(**kwargs) + + def add_table(table_name, table): """ Register a table with the simulation. @@ -257,7 +296,7 @@ def add_column(table_name, column_name, column): column = \ _ColumnFuncWrapper(table_name, column_name, column) else: - raise TypeError('Only Series or calleable allowed for column.') + raise TypeError('Only Series or callable allowed for column.') _COLUMNS[(table_name, column_name)] = column @@ -310,3 +349,46 @@ def _columns_for_table(table_name): return {cname: col for (tname, cname), col in _COLUMNS.items() if tname == table_name} + + +def add_model(model_name, func): + """ + Add a model function to the simulation. + + Parameters + ---------- + model_name : str + func : callable + + """ + if isinstance(func, Callable): + _MODELS[model_name] = _ModelFuncWrapper(model_name, func) + else: + raise TypeError('func must be a callable') + + +def model(model_name): + """ + Decorator version of `add_model`, used to decorate a function that + will require injection of tables and that can be run by the + `run` function. + + """ + def decorator(func): + add_model(model_name, func) + return func + return decorator + + +def get_model(model_name): + """ + Get a wrapped model by name. + + Parameters + ---------- + + """ + if model_name in _MODELS: + return _MODELS[model_name] + else: + raise KeyError('no model named {}'.format(model_name)) diff --git a/tests/test_simulation.py b/tests/test_simulation.py index <HASH>..<HASH> 100644 --- a/tests/test_simulation.py +++ b/tests/test_simulation.py @@ -107,3 +107,23 @@ def test_columns_and_tables(df, clear_sim): {'b': [2, 2.5, 3], 'd': [4., 5., 6.]}, index=['x', 'y', 'z'])) + + +def test_models(df, clear_sim): + sim.add_table('test_table', df) + + @sim.model('test_model') + def test_model(test_table): + tt = test_table.to_frame() + test_table['a'] = tt['a'] + tt['b'] + + model = sim.get_model('test_model') + model() + + table = sim.get_table('test_table') + pdt.assert_frame_equal( + table.to_frame(), + pd.DataFrame( + {'a': [5, 7, 9], + 'b': [4, 5, 6]}, + index=['x', 'y', 'z']))
Add decorator and function or adding models that have tables injected.
UDST_orca
train
174b94eda551818a7b5dcfb237289836b99bad39
diff --git a/src/services/campaigns/enum/SmartCampaignSearchStrategyTypeEnum.php b/src/services/campaigns/enum/SmartCampaignSearchStrategyTypeEnum.php index <HASH>..<HASH> 100644 --- a/src/services/campaigns/enum/SmartCampaignSearchStrategyTypeEnum.php +++ b/src/services/campaigns/enum/SmartCampaignSearchStrategyTypeEnum.php @@ -6,12 +6,40 @@ use directapi\components\Enum; class SmartCampaignSearchStrategyTypeEnum extends Enum { - public const AVERAGE_CPC_PER_CAMP = 'AVERAGE_CPC_PER_CAMP'; + /** + * «Оптимизация количества конверсий», CPC или CPA на всю кампанию + */ + public const AVERAGE_CPA_PER_CAMPAIGN = 'AVERAGE_CPA_PER_CAMPAIGN'; + + /** + * «Оптимизация количества конверсий», CPC или CPA на каждый фильтр + */ public const AVERAGE_CPC_PER_FILTER = 'AVERAGE_CPC_PER_FILTER'; - public const AVERAGE_CPA_PER_CAMP = 'AVERAGE_CPA_PER_CAMP'; + + /** + * «Оптимизация количества кликов», CPC на всю кампанию + */ + public const AVERAGE_CPC_PER_CAMPAIGN = 'AVERAGE_CPC_PER_CAMPAIGN'; + + /** + * «Оптимизация количества кликов», CPC на каждый фильтр + */ public const AVERAGE_CPA_PER_FILTER = 'AVERAGE_CPA_PER_FILTER'; + + /** + * «Оптимизация рентабельности» + */ public const AVERAGE_ROI = 'AVERAGE_ROI'; - public const PAY_FOR_CONVERSION = 'PAY_FOR_CONVERSION'; + + /** + * «Оптимизация количества конверсий», оплата за конверсии (для кампаний с типом «Смарт-баннеры») + */ + public const PAY_FOR_CONVERSION_PER_CAMPAIGN = 'PAY_FOR_CONVERSION_PER_CAMPAIGN'; + + /** + * Показы отключены + */ public const SERVING_OFF = 'SERVING_OFF'; + public const UNKNOWN = 'UNKNOWN'; }
#<I> fix smart campaign strategy types
sitkoru_yandex-direct-api
train
0af8046b12f104d481818983cb75d3ae909f3c0d
diff --git a/src/js/pignose.calendar.js b/src/js/pignose.calendar.js index <HASH>..<HASH> 100644 --- a/src/js/pignose.calendar.js +++ b/src/js/pignose.calendar.js @@ -452,7 +452,7 @@ var ComponentPreference = { var $this = $(this); if($this.hasClass(_calendarButtonClass + '-apply')) { $super.trigger('apply.' + ComponentName, local); - var value = '' + var value = ''; if(_this.settings.toggle === true) { value = local.storage.activeDates.join(', '); } else if(_this.settings.multiple === true) { @@ -703,7 +703,7 @@ var ComponentPreference = { var lastDate = DateManager.Convert(local.dateManager.year, local.dateManager.month, local.dateManager.lastDay); var lastWeekday = lastDate.weekday(); - for(var i=lastWeekday+1;$unitList.length <= 7 * 5;i++) { + for(var i=lastWeekday+1;$unitList.length < 7 * 5;i++) { var $unit = $(Helper.Format('<div class="{0} {0}-{1}"></div>', Helper.GetSubClass('Unit'), languagePack.weeks.en[i % 7].toLowerCase())); $unitList.push($unit); }
Fix plus one bug on generation of empty unit-cell at the end of month at line <I>. Add missing semicolon at line <I>
KennethanCeyer_pg-calendar
train
8078eb51aa9c0b1fbf2d726199b2d8ffdfbc25a9
diff --git a/VersionInfo.py b/VersionInfo.py index <HASH>..<HASH> 100644 --- a/VersionInfo.py +++ b/VersionInfo.py @@ -5,5 +5,5 @@ ReferencePylonVersion = { # which is not equal to the version on the outer tar.gz "Linux": "6.1.0", "Linux_x86_64": "6.1.1", - "Darwin": "5.1.1" + "Darwin": "6.1.2" }
Update the official upstream version for macos This prevents the additional +pylonX.Y.Z addition on the python package
basler_pypylon
train
20312202a20c0fdc226d0baa7120ac193b3f0518
diff --git a/lib/Ouzo/Error.php b/lib/Ouzo/Error.php index <HASH>..<HASH> 100644 --- a/lib/Ouzo/Error.php +++ b/lib/Ouzo/Error.php @@ -16,7 +16,9 @@ class Error private static function _clearOutputBuffers() { while (ob_get_level()) { - ob_end_clean(); + if (!ob_end_clean()){ + break; + } } }
Fix to avoid infinite loop when ob_end_clean() failed.
letsdrink_ouzo
train
343de8e79f8d3c792fad2d96cb3c083f938f3547
diff --git a/tests/performance.py b/tests/performance.py index <HASH>..<HASH> 100644 --- a/tests/performance.py +++ b/tests/performance.py @@ -57,6 +57,11 @@ serializers["serpent"] = (serpent.dumps, serpent.loads) import marshal serializers["marshal"] = (marshal.dumps, marshal.loads) try: + import msgpack + serializers["msgpack"] = (lambda d: msgpack.packb(d, use_bin_type=True), lambda d: msgpack.unpackb(d, encoding="utf-8")) +except ImportError: + pass +try: import xmlrpclib as xmlrpc except ImportError: import xmlrpc.client as xmlrpc @@ -80,7 +85,6 @@ def run(): results = {} number = 10 repeat = 3 - serializers = {"serpent": (serpent.dumps, serpent.loads)} # XXX for ser in serializers: print("serializer:", ser) results[ser] = {"sizes": {}, "ser-times": {}, "deser-times": {}}
msgpack added to performance test
irmen_Serpent
train