hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
b0b4c046afcc62a1e6946cce7efbdf8f015b8f96 | diff --git a/spyder/plugins/lspmanager.py b/spyder/plugins/lspmanager.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/lspmanager.py
+++ b/spyder/plugins/lspmanager.py
@@ -716,6 +716,10 @@ class LSPManager(SpyderPluginWidget):
@Slot()
def reinit_all_lsp_clients(self):
+ """
+ Sends a new initialize message to each LSP server when the project
+ path has changed so they can update the respective server root paths.
+ """
for language_client in self.clients.values():
if language_client['status'] == self.RUNNING:
folder = self.get_root_path() | forgot to include lspmanager in commit | spyder-ide_spyder | train |
d25dea6c62e7774ec3e956cb4aea46f06ec111c5 | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -38,6 +38,13 @@ function defaultOptions() {
testTimeout: 300 * 1000,
// Whether the browser should be closed after the tests run.
persistent: false,
+ // Extra capabilities to pass to wd when building a client.
+ //
+ // Selenium: https://code.google.com/p/selenium/wiki/DesiredCapabilities
+ // Sauce: https://docs.saucelabs.com/reference/test-configuration/
+ browserOptions: {
+ 'idle-timeout': 10,
+ },
// Sauce Labs configuration.
sauce: {
username: undefined,
@@ -233,7 +240,7 @@ function startTestServer(options, emitter, done) {
options._seleniumPort = results.selenium;
options._httpPort = results.http.port;
if (results.sauceTunnel) {
- options._sauceTunnelId = results.sauceTunnel;
+ options.browserOptions['tunnel-identifier'] = results.sauceTunnel;
}
var runners = runBrowsers(options, emitter, done);
@@ -263,8 +270,8 @@ function runBrowsers(options, emitter, done) {
var failed = false;
var numDone = 0;
return options.browsers.map(function(browser, id) {
+ _.defaults(browser, options.browserOptions);
browser.id = id;
- browser['tunnel-identifier'] = options._sauceTunnelId;
return new BrowserRunner(emitter, isLocal(browser), browser, options, function(error) {
emitter.emit('log:debug', browser, 'BrowserRunner complete');
if (error) {
diff --git a/lib/browserrunner.js b/lib/browserrunner.js
index <HASH>..<HASH> 100644
--- a/lib/browserrunner.js
+++ b/lib/browserrunner.js
@@ -23,9 +23,15 @@ function BrowserRunner(emitter, local, def, options, doneCallback) {
this.browser = wd.remote('ondemand.saucelabs.com', 80, username, accessKey);
}
+ this.browser.on('command', function(method, context) {
+ emitter.emit('log:debug', def, chalk.cyan(method), context);
+ });
this.browser.on('http', function(method, path, data) {
emitter.emit('log:debug', def, chalk.magenta(method), chalk.cyan(path), data);
});
+ this.browser.on('connection', function(code, message, error) {
+ emitter.emit('log:warn', def, 'Error code ' + code + ':', message, error);
+ });
// Initialize the browser, then start tests
this.browser.init(def, function(error, session, result) { | Lower idle-timeout to speed up testing this; and more logging | Polymer_web-component-tester | train |
98719688c14197cfb6c8d3e158c8d7ae46b2e486 | diff --git a/app/models/manifestation.rb b/app/models/manifestation.rb
index <HASH>..<HASH> 100644
--- a/app/models/manifestation.rb
+++ b/app/models/manifestation.rb
@@ -26,6 +26,9 @@ class Manifestation < ActiveRecord::Base
has_one :doi_record
has_one :periodical_and_manifestation, dependent: :destroy
has_one :periodical, through: :periodical_and_manifestation
+ accepts_nested_attributes_for :creates, allow_destroy: true, reject_if: :all_blank
+ accepts_nested_attributes_for :realizes, allow_destroy: true, reject_if: :all_blank
+ accepts_nested_attributes_for :produces, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :creators, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :contributors, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :publishers, allow_destroy: true, reject_if: :all_blank
diff --git a/db/migrate/20190312033839_create_periodical_and_manifestations.rb b/db/migrate/20190312033839_create_periodical_and_manifestations.rb
index <HASH>..<HASH> 100644
--- a/db/migrate/20190312033839_create_periodical_and_manifestations.rb
+++ b/db/migrate/20190312033839_create_periodical_and_manifestations.rb
@@ -3,7 +3,7 @@ class CreatePeriodicalAndManifestations < ActiveRecord::Migration[5.2]
create_table :periodical_and_manifestations do |t|
t.references :periodical, foreign_key: true, type: :uuid, null: false
t.references :manifestation, foreign_key: true, type: :uuid, null: false
- t.boolean :periodical_master, default: false, null: false
+ t.boolean :periodical_master, default: false, null: false, index: {where: (periodical_master: true), unique: true}
t.timestamps
end | add full_name_translations to Create, Realize and Produce | next-l_enju_biblio | train |
a43b86d03f0cf058396ab74035a1fa9937a090fd | diff --git a/views/form-styling.js b/views/form-styling.js
index <HASH>..<HASH> 100644
--- a/views/form-styling.js
+++ b/views/form-styling.js
@@ -3,7 +3,6 @@ var app = require('../ridge');
var View = require('../view').extend();
_.extend(View.prototype, {
-//_.extend(View.prototype, require('../mixins/observe'), {
tagName: 'form',
events: {
@@ -19,6 +18,10 @@ _.extend(View.prototype, {
initialize: function(opts) {
this.listenTo(this.model, 'validated', this.setValid);
this.listenTo(this.model, 'reset', this.reset);
+
+ // TODO maybe turn this off, and use this.el.reset() in 'reset' method to
+ // ensure form is properly reset.
+ this.$el.on('reset', this.reset.bind(this));
},
attach: function() {
@@ -46,7 +49,10 @@ _.extend(View.prototype, {
reset: function() {
this.$('[name], [data-name], .container').removeClass('valid invalid touched validated filled empty');
this.$('label.error').remove();
- this.attach();
+
+ // needed when reset is called by 'form' reset event,
+ // otherwise form values are not cleared before reattached
+ setTimeout(this.attach.bind(this));
},
onHover: function() {
@@ -59,7 +65,7 @@ _.extend(View.prototype, {
onChange: function(e) {
var target = e.currentTarget,
- value = target.nodeName === 'DIV' ? target.textContent.trim() : target.value;
+ value = target.nodeName === 'DIV' ? target.textContent.trim() : /radio|checkbox/.test(target.type) ? target.checked : target.value;
$(target).closest('div.container', this.el).toggleClass('empty', !value).toggleClass('filled', !!value);
}, | Listen to reset event on form element, attach async inside reset and check if radio or checkbox inside onChange. | thecodebureau_ridge | train |
fd9c574f894060248642d455fac7fe2a56771f1a | diff --git a/examples/example-rest.rb b/examples/example-rest.rb
index <HASH>..<HASH> 100644
--- a/examples/example-rest.rb
+++ b/examples/example-rest.rb
@@ -70,5 +70,5 @@ t = {
'To' => '415-555-1212',
'Body' => "Hello, world. This is a text from Twilio using Ruby!"
}
-resp = account.request("/#{API_VERSION}/Accounts/#{Account_SID}/SMS/Messages",
- "POST", t)
\ No newline at end of file
+resp = account.request("/#{API_VERSION}/Accounts/#{ACCOUNT_SID}/SMS/Messages",
+ "POST", t) | modify rest example so that it actually works | twilio_twilio-ruby | train |
b8c241d5ec852a92b31fc73ad7c7bb5860ef67e6 | diff --git a/example/load.py b/example/load.py
index <HASH>..<HASH> 100644
--- a/example/load.py
+++ b/example/load.py
@@ -183,9 +183,5 @@ if __name__ == '__main__':
initial_commit = es.get(index='git', doc_type='doc', id='20fbba1230cabbc0f4644f917c6c2be52b8a63e8')
print('%s: %s' % (initial_commit['_id'], initial_commit['_source']['committed_date']))
-
- # refresh to make the documents available for search
- es.indices.refresh(index='git')
-
# and now we can count the documents
print(es.count(index='git')['count'], 'documents in index') | remove extraneous refresh() in example/load.py (#<I>)
After Git repo is loaded to ES through bulk(), Line <I> performs an index refresh to make documents available for searching. The same operation is then repeated in Line <I>; remove this duplicate refresh. | elastic_elasticsearch-py | train |
b4e982b31826fba0387f9cc1daa9219d7a180fd0 | diff --git a/camera.js b/camera.js
index <HASH>..<HASH> 100644
--- a/camera.js
+++ b/camera.js
@@ -34,10 +34,10 @@ vglModule.camera = function() {
var m_right = vec3.fromValues(1.0, 0.0, 0.0);
/** @private */
- var m_near = 0.1;
+ var m_near = 1.0;
/** @private */
- var m_far = 10000.0;
+ var m_far = 1000.0;
/** @private */
var m_viewAspect = 1.0;
diff --git a/mapper.js b/mapper.js
index <HASH>..<HASH> 100644
--- a/mapper.js
+++ b/mapper.js
@@ -15,12 +15,24 @@ vglModule.mapper = function() {
}
vglModule.boundingObject.call(this);
+ /** @private */
var m_dirty = true;
+
+ /** @private */
var m_color = [ 1.0, 1.0, 1.0 ];
- var m_geomData = 0;
+
+ /** @private */
+ var m_geomData = null;
+
+ /** @private */
var m_buffers = [];
+
+ /** @private */
var m_bufferVertexAttributeMap = {};
+ /** @private */
+ var m_glCompileTimestamp = vglModule.timestamp();
+
/**
* Compute bounds of the data
*/
@@ -45,6 +57,8 @@ vglModule.mapper = function() {
m_color[0] = r;
m_color[1] = g;
m_color[2] = br;
+
+ this.modified();
};
/**
@@ -61,8 +75,7 @@ vglModule.mapper = function() {
if (m_geomData !== geom) {
m_geomData = geom;
- // TODO we need
- m_dirty = true;
+ this.modified();
}
};
@@ -70,7 +83,7 @@ vglModule.mapper = function() {
* Render the mapper
*/
this.render = function(renderState) {
- if (m_dirty) {
+ if (this.getMTime() > m_glCompileTimestamp.getMTime()) {
setupDrawObjects(renderState);
}
@@ -142,6 +155,8 @@ vglModule.mapper = function() {
.indices(), gl.STATIC_DRAW);
m_buffers[i++] = bufferId;
}
+
+ m_glCompileTimestamp.modified();
}
}
diff --git a/shader.js b/shader.js
index <HASH>..<HASH> 100644
--- a/shader.js
+++ b/shader.js
@@ -16,7 +16,7 @@ vglModule.shader = function(type) {
vglModule.object.call(this);
var m_shaderHandle = null;
- var m_compileTimestmap = vglModule.timestamp();
+ var m_compileTimestamp = vglModule.timestamp();
var m_shaderType = type;
var m_shaderSource = "";
var m_fileName = "";
@@ -47,7 +47,7 @@ vglModule.shader = function(type) {
};
this.compile = function() {
- if (this.getMTime() < m_compileTimestmap.getMTime()) {
+ if (this.getMTime() < m_compileTimestamp.getMTime()) {
return m_shaderHandle;
}
@@ -65,7 +65,7 @@ vglModule.shader = function(type) {
return null;
}
- m_compileTimestmap.modified();
+ m_compileTimestamp.modified();
return m_shaderHandle;
}; | Implemented multi-geometry feature and got toggle country boundries working | OpenGeoscience_vgl | train |
b6e1ab47ed6a2fa56b88120818fc5348e2effcdd | diff --git a/allel/test/test_io_vcf_read.py b/allel/test/test_io_vcf_read.py
index <HASH>..<HASH> 100644
--- a/allel/test/test_io_vcf_read.py
+++ b/allel/test/test_io_vcf_read.py
@@ -1653,6 +1653,7 @@ def test_vcf_to_npz():
assert_array_almost_equal(expect[key], actual[key])
else:
assert_array_equal(expect[key], actual[key])
+ actual.close()
def test_vcf_to_zarr(): | try to close npz file for windows CI | cggh_scikit-allel | train |
5d059db67212db4dea3a7488ae181ae161f50209 | diff --git a/lib/qbwc/job.rb b/lib/qbwc/job.rb
index <HASH>..<HASH> 100644
--- a/lib/qbwc/job.rb
+++ b/lib/qbwc/job.rb
@@ -28,7 +28,7 @@ class QBWC::Job
end
def process_response(response, session, advance)
- advance_next_request if @requests.present? && advance
+ advance_next_request if advance
@response_proc.call(response, session) if @response_proc
end
diff --git a/lib/qbwc/session.rb b/lib/qbwc/session.rb
index <HASH>..<HASH> 100644
--- a/lib/qbwc/session.rb
+++ b/lib/qbwc/session.rb
@@ -89,10 +89,10 @@ class QBWC::Session
self.iterator_id = nil
return unless response.is_a?(Hash) && response['xml_attributes']
- status_code, status_severity, status_message, iterator_remaining_count, iterator_id = \
+ @status_code, status_severity, status_message, iterator_remaining_count, iterator_id = \
response['xml_attributes'].values_at('statusCode', 'statusSeverity', 'statusMessage',
'iteratorRemainingCount', 'iteratorID')
- if status_severity == 'Error' || status_code.to_i > 1 || response.keys.size <= 1
+ if status_severity == 'Error' || @status_code.to_i > 1
self.error = "QBWC ERROR: #{status_code} - #{status_message}"
else
self.iterator_id = iterator_id if iterator_remaining_count.to_i > 0 | Don't set error when status_code is 1, advance_next_request always so requests with block can check how many requests have been issued | qbwc_qbwc | train |
0b3681a495fe81ba7dd9f6805e7ce7f267759a11 | diff --git a/lib/db/upgrade.php b/lib/db/upgrade.php
index <HASH>..<HASH> 100644
--- a/lib/db/upgrade.php
+++ b/lib/db/upgrade.php
@@ -2298,6 +2298,7 @@ WHERE gradeitemid IS NOT NULL AND grademax IS NOT NULL");
$table->add_field('externalserviceid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
$table->add_field('sid', XMLDB_TYPE_CHAR, '128', null, null, null, null);
$table->add_field('contextid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
+ $table->add_field('creatorid', XMLDB_TYPE_INTEGER, '20', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1');
$table->add_field('iprestriction', XMLDB_TYPE_CHAR, '255', null, null, null, null);
$table->add_field('validuntil', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null);
$table->add_field('timecreated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
@@ -2308,6 +2309,7 @@ WHERE gradeitemid IS NOT NULL AND grademax IS NOT NULL");
$table->add_key('userid', XMLDB_KEY_FOREIGN, array('userid'), 'user', array('id'));
$table->add_key('externalserviceid', XMLDB_KEY_FOREIGN, array('externalserviceid'), 'external_services', array('id'));
$table->add_key('contextid', XMLDB_KEY_FOREIGN, array('contextid'), 'context', array('id'));
+ $table->add_key('creatorid', XMLDB_KEY_FOREIGN, array('creatorid'), 'user', array('id'));
/// Launch create table for external_tokens
$dbman->create_table($table);
@@ -2430,28 +2432,6 @@ WHERE gradeitemid IS NOT NULL AND grademax IS NOT NULL");
upgrade_main_savepoint(true, 2009112400);
}
- if ($oldversion < 2010010601) {
-
- /// Define field creatorid to be added to external_tokens
- $table = new xmldb_table('external_tokens');
- $field = new xmldb_field('creatorid', XMLDB_TYPE_INTEGER, '20', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '1', 'contextid');
-
- /// Conditionally launch add field creatorid
- if (!$dbman->field_exists($table, $field)) {
- $dbman->add_field($table, $field);
- }
-
- /// Define key creatorid (foreign) to be added to external_tokens
- $table = new xmldb_table('external_tokens');
- $key = new xmldb_key('creatorid', XMLDB_KEY_FOREIGN, array('creatorid'), 'user', array('id'));
-
- /// Launch add key creatorid
- $dbman->add_key($table, $key);
-
- /// Main savepoint reached
- upgrade_main_savepoint(true, 2010010601);
- }
-
if ($oldversion < 2010011200) {
$table = new xmldb_table('grade_categories');
$field = new xmldb_field('hidden', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 0); | MDL-<I> external_tokens created in one step | moodle_moodle | train |
21dbd57d509bdd88629f9eb9b0eb7d6e56134d86 | diff --git a/src/AlgoliaSearch/Index.php b/src/AlgoliaSearch/Index.php
index <HASH>..<HASH> 100644
--- a/src/AlgoliaSearch/Index.php
+++ b/src/AlgoliaSearch/Index.php
@@ -322,7 +322,7 @@ class Index {
}
if (gettype($disjunctive_facets) == "string") {
- $disjunctive_facets = split(",", $disjunctive_facets);
+ $disjunctive_facets = explode(",", $disjunctive_facets);
}
$disjunctive_refinements = array(); | PHP7 Removed "split" Function
Changed split to explode() as per PHP7 spec. | algolia_algoliasearch-client-php | train |
c60acaa8e6623d1ecf52deb9e3d87330333c6673 | diff --git a/src/photini/__init__.py b/src/photini/__init__.py
index <HASH>..<HASH> 100644
--- a/src/photini/__init__.py
+++ b/src/photini/__init__.py
@@ -1,4 +1,4 @@
from __future__ import unicode_literals
__version__ = '2016.02.0'
-build = '510 (fc69106)'
+build = '511 (d29019d)'
diff --git a/src/photini/imagelist.py b/src/photini/imagelist.py
index <HASH>..<HASH> 100644
--- a/src/photini/imagelist.py
+++ b/src/photini/imagelist.py
@@ -117,9 +117,23 @@ class Image(QtWidgets.QFrame):
if not paths:
return
drag = QtGui.QDrag(self)
- drag.setPixmap(self.image_list.drag_icon)
- drag.setHotSpot(QtCore.QPoint(
- drag.pixmap().width() // 2, drag.pixmap().height()))
+ # construct icon
+ count = min(len(paths), 8)
+ src_icon = self.image_list.drag_icon
+ src_w = src_icon.width()
+ src_h = src_icon.height()
+ margin = (count - 1) * 4
+ if count == 1:
+ icon = src_icon
+ else:
+ icon = QtGui.QPixmap(src_w + margin, src_h + margin)
+ icon.fill(Qt.transparent)
+ with QtGui.QPainter(icon) as paint:
+ for i in range(count):
+ paint.drawPixmap(
+ QtCore.QPoint(margin - (i * 4), i * 4), src_icon)
+ drag.setPixmap(icon)
+ drag.setHotSpot(QtCore.QPoint(src_w // 2, src_h + margin))
mimeData = QtCore.QMimeData()
mimeData.setData(DRAG_MIMETYPE, repr(paths).encode('utf-8'))
drag.setMimeData(mimeData) | Duplicate icon when dragging several photos to map | jim-easterbrook_Photini | train |
1d70cd942e668f5c6cf02e99d5ff98beaf741969 | diff --git a/src-setup/org/opencms/setup/CmsUpdateBean.java b/src-setup/org/opencms/setup/CmsUpdateBean.java
index <HASH>..<HASH> 100644
--- a/src-setup/org/opencms/setup/CmsUpdateBean.java
+++ b/src-setup/org/opencms/setup/CmsUpdateBean.java
@@ -59,22 +59,18 @@ import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
-import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
import javax.servlet.jsp.JspWriter;
import org.apache.commons.logging.Log;
import com.google.common.collect.Lists;
-import com.google.common.collect.MapMaker;
/**
* A java bean as a controller for the OpenCms update wizard.<p>
@@ -517,58 +513,6 @@ public class CmsUpdateBean extends CmsSetupBean {
}
/**
- * Try to preload necessary classes, to avoid ugly class loader issues caused by JARs being deleted during the update.
- */
- public void preload() {
-
- //opencms.jar
- preload(OpenCms.class);
-
- //guava
- preload(MapMaker.class);
-
- //xerces
- preload(org.apache.xerces.impl.Constants.class);
- }
-
- /**
- * Preloads classes from the same jar file as a given class.<p>
- *
- * @param cls the class for which the classes from the same jar file should be loaded
- */
- public void preload(Class<?> cls) {
-
- try {
- File jar = new File(cls.getProtectionDomain().getCodeSource().getLocation().getFile());
- java.util.jar.JarFile jarfile = new JarFile(jar);
- try {
- Enumeration<JarEntry> entries = jarfile.entries();
- while (entries.hasMoreElements()) {
- JarEntry entry = entries.nextElement();
- String name = entry.getName();
- if (name.endsWith(".class")) {
- String className = name.replaceFirst("\\.class$", "");
- className = className.replace('/', '.');
- try {
- Class.forName(className);
- } catch (VirtualMachineError e) {
- throw e;
- } catch (Throwable e) {
- LOG.error(e.getLocalizedMessage(), e);
- }
- }
- }
- } finally {
- jarfile.close();
- }
- } catch (VirtualMachineError e) {
- throw e;
- } catch (Throwable e) {
- LOG.error(e.getLocalizedMessage(), e);
- }
- }
-
- /**
* Prepares step 1 of the update wizard.<p>
*/
public void prepareUpdateStep1() {
@@ -644,7 +588,6 @@ public class CmsUpdateBean extends CmsSetupBean {
public void prepareUpdateStep5() {
if (isInitialized()) {
- preload();
try {
String fileName = getWebAppRfsPath() + FOLDER_UPDATE + "cmsupdate";
// read the file | Removing no longer needed preload function. | alkacon_opencms-core | train |
f4e1e12efcd77262f69bc4789a884b28d62f74d0 | diff --git a/pyqode/cobol/api/parsers/names.py b/pyqode/cobol/api/parsers/names.py
index <HASH>..<HASH> 100644
--- a/pyqode/cobol/api/parsers/names.py
+++ b/pyqode/cobol/api/parsers/names.py
@@ -300,14 +300,14 @@ def defined_names(code, free_format=False):
if not line.isspace() and not line.strip().startswith("*"):
line = line.strip()
# DIVISIONS
- if regex.DIVISION.indexIn(line.upper()) != -1:
+ if regex.DIVISION.indexIn(line.upper()) != -1 and 'EXIT' not in line.upper():
# remember
if last_div_node is not None:
last_div_node.end_line = i
last_div_node, last_section_node = parse_division(
i, column, line, root_node, last_section_node)
# SECTIONS
- elif regex.SECTION.indexIn(line.upper()) != -1:
+ elif regex.SECTION.indexIn(line.upper()) != -1 and 'EXIT' not in line.upper():
if last_section_node:
last_section_node.end_line = i
if last_div_node is None: | Improve correct recognition of SECTIONS/DIVISION.
Prevent exit SECTION/DIVISION from showing up in the navigation panel
(see pyQode/pyQode#<I>) | pyQode_pyqode.cobol | train |
5089c15fe9ce49037a7f2e9eaeeda8287a349199 | diff --git a/montblanc/BaseSolver.py b/montblanc/BaseSolver.py
index <HASH>..<HASH> 100644
--- a/montblanc/BaseSolver.py
+++ b/montblanc/BaseSolver.py
@@ -649,7 +649,7 @@ class BaseSolver(Solver):
yield mbu.fmt_array_line('Array Name','Size','Type','CPU','GPU','Shape')
yield '-'*80
- for a in self.arrays.itervalues():
+ for a in sorted(self.arrays.itervalues(), key=lambda x: x.name.upper()):
yield mbu.fmt_array_line(a.name,
mbu.fmt_bytes(mbu.array_bytes(a.shape, a.dtype)),
np.dtype(a.dtype).name,
@@ -665,7 +665,7 @@ class BaseSolver(Solver):
'Type', 'Value', 'Default Value')
yield '-'*80
- for p in self.properties.itervalues():
+ for p in sorted(self.properties.itervalues(), key=lambda x: x.name.upper()):
yield mbu.fmt_property_line(
p.name, np.dtype(p.dtype).name,
getattr(self, p.name), p.default) | Display arrays and properties sorted by their name. | ska-sa_montblanc | train |
955c13075360b9cc1f9fcdc9b306e9199024910c | diff --git a/SingularityService/src/main/java/com/hubspot/singularity/resources/TaskResource.java b/SingularityService/src/main/java/com/hubspot/singularity/resources/TaskResource.java
index <HASH>..<HASH> 100644
--- a/SingularityService/src/main/java/com/hubspot/singularity/resources/TaskResource.java
+++ b/SingularityService/src/main/java/com/hubspot/singularity/resources/TaskResource.java
@@ -272,6 +272,7 @@ public class TaskResource {
@Path("/commands/queued")
@ApiOperation(value="Retrieve a list of all the shell commands queued for execution")
public List<SingularityTaskShellCommandRequest> getQueuedShellCommands() {
+ authorizationHelper.checkAdminAuthorization(user);
return taskManager.getAllQueuedTaskShellCommandRequests();
}
@@ -283,9 +284,11 @@ public class TaskResource {
@ApiResponse(code=403, message="Given shell command doesn't exist")
})
@Consumes({ MediaType.APPLICATION_JSON })
- public SingularityTaskShellCommandRequest runShellCommand(@PathParam("taskId") String taskId, @QueryParam("user") Optional<String> user, final SingularityShellCommand shellCommand) {
+ public SingularityTaskShellCommandRequest runShellCommand(@PathParam("taskId") String taskId, @QueryParam("user") Optional<String> queryUser, final SingularityShellCommand shellCommand) {
SingularityTaskId taskIdObj = getTaskIdFromStr(taskId);
+ authorizationHelper.checkForAuthorizationByTaskId(taskId, user);
+
if (!taskManager.isActiveTask(taskId)) {
throw WebExceptions.badRequest("%s is not an active task, can't run %s on it", taskId, shellCommand.getName());
}
@@ -315,7 +318,7 @@ public class TaskResource {
}
}
- SingularityTaskShellCommandRequest shellRequest = new SingularityTaskShellCommandRequest(taskIdObj, user, System.currentTimeMillis(), shellCommand);
+ SingularityTaskShellCommandRequest shellRequest = new SingularityTaskShellCommandRequest(taskIdObj, queryUser, System.currentTimeMillis(), shellCommand);
taskManager.saveTaskShellCommandRequestToQueue(shellRequest); | check for authorization on new shell commands endpoints | HubSpot_Singularity | train |
69e3be2c18dba76d15c5632922d8eef3c1ee5a9a | diff --git a/Model/Behavior/AttachmentBehavior.php b/Model/Behavior/AttachmentBehavior.php
index <HASH>..<HASH> 100644
--- a/Model/Behavior/AttachmentBehavior.php
+++ b/Model/Behavior/AttachmentBehavior.php
@@ -199,7 +199,7 @@ class AttachmentBehavior extends ModelBehavior {
$this->s3 = $this->s3($attachment['s3']);
// Upload or import the file and attach to model data
- $uploadResponse = $this->upload($field, $attachment, array(
+ $uploadResponse = $this->upload($model->alias . '.' . $field, $attachment, array(
'overwrite' => $attachment['overwrite'],
'name' => $attachment['name'],
'append' => $attachment['append'],
diff --git a/Vendor/Uploader.php b/Vendor/Uploader.php
index <HASH>..<HASH> 100644
--- a/Vendor/Uploader.php
+++ b/Vendor/Uploader.php
@@ -1186,9 +1186,16 @@ class Uploader {
}
}
+ list($model, $field) = explode('.', $file);
+
if (isset($this->_data[$file])) {
$this->_current = $file;
-
+
+ } else if (isset($this->_data[$field])) {
+ $this->_current = $field;
+ }
+
+ if ($this->_current) {
$current =& $this->_data[$this->_current];
$current['filesize'] = self::bytes($current['size']);
$current['ext'] = self::ext($current['name']); | Fixed a bug with multiple model uploading with AttachmentBehavior | milesj_uploader | train |
e330741d6d72e97346f3c989960829c247950546 | diff --git a/pkg/volume/azure_file/azure_file.go b/pkg/volume/azure_file/azure_file.go
index <HASH>..<HASH> 100644
--- a/pkg/volume/azure_file/azure_file.go
+++ b/pkg/volume/azure_file/azure_file.go
@@ -150,7 +150,7 @@ func (plugin *azureFilePlugin) ExpandVolumeDevice(
newSize resource.Quantity,
oldSize resource.Quantity) (resource.Quantity, error) {
- if spec.PersistentVolume != nil || spec.PersistentVolume.Spec.AzureFile == nil {
+ if spec.PersistentVolume == nil || spec.PersistentVolume.Spec.AzureFile == nil {
return oldSize, fmt.Errorf("invalid PV spec")
}
shareName := spec.PersistentVolume.Spec.AzureFile.ShareName | fix azure file size grow issue | kubernetes_kubernetes | train |
98ef0c4423bd0f6d98c5c208fb2a300f0a69fe4f | diff --git a/lib/active_scaffold/data_structures/column.rb b/lib/active_scaffold/data_structures/column.rb
index <HASH>..<HASH> 100644
--- a/lib/active_scaffold/data_structures/column.rb
+++ b/lib/active_scaffold/data_structures/column.rb
@@ -278,6 +278,7 @@ module ActiveScaffold::DataStructures
end
def number_to_native(value)
+ return value if value.blank? || !value.is_a?(String)
native = '.' # native ruby separator
format = {:separator => '', :delimiter => ''}.merge! I18n.t('number.format', :default => {})
specific = case self.options[:format] | fix column_to_native when value is nil | activescaffold_active_scaffold | train |
91833dd72ef33bf4504d34faa519fc0351c06a19 | diff --git a/lib/gollum/app.rb b/lib/gollum/app.rb
index <HASH>..<HASH> 100644
--- a/lib/gollum/app.rb
+++ b/lib/gollum/app.rb
@@ -496,7 +496,7 @@ module Precious
# Extensions and layout data
@editable = true
- @page_exists = !page.versions.empty?
+ @page_exists = !page.last_version.nil?
@toc_content = wiki.universal_toc ? @page.toc_data : nil
@mathjax = wiki.mathjax
@h1_title = wiki.h1_title
diff --git a/lib/gollum/views/page.rb b/lib/gollum/views/page.rb
index <HASH>..<HASH> 100644
--- a/lib/gollum/views/page.rb
+++ b/lib/gollum/views/page.rb
@@ -22,15 +22,13 @@ module Precious
end
def author
- page_versions = @page.versions
- first = page_versions ? page_versions.first : false
+ first = page.last_version
return DEFAULT_AUTHOR unless first
first.author.name.respond_to?(:force_encoding) ? first.author.name.force_encoding('UTF-8') : first.author.name
end
def date
- page_versions = @page.versions
- first = page_versions ? page_versions.first : false
+ first = page.last_version
return Time.now.strftime(DATE_FORMAT) unless first
first.authored_date.strftime(DATE_FORMAT)
end | Use `last_version` instead of `versions` when possible. Fixes #<I>.
Use Gollum::Page#last_version instead of Gollum::Page#versions in the
cases identified in #<I>:
* In Precious::App#show_page_or_file
* In Precious::Views::Page#author
* In Precious::Views::Page#date | gollum_gollum | train |
54fc386674a383dcb350e451015dd722947e9312 | diff --git a/src/Traits/ManagesItemsTrait.php b/src/Traits/ManagesItemsTrait.php
index <HASH>..<HASH> 100644
--- a/src/Traits/ManagesItemsTrait.php
+++ b/src/Traits/ManagesItemsTrait.php
@@ -34,15 +34,27 @@ trait ManagesItemsTrait
* This is an alias for reset()
*
* @param array $items
+ * @return $this
*/
- public function initManager($items = [])
+ public function initManager($items = null)
{
if (property_exists($this, 'dataItemsName')) {
$this->setItemsName($this->dataItemsName);
}
$repo = $this->getItemsName();
+
+ if (!isset($this->$repo)) {
+ $this->$repo = [];
+ }
+
+ if (is_null($items)) {
+ return $this;
+ }
+
$this->$repo = is_array($items) ? $items : $this->getArrayableItems($items);
+
+ return $this;
}
/** | bug: initManager() with null properties to ensure repo is setup | electricjones_data-manager | train |
2ec98626c3e76f4725863f28f4fca001d1dd3072 | diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst
index <HASH>..<HASH> 100644
--- a/doc/source/whatsnew/v1.4.0.rst
+++ b/doc/source/whatsnew/v1.4.0.rst
@@ -233,7 +233,7 @@ MultiIndex
I/O
^^^
- Bug in :func:`read_excel` attempting to read chart sheets from .xlsx files (:issue:`41448`)
--
+- Bug in :func:`read_csv` with multi-header input and arguments referencing column names as tuples (:issue:`42446`)
-
Period
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx
index <HASH>..<HASH> 100644
--- a/pandas/_libs/parsers.pyx
+++ b/pandas/_libs/parsers.pyx
@@ -1280,6 +1280,8 @@ cdef class TextReader:
# generate extra (bogus) headers if there are more columns than headers
if j >= len(self.header[0]):
return j
+ elif self.has_mi_columns:
+ return tuple(header_row[j] for header_row in self.header)
else:
return self.header[0][j]
else:
diff --git a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
+++ b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py
@@ -257,3 +257,29 @@ def test_dtype_mangle_dup_cols_single_dtype(all_parsers):
result = parser.read_csv(StringIO(data), dtype=str)
expected = DataFrame({"a": ["1"], "a.1": ["1"]})
tm.assert_frame_equal(result, expected)
+
+
+def test_dtype_multi_index(all_parsers):
+ # GH 42446
+ parser = all_parsers
+ data = "A,B,B\nX,Y,Z\n1,2,3"
+
+ result = parser.read_csv(
+ StringIO(data),
+ header=list(range(2)),
+ dtype={
+ ("A", "X"): np.int32,
+ ("B", "Y"): np.int32,
+ ("B", "Z"): np.float32,
+ },
+ )
+
+ expected = DataFrame(
+ {
+ ("A", "X"): np.int32([1]),
+ ("B", "Y"): np.int32([2]),
+ ("B", "Z"): np.float32([3]),
+ }
+ )
+
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/parser/test_converters.py b/pandas/tests/io/parser/test_converters.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/io/parser/test_converters.py
+++ b/pandas/tests/io/parser/test_converters.py
@@ -161,3 +161,29 @@ def test_converter_index_col_bug(all_parsers):
xp = DataFrame({"B": [2, 4]}, index=Index([1, 3], name="A"))
tm.assert_frame_equal(rs, xp)
+
+
+def test_converter_multi_index(all_parsers):
+ # GH 42446
+ parser = all_parsers
+ data = "A,B,B\nX,Y,Z\n1,2,3"
+
+ result = parser.read_csv(
+ StringIO(data),
+ header=list(range(2)),
+ converters={
+ ("A", "X"): np.int32,
+ ("B", "Y"): np.int32,
+ ("B", "Z"): np.float32,
+ },
+ )
+
+ expected = DataFrame(
+ {
+ ("A", "X"): np.int32([1]),
+ ("B", "Y"): np.int32([2]),
+ ("B", "Z"): np.float32([3]),
+ }
+ )
+
+ tm.assert_frame_equal(result, expected)
diff --git a/pandas/tests/io/parser/test_na_values.py b/pandas/tests/io/parser/test_na_values.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/io/parser/test_na_values.py
+++ b/pandas/tests/io/parser/test_na_values.py
@@ -570,3 +570,23 @@ foo,,bar
)
tm.assert_frame_equal(result, expected)
+
+
+def test_nan_multi_index(all_parsers):
+ # GH 42446
+ parser = all_parsers
+ data = "A,B,B\nX,Y,Z\n1,2,inf"
+
+ result = parser.read_csv(
+ StringIO(data), header=list(range(2)), na_values={("B", "Z"): "inf"}
+ )
+
+ expected = DataFrame(
+ {
+ ("A", "X"): [1],
+ ("B", "Y"): [2],
+ ("B", "Z"): [np.nan],
+ }
+ )
+
+ tm.assert_frame_equal(result, expected) | BUG: Fix multi-index colname references in read_csv c engine. (#<I>) | pandas-dev_pandas | train |
fb872f953decc100e3dccad900f862f6a9064729 | diff --git a/src/core/scene/a-scene.js b/src/core/scene/a-scene.js
index <HASH>..<HASH> 100644
--- a/src/core/scene/a-scene.js
+++ b/src/core/scene/a-scene.js
@@ -711,13 +711,13 @@ function getMaxSize (maxSize, isVR) {
aspectRatio = size.width / size.height;
if ((size.width * pixelRatio) > maxSize.width && maxSize.width !== -1) {
- size.width = maxSize.width / pixelRatio;
- size.height = parseInt(maxSize.width / aspectRatio / pixelRatio);
+ size.width = Math.round(maxSize.width / pixelRatio);
+ size.height = Math.round(maxSize.width / aspectRatio / pixelRatio);
}
if ((size.height * pixelRatio) > maxSize.height && maxSize.height !== -1) {
- size.height = maxSize.height / pixelRatio;
- size.width = parseInt(maxSize.height * aspectRatio / pixelRatio);
+ size.height = Math.round(maxSize.height / pixelRatio);
+ size.width = Math.round(maxSize.height * aspectRatio / pixelRatio);
}
return size; | Switching to math.round and rounding the long side | aframevr_aframe | train |
623d14f4fc54e11936e6fdb0b8c6abefc08138bc | diff --git a/lib/metadata.js b/lib/metadata.js
index <HASH>..<HASH> 100644
--- a/lib/metadata.js
+++ b/lib/metadata.js
@@ -127,8 +127,25 @@ function Metadata(dyno, dataset) {
}))
.on('error', callback)
.on('finish', function() {
- dyno.putItem({ Item: info }, function(err) {
- callback(err, prepare(info));
+
+ var updateParams = {
+ Key: key,
+ ExpressionAttributeNames: {
+ '#w': 'west', '#s': 'south', '#e': 'east', '#n': 'north',
+ '#c': 'count', '#size': 'size', '#id': 'id', '#u': 'updated',
+ '#ec': 'editcount'
+ },
+ ExpressionAttributeValues: {
+ ':w': info.west, ':s': info.south, ':e': info.east, ':n': info.north,
+ ':c': info.count, ':size': info.size, ':u': info.updated, ':ec': 0
+ },
+ UpdateExpression: 'set #w = :w, #s = :s, #e = :e, #n = :n, #c = :c, #size = :size, #u = if_not_exists(#u, :u), #ec = if_not_exists(#ec, :ec)',
+ ConditionExpression: 'attribute_not_exists(#id)',
+ ReturnValues: 'ALL_NEW'
+ };
+
+ dyno.updateItem(updateParams, function(err, update) {
+ callback(err, prepare(update.Attributes));
});
});
};
diff --git a/test/metadata.test.js b/test/metadata.test.js
index <HASH>..<HASH> 100644
--- a/test/metadata.test.js
+++ b/test/metadata.test.js
@@ -520,7 +520,8 @@ test('metadata: calculate dataset info', function(t) {
east: expectedBounds[2],
north: expectedBounds[3],
minzoom: 3,
- maxzoom: 11
+ maxzoom: 11,
+ editcount: 0
};
metadata.calculateInfo(function(err, info) {
@@ -813,7 +814,8 @@ test('calculateDatasetInfo', function(t) {
east: expectedBounds[2],
north: expectedBounds[3],
minzoom: 3,
- maxzoom: 11
+ maxzoom: 11,
+ editcount: 0
};
cardboard.calculateDatasetInfo(dataset, function(err, info) { | add editcount to calculate and fix tests | mapbox_cardboard | train |
18f2c646e4c8902a4b670db8ae76916ffe6f5977 | diff --git a/gatekeeper/responses/response.py b/gatekeeper/responses/response.py
index <HASH>..<HASH> 100644
--- a/gatekeeper/responses/response.py
+++ b/gatekeeper/responses/response.py
@@ -1,7 +1,7 @@
from http.client import responses as STATUS_MESSAGES
-class Response(object):
+class Response(BaseException):
def __init__(self):
self.status = 200
diff --git a/tests/endpoint_tests/endpoint_tests.py b/tests/endpoint_tests/endpoint_tests.py
index <HASH>..<HASH> 100644
--- a/tests/endpoint_tests/endpoint_tests.py
+++ b/tests/endpoint_tests/endpoint_tests.py
@@ -99,18 +99,18 @@ class EndpointTestCase(TestCase):
class ArgsEndpoint(Endpoint):
endpoint_path = '/users/:id/:username/edit'
def get(self, request, response):
- response.args = request.args
+ pass
endpoint = ArgsEndpoint()
request = Request({'REQUEST_METHOD': 'GET', 'PATH_INFO': '/users/9/john/edit'})
response = endpoint.handle_request(request)
- self.assertEqual(response.args, {'id': '9', 'username': 'john'})
+ self.assertEqual(request.args, {'id': '9', 'username': 'john'})
def test_endpoint_without_arguments_have_empty_dict_as_args(self):
class ArgsEndpoint(Endpoint):
endpoint_path = '/users'
def get(self, request, response):
- response.args = request.args
+ pass
endpoint = ArgsEndpoint()
request = Request({'REQUEST_METHOD': 'GET', 'PATH_INFO': '/users'})
response = endpoint.handle_request(request)
- self.assertEqual(response.args, {})
+ self.assertEqual(request.args, {})
diff --git a/tests/response_tests/response_tests.py b/tests/response_tests/response_tests.py
index <HASH>..<HASH> 100644
--- a/tests/response_tests/response_tests.py
+++ b/tests/response_tests/response_tests.py
@@ -51,3 +51,8 @@ class ResponseTestCase(TestCase):
for chunk in file_generator:
contents += chunk
self.assertEqual(contents, b'hello world')
+
+ def test_response_object_can_be_raised(self):
+ response = Response()
+ with self.assertRaises(Response):
+ raise response | Make response a child of BaseException so it can be raised inside endpoints | hugollm_gatekeeper | train |
2f170573145d7fb8a24ed8e0df11555aa8336ec0 | diff --git a/docs/config.go b/docs/config.go
index <HASH>..<HASH> 100644
--- a/docs/config.go
+++ b/docs/config.go
@@ -34,7 +34,17 @@ var (
// NotaryServer is the endpoint serving the Notary trust server
NotaryServer = "https://notary.docker.io"
- // IndexServer = "https://registry-stage.hub.docker.com/v1/"
+ // DefaultV1Registry is the URI of the default v1 registry
+ DefaultV1Registry = &url.URL{
+ Scheme: "https",
+ Host: "index.docker.io",
+ }
+
+ // DefaultV2Registry is the URI of the default v2 registry
+ DefaultV2Registry = &url.URL{
+ Scheme: "https",
+ Host: "registry-1.docker.io",
+ }
)
var (
diff --git a/docs/config_unix.go b/docs/config_unix.go
index <HASH>..<HASH> 100644
--- a/docs/config_unix.go
+++ b/docs/config_unix.go
@@ -2,24 +2,6 @@
package registry
-import (
- "net/url"
-)
-
-var (
- // DefaultV1Registry is the URI of the default v1 registry
- DefaultV1Registry = &url.URL{
- Scheme: "https",
- Host: "index.docker.io",
- }
-
- // DefaultV2Registry is the URI of the default v2 registry
- DefaultV2Registry = &url.URL{
- Scheme: "https",
- Host: "registry-1.docker.io",
- }
-)
-
var (
// CertsDir is the directory where certificates are stored
CertsDir = "/etc/docker/certs.d"
diff --git a/docs/config_windows.go b/docs/config_windows.go
index <HASH>..<HASH> 100644
--- a/docs/config_windows.go
+++ b/docs/config_windows.go
@@ -1,30 +1,11 @@
package registry
import (
- "net/url"
"os"
"path/filepath"
"strings"
)
-var (
- // DefaultV1Registry is the URI of the default v1 registry
- DefaultV1Registry = &url.URL{
- Scheme: "https",
- Host: "registry-win-tp3.docker.io",
- }
-
- // DefaultV2Registry is the URI of the default (official) v2 registry.
- // This is the windows-specific endpoint.
- //
- // Currently it is a TEMPORARY link that allows Microsoft to continue
- // development of Docker Engine for Windows.
- DefaultV2Registry = &url.URL{
- Scheme: "https",
- Host: "registry-win-tp3.docker.io",
- }
-)
-
// CertsDir is the directory where certificates are stored
var CertsDir = os.Getenv("programdata") + `\docker\certs.d` | Remove Windows-specific default registry definitions
Going forward, Docker won't use a different default registry on Windows.
This changes Windows to use the standard Docker Hub registry as the
default registry.
There is a plan in place to migrate existing images from the Windows
registry to Hub's normal registry, in advance of the <I> release. In
the mean time, images on the Windows registry can be accessed by
prefixing them with `registry-win-tp3.docker.io/`. | docker_distribution | train |
834fd1db6e213bb716a32760f308eba89b14a4cd | diff --git a/store/src/main/java/com/buschmais/jqassistant/core/store/impl/RemoteGraphStore.java b/store/src/main/java/com/buschmais/jqassistant/core/store/impl/RemoteGraphStore.java
index <HASH>..<HASH> 100644
--- a/store/src/main/java/com/buschmais/jqassistant/core/store/impl/RemoteGraphStore.java
+++ b/store/src/main/java/com/buschmais/jqassistant/core/store/impl/RemoteGraphStore.java
@@ -11,7 +11,7 @@ import com.buschmais.xo.api.XOManager;
import com.buschmais.xo.api.XOManagerFactory;
import com.buschmais.xo.api.bootstrap.XO;
import com.buschmais.xo.api.bootstrap.XOUnit;
-import com.buschmais.xo.neo4j.remote.api.Neo4jRemoteStoreProvider;
+import com.buschmais.xo.neo4j.remote.api.RemoteNeo4jXOProvider;
public class RemoteGraphStore extends AbstractGraphStore {
@@ -37,7 +37,7 @@ public class RemoteGraphStore extends AbstractGraphStore {
@Override
protected int getAutocommitThreshold() {
- return 512;
+ return 2048;
}
private XOUnit getXoUnit(Collection<Class<?>> types) {
@@ -54,7 +54,7 @@ public class RemoteGraphStore extends AbstractGraphStore {
if (encryptionLevel != null) {
properties.setProperty("neo4j.remote.encryptionLevel", encryptionLevel);
}
- return XOUnit.builder().uri(storeConfiguration.getUri()).provider(Neo4jRemoteStoreProvider.class).types(types).properties(properties)
+ return XOUnit.builder().uri(storeConfiguration.getUri()).provider(RemoteNeo4jXOProvider.class).types(types).properties(properties)
.validationMode(ValidationMode.NONE).mappingConfiguration(XOUnit.MappingConfiguration.builder().strictValidation(true).build()).build();
}
} | updated class name of remote XO provider for Neo4j | buschmais_jqa-core-framework | train |
3479225c09bb4e32645447cf7f8368050454a10f | diff --git a/aws/data_source_aws_api_gateway_rest_api.go b/aws/data_source_aws_api_gateway_rest_api.go
index <HASH>..<HASH> 100644
--- a/aws/data_source_aws_api_gateway_rest_api.go
+++ b/aws/data_source_aws_api_gateway_rest_api.go
@@ -55,19 +55,19 @@ func dataSourceAwsApiGatewayRestApiRead(d *schema.ResourceData, meta interface{}
d.SetId(*match.Id)
- resp, err := conn.GetResources(&apigateway.GetResourcesInput{
+ resourceParams := &apigateway.GetResourcesInput{
RestApiId: aws.String(d.Id()),
- })
- if err != nil {
- return err
}
- for _, item := range resp.Items {
- if *item.Path == "/" {
- d.Set("root_resource_id", item.Id)
- break
+ err = conn.GetResourcesPages(resourceParams, func(page *apigateway.GetResourcesOutput, lastPage bool) bool {
+ for _, item := range page.Items {
+ if *item.Path == "/" {
+ d.Set("root_resource_id", item.Id)
+ return false
+ }
}
- }
+ return !lastPage
+ })
- return nil
+ return err
} | data-source/aws_api_gateway_rest_api: Fixes root_resource_id not being set on correctly when REST API contains more than <I> resources (#<I>)
Output from acceptance testing:
```
--- PASS: TestAccDataSourceAwsApiGatewayRestApi (<I>s)
``` | terraform-providers_terraform-provider-aws | train |
508e42e00fbe89c0daaa3be8a8f2dcb6ec1c82d6 | diff --git a/components/select-ng/select-ng.js b/components/select-ng/select-ng.js
index <HASH>..<HASH> 100644
--- a/components/select-ng/select-ng.js
+++ b/components/select-ng/select-ng.js
@@ -418,6 +418,7 @@ angularModule.directive('rgSelect', function rgSelectDirective() {
});
},
onClose: () => {
+ ctrl.query = null;
$scope.$evalAsync(() => {
ctrl.onClose();
});
diff --git a/components/select-ng/select-ng.test.js b/components/select-ng/select-ng.test.js
index <HASH>..<HASH> 100644
--- a/components/select-ng/select-ng.test.js
+++ b/components/select-ng/select-ng.test.js
@@ -70,6 +70,7 @@ describe('Select Ng', () => {
function initDirective() {
compileTemplate('<rg-select options="item.name for item in items track by item.id"></rg-select>');
}
+
initDirective.should.not.throw;
});
@@ -498,5 +499,13 @@ describe('Select Ng', () => {
ctrl.optionsParser.optionVariableName.should.be.equal('itemvar');
});
+
+ it('should clear last query on close', () => {
+ ctrl.query = 'query';
+ ctrl.config.onClose();
+ scope.$digest();
+
+ expect(ctrl.query).to.be.null;
+ });
});
}); | SelectNg: filter query is not reset after select has been closed #RG-<I> fixed
Former-commit-id: a<I>d8ac<I>f<I>ae<I>faec<I>f0fd7ab1cb3d7 | JetBrains_ring-ui | train |
945efb3a45304d3444117a35f65f67b2a825c066 | diff --git a/Kwf/Controller/Dispatcher.php b/Kwf/Controller/Dispatcher.php
index <HASH>..<HASH> 100644
--- a/Kwf/Controller/Dispatcher.php
+++ b/Kwf/Controller/Dispatcher.php
@@ -42,7 +42,7 @@ class Kwf_Controller_Dispatcher extends Zend_Controller_Dispatcher_Standard
if (!$className) {
return false;
}
- Zend_Loader::loadClass($className);
+ class_exists($className); //trigger autoloader
} else { | load class using autoloader
fixes dispatch if class in not in include path but autoloader can load it | koala-framework_koala-framework | train |
17d83e3b2efdc9e6e995331ca6bb78284d30b89e | diff --git a/packages/ember-views/lib/core.js b/packages/ember-views/lib/core.js
index <HASH>..<HASH> 100644
--- a/packages/ember-views/lib/core.js
+++ b/packages/ember-views/lib/core.js
@@ -4,7 +4,7 @@
*/
var jQuery = Ember.imports.jQuery;
-Ember.assert("Ember Views require jQuery 1.8, 1.9, 1.10, or 2.0", jQuery && (jQuery().jquery.match(/^((1\.(8|9|10))|2.0)(\.\d+)?(pre|rc\d?)?/) || Ember.ENV.FORCE_JQUERY));
+Ember.assert("Ember Views require jQuery 1.7, 1.8, 1.9, 1.10, or 2.0", jQuery && (jQuery().jquery.match(/^((1\.(7|8|9|10))|2.0)(\.\d+)?(pre|rc\d?)?/) || Ember.ENV.FORCE_JQUERY));
/**
Alias for jQuery | Fix to support jQuery <I> | emberjs_ember.js | train |
7b761e0f48d89706043f21d2fe349c9dc0211fd5 | diff --git a/bundles/org.eclipse.orion.client.javascript/web/javascript/validator.js b/bundles/org.eclipse.orion.client.javascript/web/javascript/validator.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.javascript/web/javascript/validator.js
+++ b/bundles/org.eclipse.orion.client.javascript/web/javascript/validator.js
@@ -236,7 +236,7 @@ define([
delete cfg.rules[key];
}
});
- if(confg && !confg.skip) { //test hook to disable these rules unless explicitly added
+ if(!confg || (confg && !confg.skip)) { //test hook to disable these rules unless explicitly added
cfg.rules["unknown-require"] = config.rules["unknown-require"];
cfg.rules["check-tern-plugin"] = config.rules["check-tern-plugin"];
cfg.rules["missing-requirejs"] = config.rules["missing-requirejs"]; | [nobug] Make sure without a test config certain lint rules are always on | eclipse_orion.client | train |
bd44a257624c6a777f47cb14a32ed80f5e6d8a95 | diff --git a/jbake-core/src/main/java/org/jbake/app/ContentStore.java b/jbake-core/src/main/java/org/jbake/app/ContentStore.java
index <HASH>..<HASH> 100644
--- a/jbake-core/src/main/java/org/jbake/app/ContentStore.java
+++ b/jbake-core/src/main/java/org/jbake/app/ContentStore.java
@@ -322,15 +322,22 @@ public class ContentStore {
private void createDocType(final OSchema schema, final String docType) {
logger.debug("Create document class '{}'", docType);
+
OClass page = schema.createClass(docType);
- page.createProperty(String.valueOf(DocumentAttributes.SHA1), OType.STRING).setNotNull(true);
- page.createIndex(docType + "sha1Index", OClass.INDEX_TYPE.NOTUNIQUE, DocumentAttributes.SHA1.toString());
+
+ // Primary key
page.createProperty(String.valueOf(DocumentAttributes.SOURCE_URI), OType.STRING).setNotNull(true);
page.createIndex(docType + "sourceUriIndex", OClass.INDEX_TYPE.UNIQUE, DocumentAttributes.SOURCE_URI.toString());
+
+ page.createProperty(String.valueOf(DocumentAttributes.SHA1), OType.STRING).setNotNull(true);
+ page.createIndex(docType + "sha1Index", OClass.INDEX_TYPE.NOTUNIQUE, DocumentAttributes.SHA1.toString());
+
page.createProperty(String.valueOf(DocumentAttributes.CACHED), OType.BOOLEAN).setNotNull(true);
page.createIndex(docType + "cachedIndex", OClass.INDEX_TYPE.NOTUNIQUE, DocumentAttributes.CACHED.toString());
+
page.createProperty(String.valueOf(DocumentAttributes.RENDERED), OType.BOOLEAN).setNotNull(true);
page.createIndex(docType + "renderedIndex", OClass.INDEX_TYPE.NOTUNIQUE, DocumentAttributes.RENDERED.toString());
+
page.createProperty(String.valueOf(DocumentAttributes.STATUS), OType.STRING).setNotNull(true);
page.createIndex(docType + "statusIndex", OClass.INDEX_TYPE.NOTUNIQUE, DocumentAttributes.STATUS.toString());
} | Make index creation bit more readable (just reorder) | jbake-org_jbake | train |
78da2bde5cb2429ada45d3b719a9a716ca00dc4f | diff --git a/plugins/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java b/plugins/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java
index <HASH>..<HASH> 100644
--- a/plugins/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java
+++ b/plugins/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java
@@ -829,7 +829,7 @@ public class JvmTypesBuilder {
} else {
p.append(toStringBuilder.getName());
}
- p.append("(this).addAllFields().toString()");
+ p.append("(this).addAllFields().toString();");
p.newLine().append("return result;");
}
}); | [xbase][builder] Fixed typo: Added missing semicolon
Change-Id: I<I>fbbb1d1deec<I>dac<I>c<I>bad4d<I>c<I> | eclipse_xtext-extras | train |
63bb7616a06e1232e8e867919450649e91a4515c | diff --git a/pact-jvm-provider-junit/src/main/java/au/com/dius/pact/provider/junit/loader/PactBrokerLoader.java b/pact-jvm-provider-junit/src/main/java/au/com/dius/pact/provider/junit/loader/PactBrokerLoader.java
index <HASH>..<HASH> 100644
--- a/pact-jvm-provider-junit/src/main/java/au/com/dius/pact/provider/junit/loader/PactBrokerLoader.java
+++ b/pact-jvm-provider-junit/src/main/java/au/com/dius/pact/provider/junit/loader/PactBrokerLoader.java
@@ -58,7 +58,7 @@ public class PactBrokerLoader implements PactLoader {
this.pactBrokerTags = tags.stream().flatMap(tag -> parseListExpression(tag).stream()).collect(toList());
this.pactBrokerConsumers = consumers.stream().flatMap(consumer -> parseListExpression(consumer).stream()).collect(toList());
this.failIfNoPactsFound = true;
- this.pactSource = new PactBrokerSource(this.pactBrokerHost, this.pactBrokerPort);
+ this.pactSource = new PactBrokerSource(this.pactBrokerHost, this.pactBrokerPort, this.pactBrokerProtocol);
}
public PactBrokerLoader(final PactBroker pactBroker) { | Put back oddly removed param for pactSource initialization | DiUS_pact-jvm | train |
e0fd6074aadcc531d569bf242acc79212c208913 | diff --git a/app/controllers/organizations_controller.rb b/app/controllers/organizations_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/organizations_controller.rb
+++ b/app/controllers/organizations_controller.rb
@@ -103,9 +103,8 @@ class OrganizationsController < ApplicationController
def edit
@org_label = ""
- default_org = current_user.default_org
- if default_org && !default_org.nil?
- user_default_org = (Organization.find(default_org))
+ user_default_org = current_user.default_org
+ if user_default_org && !user_default_org.nil?
if user_default_org == @organization
@org_label = _("This is your default organization.")
else
diff --git a/app/controllers/user_sessions_controller.rb b/app/controllers/user_sessions_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/user_sessions_controller.rb
+++ b/app/controllers/user_sessions_controller.rb
@@ -84,10 +84,9 @@ class UserSessionsController < ApplicationController
current_user.set_ldap_roles if AppConfig.ldap_roles
orgs = current_user.allowed_organizations
- default_org = current_user.default_org
user_default_org = nil
- if default_org && !default_org.nil?
- user_default_org = (Organization.find(default_org))
+ if current_user.default_org && !current_user.default_org.nil?
+ user_default_org = current_user.default_org
end
if current_organization.nil?
@@ -97,7 +96,7 @@ class UserSessionsController < ApplicationController
notify.success _("Login Successful")
set_org
elsif !user_default_org.nil? && orgs.include?(user_default_org)
- params[:org_id] = default_org
+ params[:org_id] = user_default_org.id
# notice the user
notify.success _("Login Successful, logging into '%s' ") % user_default_org.name
set_org
diff --git a/app/models/user.rb b/app/models/user.rb
index <HASH>..<HASH> 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -483,11 +483,10 @@ class User < ActiveRecord::Base
org_id = self.preferences[:user][:default_org] rescue nil
if org_id && !org_id.nil? && org_id != "nil"
org = Organization.find_by_id(org_id)
- return org.id if allowed_organizations.include?org
+ return org if allowed_organizations.include?(org)
else
return nil
end
-
end
#set the default org if it's an actual org_id
diff --git a/app/views/common/_fav.html.haml b/app/views/common/_fav.html.haml
index <HASH>..<HASH> 100644
--- a/app/views/common/_fav.html.haml
+++ b/app/views/common/_fav.html.haml
@@ -10,9 +10,9 @@
have received a copy of GPLv2 along with this software; if not, see
http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
-= check_box_tag "org_#{org.id}", org.id, current_user.default_org == org.id, {:class=>"default_org", "data-url"=>setup_default_org_user_path(current_user.id)}
+= check_box_tag "org_#{org.id}", org.id, current_user.default_org == org, {:class=>"default_org", "data-url"=>setup_default_org_user_path(current_user.id)}
-- if current_user.default_org == org.id
+- if current_user.default_org == org
%span.favorite.favorites_icon-black.sprite.tipsify{:title=>_("This is your default organization."), :id=>"favorite_#{org.id}"}
- else
%span.favorite.favorites_icon-grey.sprite.tipsify{:title=>_("Make this your default organization."), :id=>"favorite_#{org.id}"}
diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/user_spec.rb
+++ b/spec/models/user_spec.rb
@@ -61,6 +61,7 @@ describe User do
@org = Organization.create!(:name => 'test_org', :cp_key => 'test_org')
@user.default_org = @org
@user.save!
+ @user.stub!(:allowed_organizations).and_return([@org])
@user.default_org.should == @org
end
@@ -112,6 +113,7 @@ describe User do
@org = Organization.create!(:name => 'test_org', :cp_key => 'test_org')
@user.default_org = @org
@user.save!
+ allow(@user.own_role, [:read], :providers, nil, @org)
@user.default_org.should == @org
end | Fixing user spec tests that were breaking
Fixed user spec tests and also refactored User#default_org so that it returns an organization
instead of an organization id. | Katello_katello | train |
05d46ea0b32421a7874ef8b5db728f9338eeebf7 | diff --git a/lib/flip/cookie_strategy.rb b/lib/flip/cookie_strategy.rb
index <HASH>..<HASH> 100644
--- a/lib/flip/cookie_strategy.rb
+++ b/lib/flip/cookie_strategy.rb
@@ -38,7 +38,7 @@ module Flip
private
def cookies
- @@cookies || raise("Cookies not loaded")
+ @@cookies || {}
end
# Include in ApplicationController to push cookies into CookieStrategy. | CookieStrategy gracefully handles absence of cookie data. | voormedia_flipflop | train |
f0dd709ced6087c36870af9ba9d956dd38f9ab4b | diff --git a/lib/gitnesse.rb b/lib/gitnesse.rb
index <HASH>..<HASH> 100644
--- a/lib/gitnesse.rb
+++ b/lib/gitnesse.rb
@@ -128,7 +128,7 @@ module Gitnesse
feature_files.each do |feature_file|
feature_name = File.basename(feature_file, ".feature")
- feature_content = File.open(feature_file, "r") { |file| file.read }
+ feature_content = File.read(feature_file)
wiki_page = wiki.page(page_name)
if wiki_page | Enhance readability of code when reading file. | hybridgroup_gitnesse | train |
dd0147056ad17e82eafa594d0564730821fd81cc | diff --git a/source/org/jasig/portal/channels/UserPreferences/TabColumnPrefsState.java b/source/org/jasig/portal/channels/UserPreferences/TabColumnPrefsState.java
index <HASH>..<HASH> 100644
--- a/source/org/jasig/portal/channels/UserPreferences/TabColumnPrefsState.java
+++ b/source/org/jasig/portal/channels/UserPreferences/TabColumnPrefsState.java
@@ -41,6 +41,7 @@ import org.jasig.portal.IUserPreferencesManager;
import org.jasig.portal.UserPreferencesManager;
import org.jasig.portal.UserPreferences;
import org.jasig.portal.UserProfile;
+import org.jasig.portal.PortalControlStructures;
import org.jasig.portal.StructureStylesheetUserPreferences;
import org.jasig.portal.StructureAttributesIncorporationFilter;
import org.jasig.portal.PortalException;
@@ -101,14 +102,14 @@ import org.jasig.portal.layout.UserLayoutFolderDescription;
* @author Ken Weiner, [email protected]
* @version $Revision$
*/
-final class TabColumnPrefsState extends BaseState
+class TabColumnPrefsState extends BaseState
{
protected ChannelStaticData staticData;
protected ChannelRuntimeData runtimeData;
private static final String sslLocation = "/org/jasig/portal/channels/CUserPreferences/tab-column/tab-column.ssl";
private IUserLayoutManager ulm;
-
+ private PortalControlStructures pcs;
private UserPreferences userPrefs;
private UserProfile editedUserProfile;
private static IUserLayoutStore ulStore = UserLayoutStoreFactory.getUserLayoutStoreImpl();
@@ -201,6 +202,10 @@ final class TabColumnPrefsState extends BaseState
}
}
+ public void setPortalControlStructures(PortalControlStructures pcs) throws PortalException {
+ this.pcs = pcs;
+ }
+
public void renderXML(ContentHandler out) throws PortalException
{
if (this.internalState != null)
@@ -474,8 +479,6 @@ final class TabColumnPrefsState extends BaseState
*/
private final void addChannel(Element newChannel, String position, String destinationElementId) throws PortalException
{
- //ken: the meaning of destinationElement eludes me here ... I'll just guess -peterk.
-
UserLayoutChannelDescription channel=new UserLayoutChannelDescription(newChannel);
if(isTab(destinationElementId)) {
// create a new column and move channel there
@@ -492,6 +495,10 @@ final class TabColumnPrefsState extends BaseState
}
ulm.addNode(channel,ulm.getParentId(destinationElementId),siblingId);
}
+
+ // Make sure ChannelManager knows about the new channel
+ pcs.getChannelManager().instantiateChannel(channel.getId());
+
ulm.saveUserLayout();
}
@@ -504,13 +511,25 @@ final class TabColumnPrefsState extends BaseState
*/
private final void addChannel(String selectedChannelSubscribeId, String position, String destinationElementId) throws Exception
{
+System.out.println("addChannel1");
Document channelRegistry = ChannelRegistryManager.getChannelRegistry(staticData.getPerson());
Element newChannel = channelRegistry.getElementById(selectedChannelSubscribeId);
addChannel(newChannel, position, destinationElementId);
}
+ /**
+ * Removes a channel element from the layout
+ * @param channelSubscribeId the ID attribute of the channel to remove
+ */
+ private final void deleteChannel(String channelSubscribeId) throws Exception
+ {
+ pcs.getChannelManager().removeChannel(channelSubscribeId);
+ deleteElement(channelSubscribeId);
+ }
+
/**
- * Removes a tab, column, or channel element from the layout
+ * Removes a tab or column element from the layout. To remove
+ * a channel element, call deleteChannel().
* @param elementId the ID attribute of the element to remove
*/
private final void deleteElement(String elementId) throws Exception
@@ -955,7 +974,7 @@ final class TabColumnPrefsState extends BaseState
{
String channelSubscribeId = runtimeData.getParameter("elementID");
- deleteElement(channelSubscribeId);
+ deleteChannel(channelSubscribeId);
}
catch (Exception e)
{ | Now calls ChannelManager to add or remove a channel. This ensures that the UNSUBSCRIBE portal event gets passed to the channel.
git-svn-id: <URL> | Jasig_uPortal | train |
d5936784b5835eae82e3d0166ddc383e17cd063b | diff --git a/cdm/src/test/java/thredds/catalog/TestWrite.java b/cdm/src/test/java/thredds/catalog/TestWrite.java
index <HASH>..<HASH> 100644
--- a/cdm/src/test/java/thredds/catalog/TestWrite.java
+++ b/cdm/src/test/java/thredds/catalog/TestWrite.java
@@ -55,6 +55,22 @@ public class TestWrite extends TestCase {
String fileOutName = TestCatalogAll.tmpDir + filename + ".tmp";
System.out.println(" output filename= "+fileOutName);
+
+ File tmpFile = new File(fileOutName);
+ boolean ret;
+ if (tmpFile.exists()) {
+ System.out.println("output file exists!");
+ if (tmpFile.isDirectory()) {
+ System.out.println("output file is directory!");
+ ret = tmpFile.delete();
+ if (!ret) System.out.println("error deleting directory");
+ } else if (!tmpFile.canWrite()) {
+ System.out.println("cannot write to output file");
+ ret = tmpFile.setWritable(true);
+ if (!ret) System.out.println("error making file writable");
+ }
+ }
+
try {
OutputStream out = new BufferedOutputStream( new FileOutputStream( fileOutName));
cat.writeXML( out); | Trying to make test more robust.
Not really sure what's wrong here. | Unidata_thredds | train |
b232a8df70a5a55422bb3593dd5c7aa49f58df48 | diff --git a/fireplace/targeting.py b/fireplace/targeting.py
index <HASH>..<HASH> 100644
--- a/fireplace/targeting.py
+++ b/fireplace/targeting.py
@@ -19,5 +19,6 @@ TARGET_ENEMY_CHARACTERS = TARGET_ENEMY_HERO | TARGET_ENEMY_MINIONS
TARGET_ANY_MINION = TARGET_FRIENDLY_MINION | TARGET_ENEMY_MINION
TARGET_ANY_HERO = TARGET_FRIENDLY_HERO | TARGET_ENEMY_HERO
+TARGET_ANY_CHARACTER = TARGET_ANY_MINION | TARGET_ANY_HERO
TARGET_ALL_MINIONS = TARGET_FRIENDLY_MINIONS | TARGET_ENEMY_MINIONS
TARGET_ALL_CHARACTERS = TARGET_ALL_MINIONS | TARGET_ANY_HERO | Add missing TARGET_ANY_CHARACTER constant | jleclanche_fireplace | train |
4f76cdaee2fffb87ae3c13ddcd62c4d0adbc5059 | diff --git a/parallax.js b/parallax.js
index <HASH>..<HASH> 100755
--- a/parallax.js
+++ b/parallax.js
@@ -5,35 +5,6 @@
*/
;(function ( $, window, document, undefined ) {
-
- // Polyfill for requestAnimationFrame
- // via: https://gist.github.com/paulirish/1579671
-
- (function() {
- var lastTime = 0;
- var vendors = ['ms', 'moz', 'webkit', 'o'];
- for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
- window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
- window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
- }
-
- if (!window.requestAnimationFrame)
- window.requestAnimationFrame = function(callback) {
- var currTime = new Date().getTime();
- var timeToCall = Math.max(0, 16 - (currTime - lastTime));
- var id = window.setTimeout(function() { callback(currTime + timeToCall); },
- timeToCall);
- lastTime = currTime + timeToCall;
- return id;
- };
-
- if (!window.cancelAnimationFrame)
- window.cancelAnimationFrame = function(id) {
- clearTimeout(id);
- };
- }());
-
-
// Parallax Constructor
function Parallax(element, options) {
@@ -267,7 +238,7 @@
setup: function() {
if (this.isReady) return;
- this.lastRequestAnimationFrame = null;
+ var self = this;
var $doc = $(document), $win = $(window);
@@ -289,6 +260,7 @@
$win.on('resize.px.parallax load.px.parallax', function() {
loadDimensions();
+ self.refresh();
Parallax.isFresh = false;
Parallax.requestRender();
})
@@ -323,12 +295,9 @@
requestRender: function() {
var self = this;
- window.cancelAnimationFrame(self.lastRequestAnimationFrame);
- self.lastRequestAnimationFrame = window.requestAnimationFrame(function() {
- self.render();
- self.isBusy = false;
- });
+ self.render();
+ self.isBusy = false;
},
destroy: function(el){
var i, | Bypassing requestAnimationFrame removes any delay when fast scrolling.
requestAnimationFrame may be used with better results in a loop in the future | pixelcog_parallax.js | train |
a8f2860d0e7db86c61bb70935006100b04667ab1 | diff --git a/activesupport/lib/active_support/core_ext/date/calculations.rb b/activesupport/lib/active_support/core_ext/date/calculations.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/core_ext/date/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/date/calculations.rb
@@ -190,9 +190,14 @@ class Date
result = self - days_to_start
acts_like?(:time) ? result.midnight : result
end
- alias :monday :beginning_of_week
alias :at_beginning_of_week :beginning_of_week
+ # Returns a new +Date+/+DateTime+ representing the start of this week. Week is
+ # assumed to start on a Monday. +DateTime+ objects have their time set to 0:00.
+ def monday
+ beginning_of_week
+ end
+
# Returns a new +Date+/+DateTime+ representing the end of this week. Week is
# assumed to start on +start_day+, default is +:monday+. +DateTime+ objects
# have their time set to 23:59:59.
@@ -201,9 +206,14 @@ class Date
result = self + days_to_end.days
self.acts_like?(:time) ? result.end_of_day : result
end
- alias :sunday :end_of_week
alias :at_end_of_week :end_of_week
+ # Returns a new +Date+/+DateTime+ representing the end of this week. Week is
+ # assumed to start on a Monday. +DateTime+ objects have their time set to 23:59:59.
+ def sunday
+ end_of_week
+ end
+
# Returns a new +Date+/+DateTime+ representing the given +day+ in the previous
# week. Default is +:monday+. +DateTime+ objects have their time set to 0:00.
def prev_week(day = :monday)
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -174,9 +174,14 @@ class Time
days_to_start = days_to_week_start(start_day)
(self - days_to_start.days).midnight
end
- alias :monday :beginning_of_week
alias :at_beginning_of_week :beginning_of_week
+ # Returns a new +Date+/+DateTime+ representing the start of this week. Week is
+ # assumed to start on a Monday. +DateTime+ objects have their time set to 0:00.
+ def monday
+ beginning_of_week
+ end
+
# Returns a new Time representing the end of this week, week starts on start_day (default is :monday, i.e. end of Sunday).
def end_of_week(start_day = :monday)
days_to_end = 6 - days_to_week_start(start_day)
diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile
index <HASH>..<HASH> 100644
--- a/railties/guides/source/active_support_core_extensions.textile
+++ b/railties/guides/source/active_support_core_extensions.textile
@@ -3051,7 +3051,7 @@ d.end_of_week # => Sun, 09 May 2010
d.end_of_week(:sunday) # => Sat, 08 May 2010
</ruby>
-+beginning_of_week+ is aliased to +monday+ and +at_beginning_of_week+. +end_of_week+ is aliased to +sunday+ and +at_end_of_week+.
++beginning_of_week+ is aliased to +at_beginning_of_week+ and +end_of_week+ is aliased to +at_end_of_week+.
h6. +prev_week+, +next_week+
@@ -3276,8 +3276,10 @@ The class +DateTime+ is a subclass of +Date+ so by loading +active_support/core_
<ruby>
yesterday
tomorrow
-beginning_of_week (monday, at_beginning_of_week)
+beginning_of_week (at_beginning_of_week)
end_of_week (at_end_of_week)
+monday
+sunday
weeks_ago
prev_week
next_week
@@ -3450,8 +3452,9 @@ ago
since (in)
beginning_of_day (midnight, at_midnight, at_beginning_of_day)
end_of_day
-beginning_of_week (monday, at_beginning_of_week)
+beginning_of_week (at_beginning_of_week)
end_of_week (at_end_of_week)
+monday
weeks_ago
prev_week
next_week | Convert aliases monday and sunday to methods
A recent change to beginning_of_week and end_of_week added an argument
that can be used to specify the week's starting day as a symbol. Now
these methods were aliased as monday and sunday respectively which as a
consequence of the argument addition, made calls like obj.monday(:sunday)
possible. This commit makes them methods on their own. | rails_rails | train |
c986b0d8e6d7c631d5afee87fadd8d969f94d0e1 | diff --git a/lib/beefcake/generator.rb b/lib/beefcake/generator.rb
index <HASH>..<HASH> 100644
--- a/lib/beefcake/generator.rb
+++ b/lib/beefcake/generator.rb
@@ -109,7 +109,8 @@ class CodeGeneratorRequest
optional :name, :string, 1 # file name, relative to root of source tree
optional :package, :string, 2 # e.g. "foo", "foo.bar", etc.
- repeated :message_type, DescriptorProto, 4;
+ repeated :message_type, DescriptorProto, 4;
+ repeated :enum_type, EnumDescriptorProto, 5;
end
@@ -280,10 +281,14 @@ module Beefcake
puts
ns!(ns) do
+ Array(file.enum_type).each do |et|
+ enum!(et)
+ end
file.message_type.each do |mt|
define! mt
end
+
file.message_type.each do |mt|
message!(file.package, mt)
end | Add support for top-level enums | protobuf-ruby_beefcake | train |
440761e33b144f90010a4bb483ce1b9e55f4c36f | diff --git a/lib/figleaf/configuration.rb b/lib/figleaf/configuration.rb
index <HASH>..<HASH> 100644
--- a/lib/figleaf/configuration.rb
+++ b/lib/figleaf/configuration.rb
@@ -33,15 +33,17 @@ module Figleaf
def method_missing(method_name, *args)
if self.auto_define && method_name.to_s =~ /=$/ && args.length == 1
+ arg = args.shift
self.define_cattr_methods(method_name)
- self.send(method_name, args.shift)
+ self.define_predicate_cattr_methods(method_name) if !!arg == arg
+ self.send(method_name, arg)
else
super
end
end
- def define_cattr_methods(setter_name)
- getter_name = setter_name.to_s.gsub('=','')
+ def define_cattr_methods(method_name)
+ getter_name = method_name.to_s.gsub('=', '')
cattr_writer getter_name
define_singleton_method(getter_name) do
@@ -49,6 +51,15 @@ module Figleaf
result.respond_to?(:call) ? result.call : result
end
end
+
+ def define_predicate_cattr_methods(method_name)
+ getter_name = method_name.to_s.gsub('=', '')
+ define_singleton_method("#{getter_name}?") do
+ result = class_variable_get "@@#{getter_name}"
+ result.respond_to?(:call) ? result.call : result
+ end
+ end
+
end
end
end
diff --git a/spec/settings_spec.rb b/spec/settings_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/settings_spec.rb
+++ b/spec/settings_spec.rb
@@ -54,6 +54,16 @@ describe Figleaf::Settings do
described_class.another_fictional_feature_mode.should eq(:admin)
described_class.enable_fictional_activity_feed.should be_true
end
+
+ it "should define predicate methods" do
+ described_class.configure_with_auto_define do |s|
+ s.some_boolean = true
+ s.another_boolean = false
+ end
+
+ described_class.some_boolean?.should be_true
+ described_class.another_boolean?.should be_false
+ end
end
describe "self.configure" do | Support predicate methods for boolean values | jcmuller_figleaf | train |
8e293de233491870149fc01a3f621f47e4d83162 | diff --git a/java-vision/samples/snippets/src/test/java/com/example/vision/DetectIT.java b/java-vision/samples/snippets/src/test/java/com/example/vision/DetectIT.java
index <HASH>..<HASH> 100644
--- a/java-vision/samples/snippets/src/test/java/com/example/vision/DetectIT.java
+++ b/java-vision/samples/snippets/src/test/java/com/example/vision/DetectIT.java
@@ -125,7 +125,7 @@ public class DetectIT {
public void testLandmarksUrl() throws Exception {
// Act
String uri = "https://storage-download.googleapis.com/"
- + "cloud-samples-tests" + "/vision/landmark.jpg";
+ + BUCKET + "/vision/landmark.jpg";
String[] args = {"landmarks", uri};
Detect.argsHelper(args, out); | samples: Change test to environment variable. | googleapis_google-cloud-java | train |
b641146d423debb041ad94037bf03a8ea89fd082 | diff --git a/core-bundle/src/Resources/contao/drivers/DC_Table.php b/core-bundle/src/Resources/contao/drivers/DC_Table.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/drivers/DC_Table.php
+++ b/core-bundle/src/Resources/contao/drivers/DC_Table.php
@@ -468,7 +468,7 @@ class DC_Table extends \DataContainer implements \listable, \editable
}
}
- $row[$i] = implode('<br>', $value);
+ $row[$i] = implode(', ', $value);
}
else
{
@@ -499,7 +499,7 @@ class DC_Table extends \DataContainer implements \listable, \editable
}
}
- $row[$i] = implode('<br>', $value);
+ $row[$i] = implode(', ', $value);
}
}
elseif ($GLOBALS['TL_DCA'][$this->strTable]['fields'][$i]['eval']['rgxp'] == 'date') | Do not use <br> tags in the show view (see #<I>) | contao_contao | train |
71fc9f00e36cd71fc70575e7c7e2562437eef76e | diff --git a/runcommands/args.py b/runcommands/args.py
index <HASH>..<HASH> 100644
--- a/runcommands/args.py
+++ b/runcommands/args.py
@@ -276,9 +276,15 @@ class Arg:
if self.inverse_help:
inverse_help = self.inverse_help
elif self.help:
- first_letter = kwargs['help'][0].lower()
- rest = kwargs['help'][1:]
- inverse_help = 'Don\'t {first_letter}{rest}'.format_map(locals())
+ help_ = kwargs['help']
+ if help_.startswith('Don\'t '):
+ inverse_help = help_[6:].capitalize()
+ elif help_.startswith('Do not '):
+ inverse_help = help_[7:].capitalize()
+ else:
+ first_letter = help_[0].lower()
+ rest = help_[1:]
+ inverse_help = 'Don\'t {first_letter}{rest}'.format_map(locals())
else:
inverse_help = self.help | Improve inverse help message for some cases
Handle `help` that starts with "Don't" or "Do not" by trimming either of
those strings from `help` and then capitalizing the remaining string. | wylee_runcommands | train |
6aaf5ed897d6b14241957b1fdc98009e5bec05d7 | diff --git a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/LongSerializer.java b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/LongSerializer.java
index <HASH>..<HASH> 100644
--- a/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/LongSerializer.java
+++ b/flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/LongSerializer.java
@@ -18,12 +18,12 @@
package org.apache.flink.api.common.typeutils.base;
-import java.io.IOException;
-
import org.apache.flink.annotation.Internal;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
+import java.io.IOException;
+
@Internal
public final class LongSerializer extends TypeSerializerSingleton<Long> {
@@ -31,7 +31,7 @@ public final class LongSerializer extends TypeSerializerSingleton<Long> {
public static final LongSerializer INSTANCE = new LongSerializer();
- private static final Long ZERO = Long.valueOf(0);
+ private static final Long ZERO = 0L;
@Override
public boolean isImmutableType() {
@@ -55,17 +55,17 @@ public final class LongSerializer extends TypeSerializerSingleton<Long> {
@Override
public int getLength() {
- return 8;
+ return Long.BYTES;
}
@Override
public void serialize(Long record, DataOutputView target) throws IOException {
- target.writeLong(record.longValue());
+ target.writeLong(record);
}
@Override
public Long deserialize(DataInputView source) throws IOException {
- return Long.valueOf(source.readLong());
+ return source.readLong();
}
@Override | [hotfix] Minor cleanups in LongSerializer | apache_flink | train |
34a66d8e803e47d17e187dc6fa6bf8e13b23a63e | diff --git a/core-bundle/src/DependencyInjection/Configuration.php b/core-bundle/src/DependencyInjection/Configuration.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/DependencyInjection/Configuration.php
+++ b/core-bundle/src/DependencyInjection/Configuration.php
@@ -96,7 +96,7 @@ class Configuration implements ConfigurationInterface
->end()
->end()
->scalarNode('editable_files')
- ->defaultValue('css,csv,html,ini,js,json,less,md,scss,svg,svgz,txt,xliff,xml,yml,yaml')
+ ->defaultValue('css,csv,html,ini,js,json,less,md,scss,svg,svgz,ts,txt,xliff,xml,yml,yaml')
->end()
->scalarNode('url_suffix')
->setDeprecated('contao/core-bundle', '4.10', 'The URL suffix is configured per root page since Contao 4.10. Using this option requires legacy routing.')
diff --git a/core-bundle/src/Resources/contao/classes/Backend.php b/core-bundle/src/Resources/contao/classes/Backend.php
index <HASH>..<HASH> 100644
--- a/core-bundle/src/Resources/contao/classes/Backend.php
+++ b/core-bundle/src/Resources/contao/classes/Backend.php
@@ -163,6 +163,9 @@ abstract class Backend extends Controller
case 'markdown':
return 'markdown';
+ case 'ts':
+ return 'typescript';
+
case 'cgi':
case 'pl':
return 'perl';
@@ -180,7 +183,7 @@ abstract class Backend extends Controller
case 'svg':
case 'svgz':
- return 'xml';
+ return 'svg';
default:
return 'text'; | Support Typescript in the code editor (see #<I>)
Description
-----------
-
Commits
-------
a<I>d<I>e Support Typescript in the code editor | contao_contao | train |
6098b810bf49e32310c76dd4f3e3c7ab6ab2251d | diff --git a/cellbase-mongodb/src/main/java/org/opencb/cellbase/mongodb/db/VariantAnnotationMongoDBAdaptor.java b/cellbase-mongodb/src/main/java/org/opencb/cellbase/mongodb/db/VariantAnnotationMongoDBAdaptor.java
index <HASH>..<HASH> 100644
--- a/cellbase-mongodb/src/main/java/org/opencb/cellbase/mongodb/db/VariantAnnotationMongoDBAdaptor.java
+++ b/cellbase-mongodb/src/main/java/org/opencb/cellbase/mongodb/db/VariantAnnotationMongoDBAdaptor.java
@@ -1327,10 +1327,16 @@ public class VariantAnnotationMongoDBAdaptor extends MongoDBAdaptor implements
}
private List<ConsequenceType> filterConsequenceTypesBySoTerms(List<ConsequenceType> consequenceTypeList, List<String> querySoTerms) {
- for (Iterator<ConsequenceType> iterator = consequenceTypeList.iterator(); iterator.hasNext(); ) {
- ConsequenceType consequenceType = iterator.next();
- if (!consequenceTypeContainsSoTerm(consequenceType, querySoTerms)) {
- iterator.remove();
+ if (querySoTerms.size() > 0) {
+ boolean hasAnyOfQuerySoTerms = false;
+ for (ConsequenceType consequenceType : consequenceTypeList) {
+ if (consequenceTypeContainsSoTerm(consequenceType, querySoTerms)) {
+ hasAnyOfQuerySoTerms = true;
+ break;
+ }
+ }
+ if (!hasAnyOfQuerySoTerms) {
+ consequenceTypeList = Collections.EMPTY_LIST;
}
}
return consequenceTypeList; | VariantMongoDBAdaptor: fixed SO term consequence type filter | opencb_cellbase | train |
880ed10debf574a4911258f9a8147c3b8ea718f7 | diff --git a/src/themes/foundation.js b/src/themes/foundation.js
index <HASH>..<HASH> 100644
--- a/src/themes/foundation.js
+++ b/src/themes/foundation.js
@@ -68,8 +68,8 @@ JSONEditor.defaults.themes.foundation = JSONEditor.AbstractTheme.extend({
input.group.className += ' error';
if(!input.errmsg) {
- input.insertAdjacentHTML('afterend','<small class="errormsg"></small>');
- input.errmsg = input.parentNode.getElementsByClassName('errormsg')[0];
+ input.insertAdjacentHTML('afterend','<small class="error"></small>');
+ input.errmsg = input.parentNode.getElementsByClassName('error')[0];
}
else {
input.errmsg.style.display = ''; | use correct css class for latest foundation | jdorn_json-editor | train |
cb657c79a139fc676b57a89197c53c84bd9bda30 | diff --git a/bin/tapestry.php b/bin/tapestry.php
index <HASH>..<HASH> 100644
--- a/bin/tapestry.php
+++ b/bin/tapestry.php
@@ -1,7 +1,8 @@
<?php
use \Tapestry\Console\Application;
-$tapestry = require_once __DIR__ . '/../src/bootstrap.php';
+require_once __DIR__ . '/../src/bootstrap.php';
+$tapestry = new \Tapestry\Tapestry();
/** @var Application $cli */
$cli = $tapestry[Application::class];
diff --git a/src/Tapestry.php b/src/Tapestry.php
index <HASH>..<HASH> 100644
--- a/src/Tapestry.php
+++ b/src/Tapestry.php
@@ -37,18 +37,15 @@ class Tapestry implements ContainerAwareInterface, ArrayAccess
*/
public function __construct($arguments = [])
{
- $siteEnvironment = (isset($arguments['environment'])) ? $arguments['environment'] : 'local';
- $siteDirectory = (isset($arguments['cwd'])) ? $arguments['cwd'] : getcwd();
-
- if (php_sapi_name() === 'cli') {
+ //if (php_sapi_name() === 'cli') {
$input = new ArgvInput();
if ((!$siteEnvironment = $input->getParameterOption('--env')) && (!$siteEnvironment = $input->getParameterOption('-e'))) {
- $siteEnvironment = 'local';
+ $siteEnvironment = (isset($arguments['--env'])) ? $arguments['--env'] : 'local';
}
if (!$siteDirectory = $input->getParameterOption('--site-dir')) {
- $siteDirectory = getcwd();
+ $siteDirectory = (isset($arguments['--site-dir'])) ? $arguments['--site-dir'] : getcwd();
}
- }
+ //}
$this['environment'] = $siteEnvironment;
$this['currentWorkingDirectory'] = $siteDirectory;
diff --git a/src/bootstrap.php b/src/bootstrap.php
index <HASH>..<HASH> 100644
--- a/src/bootstrap.php
+++ b/src/bootstrap.php
@@ -23,8 +23,4 @@ if (isset($include)) {
} else {
echo "Please run composer install." . PHP_EOL;
exit(1);
-}
-
-$tapestry = new \Tapestry\Tapestry();
-
-return $tapestry;
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/tests/CommandTestBase.php b/tests/CommandTestBase.php
index <HASH>..<HASH> 100644
--- a/tests/CommandTestBase.php
+++ b/tests/CommandTestBase.php
@@ -4,6 +4,8 @@ use Symfony\Component\Console\Tester\ApplicationTester;
use Symfony\Component\Filesystem\Filesystem;
use Tapestry\Console\Application;
+require_once __DIR__ . '/../src/bootstrap.php';
+
abstract class CommandTestBase extends \PHPUnit_Framework_TestCase
{
/**
@@ -51,22 +53,6 @@ abstract class CommandTestBase extends \PHPUnit_Framework_TestCase
}
}
- /**
- * @return Application
- */
- private function createCliApplication()
- {
- /** @var Application $app */
- $app = require __DIR__ . '/../src/bootstrap.php';
-
- //$app->reboot();
-
- /** @var Application $cli */
- $cli = $app[Application::class];
- $cli->setAutoExit(false);
- return $cli;
- }
-
protected function copyDirectory($from, $to)
{
$from = __DIR__ . DIRECTORY_SEPARATOR . $from;
@@ -117,7 +103,7 @@ abstract class CommandTestBase extends \PHPUnit_Framework_TestCase
*/
protected function runCommand($command, array $arguments = [])
{
- $applicationTester = new ApplicationTester($this->getCli());
+ $applicationTester = new ApplicationTester($this->getCli($arguments));
$arguments = array_merge(['command' => $command], $arguments);
$applicationTester->run($arguments);
return $applicationTester;
@@ -126,12 +112,14 @@ abstract class CommandTestBase extends \PHPUnit_Framework_TestCase
* Obtain the cli application for testing
* @return Application
*/
- private function getCli()
+ private function getCli(array $arguments = [])
{
- if (is_null($this->cli)) {
- $this->cli = $this->createCliApplication();
- }
- return $this->cli;
+ $tapestry = new \Tapestry\Tapestry($arguments);
+
+ /** @var Application $cli */
+ $cli = $tapestry[Application::class];
+ $cli->setAutoExit(false);
+ return $cli;
}
}
\ No newline at end of file | :green_heart: Load Environment Config now passes unit tests | tapestry-cloud_tapestry | train |
bf5ffdcd35537cf424beaefba5fa4bc50a8fb5be | diff --git a/lib/lit/cache.rb b/lib/lit/cache.rb
index <HASH>..<HASH> 100644
--- a/lib/lit/cache.rb
+++ b/lib/lit/cache.rb
@@ -49,11 +49,12 @@ module Lit
localizations.keys
end
- def update_locale(key, value, force_array = false)
+ def update_locale(key, value, force_array = false, unless_changed = false)
key = key.to_s
locale_key, key_without_locale = split_key(key)
locale = find_locale(locale_key)
localization = find_localization(locale, key_without_locale, value, force_array, true)
+ return localization.get_value if unless_changed && localization.is_changed?
localizations[key] = localization.get_value if localization
end
@@ -62,11 +63,11 @@ module Lit
localizations[key] = value
end
- def delete_locale(key)
+ def delete_locale(key, unless_changed = false)
key = key.to_s
locale_key, key_without_locale = split_key(key)
locale = find_locale(locale_key)
- delete_localization(locale, key_without_locale)
+ delete_localization(locale, key_without_locale, unless_changed)
end
def load_all_translations
@@ -227,8 +228,9 @@ module Lit
where(localization_key_id: localization_key.id).first
end
- def delete_localization(locale, key_without_locale)
+ def delete_localization(locale, key_without_locale, unless_changed = false)
localization = find_localization_for_delete(locale, key_without_locale)
+ return if unless_changed && localization.try(:is_changed?)
if localization
localizations.delete("#{locale.locale}.#{key_without_locale}")
localization_keys.delete(key_without_locale)
diff --git a/lib/lit/i18n_backend.rb b/lib/lit/i18n_backend.rb
index <HASH>..<HASH> 100644
--- a/lib/lit/i18n_backend.rb
+++ b/lib/lit/i18n_backend.rb
@@ -83,26 +83,26 @@ module Lit
content
end
- def store_item(locale, data, scope = [])
+ def store_item(locale, data, scope = [], unless_changed = false)
if data.respond_to?(:to_hash)
# ActiveRecord::Base.transaction do
data.to_hash.each do |key, value|
- store_item(locale, value, scope + [key])
+ store_item(locale, value, scope + [key], unless_changed)
end
# end
elsif data.respond_to?(:to_str)
key = ([locale] + scope).join('.')
- @cache[key] ||= data
+ @cache.update_locale(key, data, false, unless_changed)
elsif data.nil?
key = ([locale] + scope).join('.')
- @cache.delete_locale(key)
+ @cache.delete_locale(key, unless_changed)
end
end
def load_translations_to_cache
ActiveRecord::Base.transaction do
(@translations || {}).each do |locale, data|
- store_item(locale, data) if valid_locale?(locale)
+ store_item(locale, data, [], true) if valid_locale?(locale)
end
end
end | Prevent overwriting UI-modified strings with .yml defaults | prograils_lit | train |
06e76e28435b3e9c6e420c02ebc144117939b99a | diff --git a/lib/main.js b/lib/main.js
index <HASH>..<HASH> 100755
--- a/lib/main.js
+++ b/lib/main.js
@@ -1,6 +1,7 @@
#!/usr/bin/env node
var fs = require('fs');
+var os = require('os');
var net = require('net');
var assert = require('assert');
var json_socket = require('./json_socket');
@@ -10,6 +11,7 @@ var DEFAULT_IPC_FILE = 'naught.ipc';
var DEFAULT_PID_FILE = 'naught.pid';
var CWD = process.cwd();
var daemon = require('./daemon');
+var packageJson = require('../package.json');
var cmds = {
start: {
@@ -230,7 +232,7 @@ var cmds = {
fn: function(argv) {
if (argv) {
if (argv.length > 0) return false;
- console.log(require('../package.json').version);
+ console.log(packageJson.version);
return true;
}
},
@@ -575,7 +577,7 @@ function displayStatus(ipcFile){
function extendedWorkerCount(workerCount){
if (workerCount === 'auto'){
- return require('os').cpus().length;
+ return os.cpus().length;
} else {
return parseInt(workerCount, 10);
} | minor cleanup: require things at the top | andrewrk_naught | train |
228988ffb82a906932ba857b4932aa5eb98919f8 | diff --git a/chat/indico_chat/controllers/base.py b/chat/indico_chat/controllers/base.py
index <HASH>..<HASH> 100644
--- a/chat/indico_chat/controllers/base.py
+++ b/chat/indico_chat/controllers/base.py
@@ -25,8 +25,6 @@ from indico_chat.util import is_chat_admin
class RHChatManageEventBase(RHConferenceModifBase):
- ALLOW_LEGACY_IDS = False
-
def _checkParams(self, params):
RHConferenceModifBase._checkParams(self, params)
self.event_id = int(self._conf.id)
diff --git a/chat/indico_chat/controllers/event.py b/chat/indico_chat/controllers/event.py
index <HASH>..<HASH> 100644
--- a/chat/indico_chat/controllers/event.py
+++ b/chat/indico_chat/controllers/event.py
@@ -27,8 +27,6 @@ from indico_chat.views import WPChatEventPage
class RHChatEventPage(RHConferenceBaseDisplay):
"""Lists the public chatrooms in a conference"""
- ALLOW_LEGACY_IDS = False
-
def _process(self):
chatrooms = ChatroomEventAssociation.find_for_event(self._conf).all()
cols = set()
diff --git a/chat/indico_chat/plugin.py b/chat/indico_chat/plugin.py
index <HASH>..<HASH> 100644
--- a/chat/indico_chat/plugin.py
+++ b/chat/indico_chat/plugin.py
@@ -113,8 +113,6 @@ class ChatPlugin(IndicoPlugin):
self.register_js_bundle('chat_js', 'js/chat.js')
def inject_event_header(self, event, **kwargs):
- if event.has_legacy_id:
- return ''
chatrooms = ChatroomEventAssociation.find_for_event(event).all()
if not chatrooms:
return ''
@@ -150,8 +148,6 @@ class ChatPlugin(IndicoPlugin):
return url_for_plugin('chat.manage_rooms', event)
def event_deleted(self, event, **kwargs):
- if event.has_legacy_id:
- return
for event_chatroom in ChatroomEventAssociation.find_for_event(event, include_hidden=True):
chatroom_deleted = event_chatroom.delete()
notify_deleted(event_chatroom.chatroom, event, None, chatroom_deleted)
@@ -162,8 +158,7 @@ class ChatPlugin(IndicoPlugin):
class ChatroomCloner(EventCloner):
def get_options(self):
- enabled = (not self.event.has_legacy_id and
- bool(ChatroomEventAssociation.find_for_event(self.event, include_hidden=True).count()))
+ enabled = bool(ChatroomEventAssociation.find_for_event(self.event, include_hidden=True).count())
return {'chatrooms': (_('Chatrooms'), enabled, False)}
def clone(self, new_event, options): | Chat: Remove legacy event id checks | indico_indico-plugins | train |
036c134cb307dbbac789d57781eb1ef122586da0 | diff --git a/billy/importers/events.py b/billy/importers/events.py
index <HASH>..<HASH> 100644
--- a/billy/importers/events.py
+++ b/billy/importers/events.py
@@ -62,9 +62,10 @@ def import_events(abbr, data_dir, import_actions=False):
bill['_scraped_bill_id'] = bill['bill_id']
bill_id = bill['bill_id']
bill_id = fix_bill_id(bill_id)
+ bill['bill_id'] = ""
db_bill = db.bills.find_one({"state": abbr,
- 'session': data['session'],
- 'bill_id': bill_id})
+ 'session': data['session'],
+ 'bill_id': bill_id})
# Events are really hard to pin to a chamber. Some of these are
# also a committee considering a bill from the other chamber, or
# something like that. | Cleaning up a bit of the events stuff to fail loudly | openstates_billy | train |
3a5a525aeedfff5243d127ea38df5101aa320d54 | diff --git a/src/Symfony/Component/Console/Helper/QuestionHelper.php b/src/Symfony/Component/Console/Helper/QuestionHelper.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Console/Helper/QuestionHelper.php
+++ b/src/Symfony/Component/Console/Helper/QuestionHelper.php
@@ -28,11 +28,6 @@ class QuestionHelper extends Helper
private static $shell;
private static $stty;
- public function __construct()
- {
- $this->inputStream = STDIN;
- }
-
/**
* Asks a question to the user.
*
@@ -114,6 +109,8 @@ class QuestionHelper extends Helper
*/
public function doAsk(OutputInterface $output, Question $question)
{
+ $inputStream = $this->inputStream ?: STDIN;
+
$message = $question->getQuestion();
if ($question instanceof ChoiceQuestion) {
$width = max(array_map('strlen', array_keys($question->getChoices())));
@@ -135,7 +132,7 @@ class QuestionHelper extends Helper
$ret = false;
if ($question->isHidden()) {
try {
- $ret = trim($this->getHiddenResponse($output));
+ $ret = trim($this->getHiddenResponse($output, $inputStream));
} catch (\RuntimeException $e) {
if (!$question->isHiddenFallback()) {
throw $e;
@@ -144,14 +141,14 @@ class QuestionHelper extends Helper
}
if (false === $ret) {
- $ret = fgets($this->inputStream, 4096);
+ $ret = fgets($inputStream, 4096);
if (false === $ret) {
throw new \RuntimeException('Aborted');
}
$ret = trim($ret);
}
} else {
- $ret = trim($this->autocomplete($output, $question));
+ $ret = trim($this->autocomplete($output, $question, $inputStream));
}
$ret = strlen($ret) > 0 ? $ret : $question->getDefault();
@@ -171,7 +168,7 @@ class QuestionHelper extends Helper
*
* @return string
*/
- private function autocomplete(OutputInterface $output, Question $question)
+ private function autocomplete(OutputInterface $output, Question $question, $inputStream)
{
$autocomplete = $question->getAutocompleterValues();
$ret = '';
@@ -190,8 +187,8 @@ class QuestionHelper extends Helper
$output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
// Read a keypress
- while (!feof($this->inputStream)) {
- $c = fread($this->inputStream, 1);
+ while (!feof($inputStream)) {
+ $c = fread($inputStream, 1);
// Backspace Character
if ("\177" === $c) {
@@ -212,7 +209,7 @@ class QuestionHelper extends Helper
// Pop the last character off the end of our string
$ret = substr($ret, 0, $i);
} elseif ("\033" === $c) { // Did we read an escape sequence?
- $c .= fread($this->inputStream, 2);
+ $c .= fread($inputStream, 2);
// A = Up Arrow. B = Down Arrow
if ('A' === $c[2] || 'B' === $c[2]) {
@@ -289,7 +286,7 @@ class QuestionHelper extends Helper
*
* @throws \RuntimeException In case the fallback is deactivated and the response cannot be hidden
*/
- private function getHiddenResponse(OutputInterface $output)
+ private function getHiddenResponse(OutputInterface $output, $inputStream)
{
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
@@ -315,7 +312,7 @@ class QuestionHelper extends Helper
$sttyMode = shell_exec('stty -g');
shell_exec('stty -echo');
- $value = fgets($this->inputStream, 4096);
+ $value = fgets($inputStream, 4096);
shell_exec(sprintf('stty %s', $sttyMode));
if (false === $value) { | [Console] Fix #<I>: Allow instancing Console Application when STDIN is not declared | symfony_symfony | train |
569e7ac71a5a87b03e846033a334de111b0eed30 | diff --git a/src/main/java/org/audit4j/handler/db/AuditLogDaoImpl.java b/src/main/java/org/audit4j/handler/db/AuditLogDaoImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/audit4j/handler/db/AuditLogDaoImpl.java
+++ b/src/main/java/org/audit4j/handler/db/AuditLogDaoImpl.java
@@ -85,35 +85,20 @@ final class AuditLogDaoImpl extends AuditBaseDao implements AuditLogDao {
query.append("insert into audit(uuid, timestamp, actor, origin, action, elements) ").append(
"values (?, ?, ?, ?, ?, ?)");
- Connection conn = getConnection();
- PreparedStatement statement = null;
- try {
- statement = conn.prepareStatement(query.toString());
- statement.setString(1, uuid);
- statement.setString(2, timestamp);
- statement.setString(3, event.getActor());
- statement.setString(4, event.getOrigin());
- statement.setString(5, event.getAction());
- statement.setString(6, elements.toString());
- statement.execute();
+ try (Connection conn = getConnection()) {
+ try (PreparedStatement statement = conn.prepareStatement(query.toString())) {
+ statement.setString(1, uuid);
+ statement.setString(2, timestamp);
+ statement.setString(3, event.getActor());
+ statement.setString(4, event.getOrigin());
+ statement.setString(5, event.getAction());
+ statement.setString(6, elements.toString());
+
+ return statement.execute();
+ }
} catch (SQLException e) {
throw new HandlerException("SQL Exception", DatabaseAuditHandler.class, e);
- } finally {
- try {
- statement.close();
- statement = null;
- } catch (SQLException e) {
- throw new HandlerException("SQL Exception", DatabaseAuditHandler.class, e);
- } finally {
- try {
- conn.close();
- conn = null;
- } catch (SQLException e) {
- throw new HandlerException("SQL Exception", DatabaseAuditHandler.class, e);
- }
- }
}
- return true;
}
/**
@@ -133,29 +118,13 @@ final class AuditLogDaoImpl extends AuditBaseDao implements AuditLogDao {
query.append("elements varchar(20000)");
query.append(");");
- Connection conn = getConnection();
- PreparedStatement statement = null;
- try {
- statement = conn.prepareStatement(query.toString());
- statement.execute();
+ try (Connection conn = getConnection()) {
+ try (PreparedStatement statement = conn.prepareStatement(query.toString())) {
+ return statement.execute();
+ }
} catch (SQLException e) {
throw new HandlerException("SQL Exception", DatabaseAuditHandler.class, e);
- } finally {
- try {
- statement.close();
- statement = null;
- } catch (SQLException e) {
- throw new HandlerException("SQL Exception", DatabaseAuditHandler.class, e);
- } finally {
- try {
- conn.close();
- conn = null;
- } catch (SQLException e) {
- throw new HandlerException("SQL Exception", DatabaseAuditHandler.class, e);
- }
- }
}
- return true;
}
/** | prevent hiding exception when writing event
use try-with-resources to close PreparedStatement and Connection | audit4j_audit4j-db | train |
6eb4ec28cc17447c916a941c85cf6397f6b76bc6 | diff --git a/src/main/java/nl/jqno/equalsverifier/internal/ConditionalInstantiator.java b/src/main/java/nl/jqno/equalsverifier/internal/ConditionalInstantiator.java
index <HASH>..<HASH> 100644
--- a/src/main/java/nl/jqno/equalsverifier/internal/ConditionalInstantiator.java
+++ b/src/main/java/nl/jqno/equalsverifier/internal/ConditionalInstantiator.java
@@ -96,12 +96,34 @@ public class ConditionalInstantiator {
* If the call to the factory method fails.
*/
public Object callFactory(String factoryMethod, Class<?>[] paramTypes, Object[] paramValues) {
+ return callFactory(fullyQualifiedClassName, factoryMethod, paramTypes, paramValues);
+ }
+
+ /**
+ * Attempts to call a static factory method on a type.
+ *
+ * @param factoryTypeName
+ * The type that contains the factory method.
+ * @param factoryMethod
+ * The name of the factory method.
+ * @param paramTypes
+ * The types of the parameters of the specific overload of the
+ * factory method we want to call.
+ * @param paramValues
+ * The values that we want to pass into the factory method.
+ * @return An instance of the type given by the factory method with the
+ * given parameter values, or null of the type does not exist.
+ * @throws ReflectionException
+ * If the call to the factory method fails.
+ */
+ public Object callFactory(String factoryTypeName, String factoryMethod, Class<?>[] paramTypes, Object[] paramValues) {
try {
Class<?> type = resolve();
if (type == null) {
return null;
}
- Method factory = type.getMethod(factoryMethod, paramTypes);
+ Class<?> factoryType = Class.forName(factoryTypeName);
+ Method factory = factoryType.getMethod(factoryMethod, paramTypes);
return factory.invoke(null, paramValues);
}
catch (Exception e) {
diff --git a/src/test/java/nl/jqno/equalsverifier/internal/ConditionalInstantiatorTest.java b/src/test/java/nl/jqno/equalsverifier/internal/ConditionalInstantiatorTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/nl/jqno/equalsverifier/internal/ConditionalInstantiatorTest.java
+++ b/src/test/java/nl/jqno/equalsverifier/internal/ConditionalInstantiatorTest.java
@@ -24,6 +24,7 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import java.math.BigDecimal;
+import java.util.Collections;
import java.util.GregorianCalendar;
import nl.jqno.equalsverifier.internal.exceptions.ReflectionException;
@@ -113,6 +114,46 @@ public class ConditionalInstantiatorTest {
}
@Test
+ public void objectIsInstantiatedCorrectly_whenValidExternalFactoryMethodAndParametersAreProvided() {
+ ci = new ConditionalInstantiator("java.util.List");
+ Object expected = Collections.emptyList();
+
+ Object actual = ci.callFactory("java.util.Collections", "emptyList", classes(), objects());
+ assertThat(actual, is(expected));
+ }
+
+ @Test
+ public void nullIsReturned_whenExternalFactoryIsCalled_givenTypeDoesNotExist() {
+ ci = new ConditionalInstantiator(THIS_TYPE_DOES_NOT_EXIST);
+ Object actual = ci.callFactory("java.util.Collections", "emptyList", classes(), objects());
+ assertThat(actual, is(nullValue()));
+ }
+
+ @Test
+ public void nullIsReturned_whenExternalFactoryIsCalled_givenFactoryTypeDoesNotExist() {
+ ci = new ConditionalInstantiator("java.util.List");
+
+ thrown.expect(ReflectionException.class);
+ ci.callFactory("java.util.ThisTypeDoesNotExist", "emptyList", classes(), objects());
+ }
+
+ @Test
+ public void throwsISE_whenInvalidExternalFactoryMethodNameIsProvided() {
+ ci = new ConditionalInstantiator("java.util.List");
+
+ thrown.expect(ReflectionException.class);
+ ci.callFactory("java.util.Collections", "thisMethodDoesntExist", classes(), objects());
+ }
+
+ @Test
+ public void throwsISE_whenInvalidExternalFactoryMethodParametersAreProvided() {
+ ci = new ConditionalInstantiator("java.util.List");
+
+ thrown.expect(ReflectionException.class);
+ ci.callFactory("java.util.Collections", "emptyList", classes(int.class), objects(42));
+ }
+
+ @Test
public void nullIsReturned_whenReturnConstantIsCalled_givenTypeDoesNotExist() {
ci = new ConditionalInstantiator(THIS_TYPE_DOES_NOT_EXIST);
Object actual = ci.returnConstant("NOPE"); | Issue <I>: Expand ConditionalInstantiator's callFactory capability
Conflicts:
src/main/java/nl/jqno/equalsverifier/util/ConditionalInstantiator.java
src/test/java/nl/jqno/equalsverifier/util/ConditionalInstantiatorTest.java | jqno_equalsverifier | train |
aba21f8eb99ac0daa57f12a006cbc439c9718b87 | diff --git a/src/generators/dom/visitors/attributes/lookup.js b/src/generators/dom/visitors/attributes/lookup.js
index <HASH>..<HASH> 100644
--- a/src/generators/dom/visitors/attributes/lookup.js
+++ b/src/generators/dom/visitors/attributes/lookup.js
@@ -109,7 +109,7 @@ const lookup = {
title: {},
type: { appliesTo: [ 'button', 'input', 'command', 'embed', 'object', 'script', 'source', 'style', 'menu' ] },
usemap: { propertyName: 'useMap', appliesTo: [ 'img', 'input', 'object' ] },
- value: { appliesTo: [ 'button', 'option', 'input', 'li', 'meter', 'progress', 'param' ] },
+ value: { appliesTo: [ 'button', 'option', 'input', 'li', 'meter', 'progress', 'param', 'select' ] },
width: { appliesTo: [ 'canvas', 'embed', 'iframe', 'img', 'input', 'object', 'video' ] },
wrap: { appliesTo: [ 'textarea' ] }
}; | <select> elements should use .value prop to update value (#<I>) | sveltejs_svelte | train |
333d8d3e5ffd05aeb4e99602c5512b5e17cd627e | diff --git a/GPy/models/GP_regression.py b/GPy/models/GP_regression.py
index <HASH>..<HASH> 100644
--- a/GPy/models/GP_regression.py
+++ b/GPy/models/GP_regression.py
@@ -79,7 +79,7 @@ class GP_regression(model):
return self.kern._get_params_transformed()
def _get_param_names(self):
- return self.kern._get_params_names_transformed()
+ return self.kern._get_param_names_transformed()
def _model_fit_term(self):
""" | Fix error introduced into GP_regression when doing name changes. | SheffieldML_GPy | train |
e65ff01b69b379de11de514625896b48f6aafab3 | diff --git a/motion/ruby_motion_query/animations.rb b/motion/ruby_motion_query/animations.rb
index <HASH>..<HASH> 100644
--- a/motion/ruby_motion_query/animations.rb
+++ b/motion/ruby_motion_query/animations.rb
@@ -1,39 +1,42 @@
module RubyMotionQuery
class RMQ
+ # Animate
+ #
# @return [RMQ]
def animate(opts = {})
+ animations_callback = (opts[:animations] || opts[:changes])
+ after_callback = (opts[:completion] || opts[:after])
+ return self unless animations_callback
+
+
working_selected = self.selected
- @_rmq = self # @ for rm bug
+ self_rmq = self
- animations_lambda = if (animations_callback = (opts.delete(:animations) || opts.delete(:changes)))
- -> do
- working_selected.each do |view|
- animations_callback.call(@_rmq.create_rmq_in_context(view))
- end
+ working_selected.each do |view|
+ view_rmq = self_rmq.wrap(view)
+
+ animations_lambda = -> do
+ animations_callback.call(view_rmq)
end
- else
- nil
- end
- return self unless animations_lambda
+ after_lambda = if after_callback
+ ->(did_finish) {
+ after_callback.call(did_finish, view_rmq)
+ }
+ else
+ nil
+ end
- after_lambda = if (after_callback = (opts.delete(:completion) || opts.delete(:after)))
- -> (did_finish) {
- after_callback.call(did_finish, @_rmq)
- }
- else
- nil
+ UIView.animateWithDuration(
+ opts[:duration] || 0.3,
+ delay: opts[:delay] || 0,
+ options: opts[:options] || UIViewAnimationOptionCurveEaseInOut,
+ animations: animations_lambda,
+ completion: after_lambda
+ )
end
- UIView.animateWithDuration(
- opts.delete(:duration) || 0.3,
- delay: opts.delete(:delay) || 0,
- options: (opts.delete(:options) || UIViewAnimationOptionCurveEaseInOut),
- animations: animations_lambda,
- completion: after_lambda
- )
-
self
end
@@ -86,34 +89,38 @@ module RubyMotionQuery
def throb(opts = {})
opts.merge!({
duration: 0.4,
- animations: -> (cq) {
+ animations: ->(cq) {
cq.style {|st| st.scale = 1.0}
}
})
- @rmq.animate(
+ out = @rmq.animate(
duration: 0.1,
- animations: -> (q) {
+ animations: ->(q) {
q.style {|st| st.scale = 1.1}
},
- completion: -> (did_finish, q) {
- q.animate(opts)
+ completion: ->(did_finish, completion_rmq) {
+ if did_finish
+ completion_rmq.animate(opts)
+ end
}
)
+ out
end
+ # @return [RMQ]
def drop_and_spin(opts = {})
remove_view = opts[:remove_view]
opts.merge!({
duration: 0.4 + (rand(8) / 10),
options: UIViewAnimationOptionCurveEaseIn|UIViewAnimationOptionBeginFromCurrentState,
- animations: -> (cq) {
+ animations: ->(cq) {
cq.style do |st|
st.top = @rmq.device.height + st.height
st.rotation = 180 + rand(50)
end
},
- completion: -> (did_finish, q) {
+ completion: ->(did_finish, q) {
if did_finish
q.style do |st|
st.rotation = 0 | Refactored RMQ#animate, fixing some bugs. It now calls completion for every selected view (this was a bug) | infinitered_rmq | train |
a35de2a6ee8d887abcffbc2a4653b62b69c2f69e | diff --git a/test/lib/test.js b/test/lib/test.js
index <HASH>..<HASH> 100644
--- a/test/lib/test.js
+++ b/test/lib/test.js
@@ -39,16 +39,19 @@ _ = _
.property('checkStream', _.curry(function(property, args, test) {
var env = this,
failures = [],
+ expected = 0,
inputs,
applied,
i,
check = env.curry(function(state, inputs, index, result) {
state(
!result ?
- env.Some(_.failureReporter(
- inputs,
- index + 1
- )) :
+ env.Some(
+ _.failureReporter(
+ inputs,
+ index + 1
+ )
+ ) :
env.None
);
}),
@@ -69,12 +72,17 @@ _ = _
return function() {
test.ok(true, 'OK');
};
- };
+ },
+ add = function() {
+ expected = _.inc(expected);
+ },
+ nothing = function() {};
for(i = 0; i < env.goal; i++) {
inputs = env.generateInputs(env, args, i);
applied = property.apply(this, inputs);
applied.fork(check(reporter, inputs, i), checkDone());
+ applied.length().fork(add, nothing);
}
var valid = _.fold(failures, true, function(a, b) {
@@ -85,7 +93,7 @@ _ = _
});
// FIXME: This should only call checkDone once.
- // test.expect(shouldComplete ? 2 : 1);
+ test.expect(expected + 1);
test.ok(valid, words);
test.done();
})) | Making sure is actually called with the right number of expectations. | SimonRichardson_squishy-pants | train |
14e18cd7f5804884ad00a11cf1c9597b78cdf59c | diff --git a/packages/jsreport-chrome-pdf/test/chromeTest.js b/packages/jsreport-chrome-pdf/test/chromeTest.js
index <HASH>..<HASH> 100644
--- a/packages/jsreport-chrome-pdf/test/chromeTest.js
+++ b/packages/jsreport-chrome-pdf/test/chromeTest.js
@@ -57,7 +57,7 @@ function common (strategy, imageExecution) {
reporter.use(require('../')({
strategy,
- numberOfWorkers: 2,
+ numberOfWorkers: 1,
launchOptions: {
args: ['--no-sandbox']
}
diff --git a/packages/jsreport-pdf-utils/test/test.js b/packages/jsreport-pdf-utils/test/test.js
index <HASH>..<HASH> 100644
--- a/packages/jsreport-pdf-utils/test/test.js
+++ b/packages/jsreport-pdf-utils/test/test.js
@@ -33,7 +33,7 @@ describe('pdf utils', () => {
return jsreport.init()
})
- afterEach(() => jsreport.close())
+ afterEach(() => jsreport && jsreport.close())
it('merge should embed static text', async () => {
await jsreport.documentStore.collection('templates').insert({
@@ -1369,7 +1369,7 @@ describe('pdf utils', () => {
content: '{{{pdfAddPageItem "foo"}}}',
engine: 'handlebars',
recipe: 'chrome-pdf'
- }
+ }
})
const $pdf = await jsreport.pdfUtils.parse(appendRest.content)
@@ -1431,7 +1431,7 @@ describe('pdf utils', () => {
parsedPdf.pages.should.have.length(1)
})
- it('should expose jsreport-proxy pdfUtils and postprocess should be able to add pasword', async () => {
+ it('should expose jsreport-proxy pdfUtils and postprocess should be able to add password', async () => {
const result = await jsreport.render({
template: {
content: 'foo',
@@ -1444,7 +1444,7 @@ describe('pdf utils', () => {
async function afterRender (req, res) {
res.content = await jsreport.pdfUtils.postprocess(res.content, {
pdfPassword: {
- password: 'password'
+ password: 'password'
}
})
}
@@ -2042,7 +2042,7 @@ describe('pdf utils', () => {
content: "{{{pdfFormField name='b' type='text' width='200px' height='20px'}}}",
recipe: "chrome-pdf",
engine: "handlebars"
- }
+ }
})
res.content = await jsreport.pdfUtils.append(res.content, r.content)
} | chrome tests: update numberOfWorkers to 1 to avoid crash
we will investigate why the tests crash but until that we just change the option as a workaround | jsreport_jsreport | train |
2dd55db4c10d32a5d7442e977fed878c3feb72c0 | diff --git a/tools/http2_interop/http2interop_test.go b/tools/http2_interop/http2interop_test.go
index <HASH>..<HASH> 100644
--- a/tools/http2_interop/http2interop_test.go
+++ b/tools/http2_interop/http2interop_test.go
@@ -17,7 +17,7 @@ var (
serverHost = flag.String("server_host", "", "The host to test")
serverPort = flag.Int("server_port", 443, "The port to test")
useTls = flag.Bool("use_tls", true, "Should TLS tests be run")
- testCase = flag.String("test_case", "", "What test cases to run")
+ testCase = flag.String("test_case", "", "What test cases to run (tls, framing)")
// The rest of these are unused, but present to fulfill the client interface
serverHostOverride = flag.String("server_host_override", "", "Unused")
@@ -69,6 +69,9 @@ func (ctx *HTTP2InteropCtx) Close() error {
}
func TestShortPreface(t *testing.T) {
+ if *testCase != "framing" {
+ t.SkipNow()
+ }
ctx := InteropCtx(t)
for i := 0; i < len(Preface)-1; i++ {
if err := testShortPreface(ctx, Preface[:i]+"X"); err != io.EOF {
@@ -78,6 +81,9 @@ func TestShortPreface(t *testing.T) {
}
func TestUnknownFrameType(t *testing.T) {
+ if *testCase != "framing" {
+ t.SkipNow()
+ }
ctx := InteropCtx(t)
if err := testUnknownFrameType(ctx); err != nil {
t.Fatal(err)
@@ -86,7 +92,7 @@ func TestUnknownFrameType(t *testing.T) {
func TestTLSApplicationProtocol(t *testing.T) {
if *testCase != "tls" {
- return
+ t.SkipNow()
}
ctx := InteropCtx(t)
err := testTLSApplicationProtocol(ctx)
@@ -95,7 +101,7 @@ func TestTLSApplicationProtocol(t *testing.T) {
func TestTLSMaxVersion(t *testing.T) {
if *testCase != "tls" {
- return
+ t.SkipNow()
}
ctx := InteropCtx(t)
err := testTLSMaxVersion(ctx, tls.VersionTLS11)
@@ -106,7 +112,7 @@ func TestTLSMaxVersion(t *testing.T) {
func TestTLSBadCipherSuites(t *testing.T) {
if *testCase != "tls" {
- return
+ t.SkipNow()
}
ctx := InteropCtx(t)
err := testTLSBadCipherSuites(ctx)
@@ -114,6 +120,9 @@ func TestTLSBadCipherSuites(t *testing.T) {
}
func TestClientPrefaceWithStreamId(t *testing.T) {
+ if *testCase != "framing" {
+ t.SkipNow()
+ }
ctx := InteropCtx(t)
err := testClientPrefaceWithStreamId(ctx)
matchError(t, err, "EOF")
diff --git a/tools/run_tests/run_interop_tests.py b/tools/run_tests/run_interop_tests.py
index <HASH>..<HASH> 100755
--- a/tools/run_tests/run_interop_tests.py
+++ b/tools/run_tests/run_interop_tests.py
@@ -170,7 +170,7 @@ class Http2Client:
self.safename = str(self)
def client_args(self):
- return ['tools/http2_interop/http2_interop.test']
+ return ['tools/http2_interop/http2_interop.test', '-v']
def cloud_to_prod_env(self):
return {}
@@ -306,7 +306,7 @@ _TEST_CASES = ['large_unary', 'empty_unary', 'ping_pong',
_AUTH_TEST_CASES = ['compute_engine_creds', 'jwt_token_creds',
'oauth2_auth_token', 'per_rpc_creds']
-_HTTP2_TEST_CASES = ["tls"]
+_HTTP2_TEST_CASES = ["tls", "framing"]
def docker_run_cmdline(cmdline, image, docker_args=[], cwd=None, environ=None):
"""Wraps given cmdline array to create 'docker run' cmdline from it.""" | Add framing http2 test case, enable verbose output, and properly skip tests | grpc_grpc | train |
9b8c5db52e7b2c49bd2086e9beb080a83adcdbf6 | diff --git a/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/java/JavaGenerator.java b/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/java/JavaGenerator.java
index <HASH>..<HASH> 100644
--- a/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/java/JavaGenerator.java
+++ b/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/java/JavaGenerator.java
@@ -3475,6 +3475,9 @@ public class JavaGenerator implements CodeGenerator
final String groupName = formatPropertyName(groupToken.name());
final String groupDecoderName = decoderName(groupToken.name());
+ append(sb, indent, "int " + groupName + "OriginalOffset = " + groupName + ".offset;");
+ append(sb, indent, "int " + groupName + "OriginalIndex = " + groupName + ".index;");
+
append(
sb, indent, "builder.append(\"" + groupName + Separator.KEY_VALUE + Separator.BEGIN_GROUP + "\");");
append(sb, indent, groupDecoderName + " " + groupName + " = " + groupName + "();");
@@ -3489,6 +3492,9 @@ public class JavaGenerator implements CodeGenerator
append(sb, indent, "}");
Separator.END_GROUP.appendToGeneratedBuilder(sb, indent);
+ append(sb, indent, groupName + ".offset = " + groupName + "OriginalOffset;");
+ append(sb, indent, groupName + ".index = " + groupName + "OriginalIndex;");
+
lengthBeforeLastGeneratedSeparator = sb.length();
Separator.FIELD.appendToGeneratedBuilder(sb, indent); | toString() shouldn't disturb repeating groups #<I> (#<I>)
* toString() shouldn't disturb repeating groups #<I>
* Remove trailing whitespace
* Ugh, removed more whitespace | real-logic_simple-binary-encoding | train |
1ce5f2286562f89f707f74f8d63c6835539b97ba | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -39,7 +39,7 @@
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
- define(factory(window));
+ define([], factory(window));
} else if (typeof exports === 'object') {
if (typeof window === 'object' && window.DOMImplementation) {
// Browserify. hardcode usage of browser's own XMLDom implementation | Fixes broken AMD registration
I am not sure if it worked okay before in browsers, but r.js and almond
gave me all kinds of trouble until I changed this. | tyrasd_jxon | train |
f5ee8f7c51fd267fd8678a9d1f6bd72af593209b | diff --git a/src/consumer/runner.js b/src/consumer/runner.js
index <HASH>..<HASH> 100644
--- a/src/consumer/runner.js
+++ b/src/consumer/runner.js
@@ -30,7 +30,7 @@ module.exports = class Runner extends EventEmitter {
* @param {(payload: import("../../types").EachBatchPayload) => Promise<void>} options.eachBatch
* @param {(payload: import("../../types").EachMessagePayload) => Promise<void>} options.eachMessage
* @param {number} [options.heartbeatInterval]
- * @param {(reason: any) => PromiseLike<never>} [options.onCrash]
+ * @param {(reason: Error) => void} options.onCrash
* @param {import("../../types").RetryOptions} [options.retry]
* @param {boolean} [options.autoCommit=true]
*/ | squash: Refine the type for `onCrash` further
* Drop the return value: We don't do anything with it anyways, so the provider of that
handler shouldn't make any assumptions
* Refine the `reason` parameter to always be an 'Error' instance, and accept the minimal
risk that some downstream library does stupid things
* Make the `onCrash` property non-optional, as we do refer to ith without a guard | tulios_kafkajs | train |
61d173c803f167892c2b9e0481592908785d8d2e | diff --git a/glances/plugins/glances_cloud.py b/glances/plugins/glances_cloud.py
index <HASH>..<HASH> 100644
--- a/glances/plugins/glances_cloud.py
+++ b/glances/plugins/glances_cloud.py
@@ -149,6 +149,11 @@ class ThreadAwsEc2Grabber(threading.Thread):
"""Function called to grab stats.
Infinite loop, should be stopped by calling the stop() method"""
+ if not cloud_tag:
+ logger.debug("cloud plugin - Requests lib is not installed")
+ self.stop()
+ return False
+
for k, v in iteritems(self.AWS_EC2_API_METADATA):
r_url = '{}/{}'.format(self.AWS_EC2_API_URL, v)
try:
@@ -161,6 +166,8 @@ class ThreadAwsEc2Grabber(threading.Thread):
if r.ok:
self._stats[k] = r.content
+ return True
+
@property
def stats(self):
"""Stats getter""" | Clod plugin error Name 'requests' is not defined #<I> | nicolargo_glances | train |
3453db79bfa51c0e882784e85150476757e31612 | diff --git a/src/math/velocity.js b/src/math/velocity.js
index <HASH>..<HASH> 100644
--- a/src/math/velocity.js
+++ b/src/math/velocity.js
@@ -27,13 +27,13 @@ module.exports = {
step: function (t, dt) {
if (!dt) return;
- var physics = this.el.sceneEl.systems.physics || {maxInterval: 1 / 60},
+ var physics = this.el.sceneEl.systems.physics || {data: {maxInterval: 1 / 60}},
// TODO - There's definitely a bug with getComputedAttribute and el.data.
velocity = this.el.getAttribute('velocity') || {x: 0, y: 0, z: 0},
position = this.el.getAttribute('position') || {x: 0, y: 0, z: 0};
- dt = Math.min(dt, physics.maxInterval * 1000);
+ dt = Math.min(dt, physics.data.maxInterval * 1000);
this.el.setAttribute('position', {
x: position.x + velocity.x * dt / 1000,
diff --git a/src/physics/system/physics.js b/src/physics/system/physics.js
index <HASH>..<HASH> 100644
--- a/src/physics/system/physics.js
+++ b/src/physics/system/physics.js
@@ -8,20 +8,20 @@ var CANNON = require('cannon'),
*/
module.exports = {
schema: {
- gravity: { default: C_GRAV },
- friction: { default: C_MAT.friction },
- restitution: { default: C_MAT.restitution },
- contactEquationStiffness: { default: C_MAT.contactEquationStiffness },
- contactEquationRelaxation: { default: C_MAT.contactEquationRelaxation },
- frictionEquationStiffness: { default: C_MAT.frictionEquationStiffness },
- frictionEquationRegularization: { default: C_MAT.frictionEquationRegularization },
+ gravity: { default: C_GRAV },
+ friction: { default: C_MAT.friction },
+ restitution: { default: C_MAT.restitution },
+ contactEquationStiffness: { default: C_MAT.contactEquationStiffness },
+ contactEquationRelaxation: { default: C_MAT.contactEquationRelaxation },
+ frictionEquationStiffness: { default: C_MAT.frictionEquationStiffness },
+ frictionEquationRegularization: { default: C_MAT.frictionEquationRegularization },
// Never step more than four frames at once. Effectively pauses the scene
// when out of focus, and prevents weird "jumps" when focus returns.
- maxInterval: { default: 4 / 60 },
+ maxInterval: { default: 4 / 60 },
// If true, show wireframes around physics bodies.
- debug: { default: false },
+ debug: { default: false },
},
/**
@@ -53,7 +53,7 @@ module.exports = {
this.world.quatNormalizeFast = false;
// this.world.solver.setSpookParams(300,10);
this.world.solver.iterations = CONSTANTS.ITERATIONS;
- this.world.gravity.set(0, data.GRAVITY, 0);
+ this.world.gravity.set(0, data.gravity, 0);
this.world.broadphase = new CANNON.NaiveBroadphase();
this.material = new CANNON.Material({name: 'defaultMaterial'}); | Fixes for physics system. | donmccurdy_aframe-extras | train |
0a757da55a66c5930161c3928d1c3b2294f25b21 | diff --git a/Classes/TcaDataGenerator/RecordFinder.php b/Classes/TcaDataGenerator/RecordFinder.php
index <HASH>..<HASH> 100644
--- a/Classes/TcaDataGenerator/RecordFinder.php
+++ b/Classes/TcaDataGenerator/RecordFinder.php
@@ -87,7 +87,7 @@ class RecordFinder
)
->orderBy('pid', 'DESC')
->execute()
- ->fetch();
+ ->fetchAssociative();
if (count($row) !== 1) {
throw new Exception(
'Found no page for main table ' . $tableName, | [BUGFIX] Use of deprecated doctrine fetch() | TYPO3_styleguide | train |
e186e14f0d7cc944c31ec0135a844fb7fd629bb9 | diff --git a/sfm-jooq/src/main/java/org/simpleflatmapper/jooq/JooqFieldKey.java b/sfm-jooq/src/main/java/org/simpleflatmapper/jooq/JooqFieldKey.java
index <HASH>..<HASH> 100644
--- a/sfm-jooq/src/main/java/org/simpleflatmapper/jooq/JooqFieldKey.java
+++ b/sfm-jooq/src/main/java/org/simpleflatmapper/jooq/JooqFieldKey.java
@@ -1,6 +1,7 @@
package org.simpleflatmapper.jooq;
import org.jooq.Field;
+import org.simpleflatmapper.jdbc.JdbcTypeHelper;
import org.simpleflatmapper.map.FieldKey;
import org.simpleflatmapper.reflect.TypeAffinity;
import org.simpleflatmapper.util.TypeHelper;
@@ -62,6 +63,12 @@ public class JooqFieldKey extends FieldKey<JooqFieldKey> implements TypeAffinity
return java.sql.Array.class;
}
}
+
+ //FIXME: "some" test fail
+ Type mappedType = JdbcTypeHelper.toJavaType(field.getDataType().getSQLType(), targetType);
+ if (mappedType != null) {
+ return mappedType;
+ }
return type;
} | here the mapped type shall be returned | arnaudroger_SimpleFlatMapper | train |
63c697dcc3babcb262aff70dd19b7096641cf73d | diff --git a/src/Test/AbstractFixerTestCase.php b/src/Test/AbstractFixerTestCase.php
index <HASH>..<HASH> 100644
--- a/src/Test/AbstractFixerTestCase.php
+++ b/src/Test/AbstractFixerTestCase.php
@@ -42,7 +42,7 @@ abstract class AbstractFixerTestCase extends \PHPUnit_Framework_TestCase
*/
private $fixerClassName;
- public function setUp()
+ protected function setUp()
{
$this->linter = $this->getLinter();
$this->fixer = $this->createFixer();
diff --git a/src/Test/AbstractIntegrationTestCase.php b/src/Test/AbstractIntegrationTestCase.php
index <HASH>..<HASH> 100644
--- a/src/Test/AbstractIntegrationTestCase.php
+++ b/src/Test/AbstractIntegrationTestCase.php
@@ -90,7 +90,7 @@ abstract class AbstractIntegrationTestCase extends \PHPUnit_Framework_TestCase
self::$fileRemoval->delete($tmpFile);
}
- public function setUp()
+ protected function setUp()
{
$this->linter = $this->getLinter();
}
diff --git a/tests/Fixer/ClassNotation/OrderedClassElementsFixerTest.php b/tests/Fixer/ClassNotation/OrderedClassElementsFixerTest.php
index <HASH>..<HASH> 100644
--- a/tests/Fixer/ClassNotation/OrderedClassElementsFixerTest.php
+++ b/tests/Fixer/ClassNotation/OrderedClassElementsFixerTest.php
@@ -143,7 +143,7 @@ abstract class Foo extends FooParent implements FooInterface1, FooInterface2
} /* multiline
comment */
- public function setUp() {}
+ protected function setUp() {}
protected function tearDown() {}
@@ -236,7 +236,7 @@ abstract class Foo extends FooParent implements FooInterface1, FooInterface2
{
} // end foo5
- public function setUp() {}
+ protected function setUp() {}
protected function __construct()
{ | Fix: Reduce visibility of setUp() | FriendsOfPHP_PHP-CS-Fixer | train |
dd41f7e91a682b7c1ceed633e12ece6ba7b6bc72 | diff --git a/common.go b/common.go
index <HASH>..<HASH> 100644
--- a/common.go
+++ b/common.go
@@ -140,7 +140,7 @@ func readElements(r io.Reader, elements ...interface{}) error {
func writeElement(w io.Writer, element interface{}) error {
var scratch [8]byte
- // Attempt to read the element based on the concrete type via fast
+ // Attempt to write the element based on the concrete type via fast
// type assertions first.
switch e := element.(type) {
case int32:
@@ -238,6 +238,8 @@ func writeElement(w io.Writer, element interface{}) error {
return nil
}
+ // Fall back to the slower binary.Write if a fast path was not available
+ // above.
return binary.Write(w, binary.LittleEndian, element)
}
diff --git a/msgtx.go b/msgtx.go
index <HASH>..<HASH> 100644
--- a/msgtx.go
+++ b/msgtx.go
@@ -144,7 +144,7 @@ func (msg *MsgTx) AddTxOut(to *TxOut) {
}
// TxSha generates the ShaHash name for the transaction.
-func (tx *MsgTx) TxSha() (ShaHash, error) {
+func (msg *MsgTx) TxSha() (ShaHash, error) {
// Encode the transaction and calculate double sha256 on the result.
// Ignore the error returns since the only way the encode could fail
// is being out of memory or due to nil pointers, both of which would
@@ -153,7 +153,7 @@ func (tx *MsgTx) TxSha() (ShaHash, error) {
// regardless of input.
var buf bytes.Buffer
var sha ShaHash
- _ = tx.Serialize(&buf)
+ _ = msg.Serialize(&buf)
_ = sha.SetBytes(DoubleSha256(buf.Bytes()))
// Even though this function can't currently fail, it still returns
@@ -164,18 +164,18 @@ func (tx *MsgTx) TxSha() (ShaHash, error) {
// Copy creates a deep copy of a transaction so that the original does not get
// modified when the copy is manipulated.
-func (tx *MsgTx) Copy() *MsgTx {
+func (msg *MsgTx) Copy() *MsgTx {
// Create new tx and start by copying primitive values and making space
// for the transaction inputs and outputs.
newTx := MsgTx{
- Version: tx.Version,
- TxIn: make([]*TxIn, 0, len(tx.TxIn)),
- TxOut: make([]*TxOut, 0, len(tx.TxOut)),
- LockTime: tx.LockTime,
+ Version: msg.Version,
+ TxIn: make([]*TxIn, 0, len(msg.TxIn)),
+ TxOut: make([]*TxOut, 0, len(msg.TxOut)),
+ LockTime: msg.LockTime,
}
// Deep copy the old TxIn data.
- for _, oldTxIn := range tx.TxIn {
+ for _, oldTxIn := range msg.TxIn {
// Deep copy the old previous outpoint.
oldOutPoint := oldTxIn.PreviousOutpoint
newOutPoint := OutPoint{}
@@ -202,7 +202,7 @@ func (tx *MsgTx) Copy() *MsgTx {
}
// Deep copy the old TxOut data.
- for _, oldTxOut := range tx.TxOut {
+ for _, oldTxOut := range msg.TxOut {
// Deep copy the old PkScript
var newScript []byte
oldScript := oldTxOut.PkScript
diff --git a/shahash.go b/shahash.go
index <HASH>..<HASH> 100644
--- a/shahash.go
+++ b/shahash.go
@@ -18,7 +18,7 @@ const MaxHashStringSize = HashSize * 2
// ErrHashStrSize describes an error that indicates the caller specified a hash
// string that has too many characters.
-var ErrHashStrSize = fmt.Errorf("Max hash length is %v chars", MaxHashStringSize)
+var ErrHashStrSize = fmt.Errorf("max hash length is %v chars", MaxHashStringSize)
// ShaHash is used in several of the bitcoin messages and common structures. It
// typically represents the double sha256 of data. | Minor cleanup.
This commit fixes a couple of comments and cleans up a couple of things
golint complained about. | btcsuite_btcd | train |
ea1acd754d98341b66433bbc6e93c68bcb8d5a12 | diff --git a/lib/puppet/application/lookup.rb b/lib/puppet/application/lookup.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/application/lookup.rb
+++ b/lib/puppet/application/lookup.rb
@@ -17,6 +17,14 @@ class Puppet::Application::Lookup < Puppet::Application
end
end
+ option('--debug', '-d')
+
+ option('--verbose', '-v')
+
+ option('--render-as FORMAT') do |format|
+ options[:render_as] = format.downcase.to_sym
+ end
+
option('--type TYPE_STRING') do |arg|
options[:type] = arg
end
@@ -33,7 +41,6 @@ class Puppet::Application::Lookup < Puppet::Application
option('--merge-hash-arrays')
- # not yet supported
option('--explain')
option('--default VALUE') do |arg|
@@ -69,8 +76,6 @@ class Puppet::Application::Lookup < Puppet::Application
raise "The options #{DEEP_MERGE_OPTIONS} are only available with '--merge deep'\n#{RUN_HELP}"
end
- scope = generate_scope
-
use_default_value = !options[:default_value].nil?
merge_options = nil
@@ -93,13 +98,31 @@ class Puppet::Application::Lookup < Puppet::Application
end
end
- puts Puppet::Pops::Lookup.lookup(keys, options[:type], options[:default_value], use_default_value, merge_options, Puppet::Pops::Lookup::Invocation.new(scope, {}, {}))
+ explain = !!options[:explain]
+
+ # Format defaults to text (:s) when producing an explanation and :yaml when producing the value
+ format = options[:render_as] || (explain ? :s : :yaml)
+ renderer = Puppet::Network::FormatHandler.format(format == :json ? :pson : format)
+ raise "Unknown rendering format '#{format}'" if renderer.nil?
+
+ type = options.include?(:type) ? Puppet::Pops::Types::TypeParser.new.parse(options[:type]) : nil
+
+ generate_scope do |scope|
+ lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}, explain)
+ begin
+ result = Puppet::Pops::Lookup.lookup(keys, type, options[:default_value], use_default_value, merge_options, lookup_invocation)
+ puts renderer.render(result) unless explain
+ rescue Puppet::Error => e
+ raise unless e.message =~ /lookup\(\) did not find a value/
+ exit(1) unless explain
+ end
+ puts format == :s ? lookup_invocation.explainer.to_s : renderer.render(lookup_invocation.explainer.to_hash) if explain
+ end
end
def generate_scope
node = Puppet::Node.indirection.find("#{options[:node]}")
compiler = Puppet::Parser::Compiler.new(node)
- compiler.compile
- compiler.topscope
+ compiler.compile { |catalog| yield(compiler.topscope); catalog }
end
end
diff --git a/spec/unit/application/lookup_spec.rb b/spec/unit/application/lookup_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/application/lookup_spec.rb
+++ b/spec/unit/application/lookup_spec.rb
@@ -37,14 +37,29 @@ describe Puppet::Application::Lookup do
context "when running with correct command line options" do
let (:lookup) { Puppet::Application[:lookup] }
+ it "calls the lookup method with the correct arguments" do
+ lookup.options[:node] = 'dantooine.local'
+ lookup.options[:render_as] = :s;
+ lookup.options[:merge_hash_arrays] = true
+ lookup.options[:merge] = 'deep'
+ lookup.command_line.stubs(:args).returns(['atton', 'kreia'])
+ lookup.stubs(:generate_scope).yields('scope')
+
+ expected_merge = {"strategy"=> "deep", "sort_merge_arrays"=> false, "merge_hash_arrays"=> true}
+
+ (Puppet::Pops::Lookup).expects(:lookup).with(['atton', 'kreia'], nil, nil, false, expected_merge, anything).returns('rand')
+
+ expect{ lookup.run_command }.to output("rand\n").to_stdout
+ end
+
it "prints the value found by lookup" do
lookup.options[:node] = 'dantooine.local'
lookup.command_line.stubs(:args).returns(['atton', 'kreia'])
- lookup.stubs(:generate_scope).returns('scope')
+ lookup.stubs(:generate_scope).yields('scope')
Puppet::Pops::Lookup.stubs(:lookup).returns('rand')
- expect{ lookup.run_command }.to output("rand\n").to_stdout
+ expect{ lookup.run_command }.to output("--- rand\n...\n").to_stdout
end
end
end | (PUP-<I>) Improve ability to control output rendering
This commit adds a 'render-as' command line option. The format
will be mapped to one of the renderers registered with
`Puppet::Network::FormatHandler` which then will be used when
rendering the result.
The default format will be 'yaml' when rendering the result of a
lookup and 's' (text) when rendering an explanation. | puppetlabs_puppet | train |
77a9c6525fc10e3a15c837bf5d494e65e314bf94 | diff --git a/http-client/src/main/java/io/airlift/http/client/jetty/JettyIoPoolConfig.java b/http-client/src/main/java/io/airlift/http/client/jetty/JettyIoPoolConfig.java
index <HASH>..<HASH> 100644
--- a/http-client/src/main/java/io/airlift/http/client/jetty/JettyIoPoolConfig.java
+++ b/http-client/src/main/java/io/airlift/http/client/jetty/JettyIoPoolConfig.java
@@ -1,6 +1,7 @@
package io.airlift.http.client.jetty;
import io.airlift.configuration.Config;
+import io.airlift.configuration.LegacyConfig;
import javax.validation.constraints.Min;
@@ -16,6 +17,7 @@ public class JettyIoPoolConfig
}
@Config("http-client.max-threads")
+ @LegacyConfig("http-client.threads")
public JettyIoPoolConfig setMaxThreads(int maxThreads)
{
this.maxThreads = maxThreads;
diff --git a/http-client/src/test/java/io/airlift/http/client/jetty/TestJettyIoPoolConfig.java b/http-client/src/test/java/io/airlift/http/client/jetty/TestJettyIoPoolConfig.java
index <HASH>..<HASH> 100644
--- a/http-client/src/test/java/io/airlift/http/client/jetty/TestJettyIoPoolConfig.java
+++ b/http-client/src/test/java/io/airlift/http/client/jetty/TestJettyIoPoolConfig.java
@@ -30,4 +30,18 @@ public class TestJettyIoPoolConfig
ConfigAssertions.assertFullMapping(properties, expected);
}
+
+ @Test
+ public void testDeprecatedProperties()
+ {
+ Map<String, String> currentProperties = new ImmutableMap.Builder<String, String>()
+ .put("http-client.max-threads", "111")
+ .build();
+
+ Map<String, String> oldProperties = new ImmutableMap.Builder<String, String>()
+ .put("http-client.threads", "111")
+ .build();
+
+ ConfigAssertions.assertDeprecatedEquivalence(JettyIoPoolConfig.class, currentProperties, oldProperties);
+ }
} | Add back support for legacy http-client.threads config | airlift_airlift | train |
2976ad5ac788516b40028e3e6e67d319169980eb | diff --git a/py/selenium/webdriver/remote/webelement.py b/py/selenium/webdriver/remote/webelement.py
index <HASH>..<HASH> 100755
--- a/py/selenium/webdriver/remote/webelement.py
+++ b/py/selenium/webdriver/remote/webelement.py
@@ -385,10 +385,7 @@ class WebElement(object):
return self._id
def __eq__(self, element):
- if self._id == element.id:
- return True
- else:
- return self._execute(Command.ELEMENT_EQUALS, {'other': element.id})['value']
+ return self._id == element.id
# Private Methods
def _execute(self, command, params=None):
diff --git a/rb/lib/selenium/webdriver/remote/bridge.rb b/rb/lib/selenium/webdriver/remote/bridge.rb
index <HASH>..<HASH> 100755
--- a/rb/lib/selenium/webdriver/remote/bridge.rb
+++ b/rb/lib/selenium/webdriver/remote/bridge.rb
@@ -582,11 +582,7 @@ module Selenium
end
def elementEquals(element, other)
- if element.ref == other.ref
- true
- else
- execute :elementEquals, :id => element.ref, :other => other.ref
- end
+ element.ref == other.ref
end
# | py,rb: Comparing remote web element for equality does not require a remote command, comparing IDs is enough | SeleniumHQ_selenium | train |
deaa1e64755b7310dd26db1f61efea9ff474ec68 | diff --git a/src/LeagueWrap/Api/AbstractApi.php b/src/LeagueWrap/Api/AbstractApi.php
index <HASH>..<HASH> 100644
--- a/src/LeagueWrap/Api/AbstractApi.php
+++ b/src/LeagueWrap/Api/AbstractApi.php
@@ -351,9 +351,17 @@ abstract class AbstractApi {
{
if ($identity instanceof Summoner)
{
- $id = $identity->id;
- $response = $responses[$id];
- $this->attachResponse($identity, $response, $key);
+ $id = $identity->id;
+ if (isset($responses[$id]))
+ {
+ $response = $responses[$id];
+ $this->attachResponse($identity, $response, $key);
+ }
+ else
+ {
+ // we did not get a response for this id, attach null
+ $this->attachResponse($identity, null, $key);
+ }
}
}
}
@@ -362,9 +370,17 @@ abstract class AbstractApi {
$identity = $identities;
if ($identity instanceof Summoner)
{
- $id = $identity->id;
- $response = $responses[$id];
- $this->attachResponse($identity, $response, $key);
+ $id = $identity->id;
+ if (isset($responses[$id]))
+ {
+ $response = $responses[$id];
+ $this->attachResponse($identity, $response, $key);
+ }
+ else
+ {
+ // we did not get a response for this id, attach null
+ $this->attachResponse($identity, null, $key);
+ }
}
}
diff --git a/src/LeagueWrap/Api/League.php b/src/LeagueWrap/Api/League.php
index <HASH>..<HASH> 100644
--- a/src/LeagueWrap/Api/League.php
+++ b/src/LeagueWrap/Api/League.php
@@ -40,12 +40,15 @@ class League extends AbstractApi {
protected $defaultRemember = 43200;
/**
- * Gets the league information by summoner id or list of summoner ids.
+ * Gets the league information by summoner id or list of summoner ids. To only
+ * get the single entry information for the summoner(s) ensure that $entry
+ * is set to true.
*
* @param mixed $identity
+ * @param bool $entry
* @return array
*/
- public function league($identities)
+ public function league($identities, $entry = false)
{
if (is_array($identities))
{
@@ -57,17 +60,28 @@ class League extends AbstractApi {
$ids = $this->extractIds($identities);
$ids = implode(',', $ids);
- $array = $this->request('league/by-summoner/'.$ids);
+ if ($entry)
+ {
+ $ids .= '/entry';
+ }
+ $array = $this->request('league/by-summoner/'.$ids);
$summoners = [];
- foreach($array as $id => $summonerLeagues)
+ foreach ($array as $id => $summonerLeagues)
{
$leagues = [];
foreach ($summonerLeagues as $info)
{
- $key = $info['participantId'];
- $info['id'] = $key;
- $league = new Dto\League($info);
+ if (isset($info['participantId']))
+ {
+ $key = $info['participantId'];
+ $info['id'] = $key;
+ }
+ else
+ {
+ $info['id'] = $id;
+ }
+ $league = new Dto\League($info);
if ( ! is_null($league->playerOrTeam))
{
$key = $league->playerOrTeam->playerOrTeamName;
@@ -79,10 +93,26 @@ class League extends AbstractApi {
$this->attachResponses($identities, $summoners, 'leagues');
- if(count($summoners) == 1)
- return reset($summoners);
- else
+ if(is_array($identities))
+ {
return $summoners;
+ }
+ else
+ {
+ return reset($summoners);
+ }
}
+ /**
+ * Gets the league information for the challenger teams.
+ *
+ * @param string $type
+ * @return array
+ */
+ public function challenger($type = 'RANKED_SOLO_5x5')
+ {
+ $info = $this->request('league/challenger', ['type' => $type]);
+ $info['id'] = null;
+ return new Dto\League($info);
+ }
} | Updated the League Api to contain the entry and challenger calls | paquettg_leaguewrap | train |
04e2a2fa41c4a479a747ff070d53af9af1e27db9 | diff --git a/aiohttp/client.py b/aiohttp/client.py
index <HASH>..<HASH> 100644
--- a/aiohttp/client.py
+++ b/aiohttp/client.py
@@ -329,7 +329,7 @@ class ClientSession:
resp = req.send(conn)
try:
await resp.start(conn, read_until_eof)
- except Exception:
+ except BaseException:
resp.close()
conn.close()
raise
@@ -425,7 +425,7 @@ class ClientSession:
)
return resp
- except Exception as e:
+ except BaseException as e:
# cleanup timer
tm.close()
if handle:
@@ -611,7 +611,7 @@ class ClientSession:
writer = WebSocketWriter(
proto, transport, use_mask=True,
compress=compress, notakeover=notakeover)
- except Exception:
+ except BaseException:
resp.close()
raise
else:
diff --git a/aiohttp/client_reqrep.py b/aiohttp/client_reqrep.py
index <HASH>..<HASH> 100644
--- a/aiohttp/client_reqrep.py
+++ b/aiohttp/client_reqrep.py
@@ -796,7 +796,7 @@ class ClientResponse(HeadersMixin):
if self._content is None:
try:
self._content = await self.content.read()
- except Exception:
+ except BaseException:
self.close()
raise
diff --git a/aiohttp/connector.py b/aiohttp/connector.py
index <HASH>..<HASH> 100644
--- a/aiohttp/connector.py
+++ b/aiohttp/connector.py
@@ -420,7 +420,7 @@ class BaseConnector:
if self._closed:
proto.close()
raise ClientConnectionError("Connector is closed.")
- except Exception:
+ except BaseException:
# signal to waiter
if key in self._waiters:
for waiter in self._waiters[key]:
@@ -710,7 +710,7 @@ class TCPConnector(BaseConnector):
self._cached_hosts.add(key, addrs)
self._throttle_dns_events[key].set()
- except Exception as e:
+ except BaseException as e:
# any DNS exception, independently of the implementation
# is set for the waiters to raise the same exception.
self._throttle_dns_events[key].set(exc=e)
@@ -896,7 +896,7 @@ class TCPConnector(BaseConnector):
proxy_resp = proxy_req.send(conn)
try:
resp = await proxy_resp.start(conn, True)
- except Exception:
+ except BaseException:
proxy_resp.close()
conn.close()
raise | Fix #<I>: Properly handle BaseException when re-raising | aio-libs_aiohttp | train |
a58e81ef45b6ea7c24dd3586727dc4e9da5f9e13 | diff --git a/android/lib/AndroidPlatform.js b/android/lib/AndroidPlatform.js
index <HASH>..<HASH> 100644
--- a/android/lib/AndroidPlatform.js
+++ b/android/lib/AndroidPlatform.js
@@ -97,7 +97,8 @@ function(output, callback) {
var deps = [
"android",
"ant",
- "java"
+ "java",
+ "lzma"
];
var found = true;
@@ -1200,6 +1201,37 @@ function() {
};
/**
+ * Wrapper for ChildProcess.execSync to preserve some support for nodejs 0.10
+ * This can probably go away with Fedora 23.
+ */
+AndroidPlatform.prototype.execSync =
+function(cmd) {
+
+ var execSyncImpl;
+ if (ChildProcess.execSync) {
+ // Nodejs >= 0.12
+ execSyncImpl = ChildProcess.execSync;
+ } else {
+ // Try to use npm module.
+ try {
+ // Exec-sync does throw even though it works, so let's use this hack,
+ // it's just for nodejs 0.10 compat anyway.
+ execSyncImpl = function(cmd) { try { return require("exec-sync")(cmd); } catch (e) {} return null; };
+ } catch (e) {
+ output.error("NPM module 'exec-sync' not found");
+ output.error("Please install this package manually when on nodejs < 0.12");
+ execSyncImpl = null;
+ }
+ }
+
+ if (execSyncImpl !== null) {
+ return execSyncImpl(cmd);
+ }
+
+ return null;
+};
+
+/**
* Import extensions.
* The directory of one external extension should be like:
* myextension/
@@ -1308,8 +1340,20 @@ function(configId, args, callback) {
ShellJS.ls(libPath).forEach(function (lib) {
if (ShellJS.test("-d", Path.join(libPath, lib))) {
abis.push(lib);
+ // Extract lzma libxwalkcore, because we are not supporting
+ // compressed runtime yet.
+ lzmaLibPath = Path.join(libPath, lib, "libxwalkcore.so.lzma");
+ if (ShellJS.test("-f", lzmaLibPath)) {
+ if (!ShellJS.which("lzma")) {
+ var message = "the lzma utility is needed for crosswalk-lite";
+ output.error(message);
+ throw new Error(message);
+ }
+ output.info("lzma -d ", lzmaLibPath);
+ this.execSync("lzma -d " + lzmaLibPath);
+ }
}
- });
+ }.bind(this));
}
this.updateEngine(); | Android: Implement support for crosswalk-lite
The parameter for crosswalk-pkg is --android="lite",
for crosswalk-app use --android-shared.
Compressed runtime (XWALK-<I>) is not supported yet.
BUG=XWALK-<I> | crosswalk-project_crosswalk-app-tools | train |
255b627f395c5e658862cf716291a6299f997cb7 | diff --git a/src/core/vdom/patch.js b/src/core/vdom/patch.js
index <HASH>..<HASH> 100644
--- a/src/core/vdom/patch.js
+++ b/src/core/vdom/patch.js
@@ -234,7 +234,9 @@ export function createPatchFunction (backend) {
function insert (parent, elm, ref) {
if (isDef(parent)) {
if (isDef(ref)) {
- nodeOps.insertBefore(parent, elm, ref)
+ if (ref.parentNode === parent) {
+ nodeOps.insertBefore(parent, elm, ref)
+ }
} else {
nodeOps.appendChild(parent, elm)
}
diff --git a/test/unit/features/component/component.spec.js b/test/unit/features/component/component.spec.js
index <HASH>..<HASH> 100644
--- a/test/unit/features/component/component.spec.js
+++ b/test/unit/features/component/component.spec.js
@@ -366,4 +366,46 @@ describe('Component', () => {
Vue.config.errorHandler = null
}).then(done)
})
+
+ it('relocates node without error', done => {
+ const el = document.createElement('div')
+ document.body.appendChild(el)
+ const target = document.createElement('div')
+ document.body.appendChild(target)
+
+ const Test = {
+ render (h) {
+ return h('div', { class: 'test' }, this.$slots.default)
+ },
+ mounted () {
+ target.appendChild(this.$el)
+ },
+ beforeDestroy () {
+ const parent = this.$el.parentNode
+ if (parent) {
+ parent.removeChild(this.$el)
+ }
+ }
+ }
+ const vm = new Vue({
+ data () {
+ return {
+ view: true
+ }
+ },
+ template: `<div><test v-if="view">Test</test></div>`,
+ components: {
+ test: Test
+ }
+ }).$mount(el)
+
+ expect(el.outerHTML).toBe('<div></div>')
+ expect(target.outerHTML).toBe('<div><div class="test">Test</div></div>')
+ vm.view = false
+ waitForUpdate(() => {
+ expect(el.outerHTML).toBe('<div></div>')
+ expect(target.outerHTML).toBe('<div></div>')
+ vm.$destroy()
+ }).then(done)
+ })
}) | fix #<I> don't throw error when node gets relocated (#<I>)
* don't throw error when node gets relocated
* perf: Simplify if check in vdom/patch | IOriens_wxml-transpiler | train |
044104be97904587c5afaf06b99bff79eec8541f | diff --git a/src/serializer.js b/src/serializer.js
index <HASH>..<HASH> 100644
--- a/src/serializer.js
+++ b/src/serializer.js
@@ -8,6 +8,12 @@ export const reader = () => transit.reader('json', {
u: rep => new UUID(rep),
// Convert keywords to plain strings
+ //
+ // TODO This is problematic. When we convert keywords to strings,
+ // we lose the information that the string was originally a
+ // keyword. Thus, `read(write(data)) !== data`. Is this a bad thing,
+ // I don't know yet? Can we make the server to threat Strings as if
+ // they were keywords, that's an open question.
':': rep => rep,
},
arrayBuilder: {
@@ -29,4 +35,13 @@ export const reader = () => transit.reader('json', {
},
});
-export const writer = () => transit.writer('json');
+const uuidHandler = transit.makeWriteHandler({
+ tag: () => 'u',
+ rep: v => v.uuid,
+});
+
+export const writer = () => transit.writer('json', {
+ handlers: transit.map([
+ UUID, uuidHandler,
+ ]),
+});
diff --git a/src/serializer.test.js b/src/serializer.test.js
index <HASH>..<HASH> 100644
--- a/src/serializer.test.js
+++ b/src/serializer.test.js
@@ -1,4 +1,5 @@
import { reader, writer } from './serializer';
+import { UUID } from './types';
describe('serializer', () => {
it('reads and writes transit', () => {
@@ -16,5 +17,16 @@ describe('serializer', () => {
expect(r.read(w.write(testData))).toEqual(testData);
});
+
+ it('handles UUIDs', () => {
+ const testData = {
+ id: new UUID('69c3d77a-db3f-11e6-bf26-cec0c932ce01'),
+ };
+
+ const r = reader();
+ const w = writer();
+
+ expect(r.read(w.write(testData))).toEqual(testData);
+ });
}); | Add UUID tests and UUID writer | sharetribe_flex-sdk-js | train |
8ab8b73b2c9fd6117dd8c072de38e7adee618b2a | diff --git a/bench/format/format.py b/bench/format/format.py
index <HASH>..<HASH> 100644
--- a/bench/format/format.py
+++ b/bench/format/format.py
@@ -165,6 +165,7 @@ class dbench():
# Plot the qps data
qps_data.plot(os.path.join(self.out_dir, self.dir_str, 'qps' + run_name))
+ qps_data.plot(os.path.join(self.out_dir, self.dir_str, 'qps' + run_name + '_large'), True)
# Add the qps plot image and metadata
print >>res, '<table style="width: 910px;" class="runPlots">'
diff --git a/bench/format/plot.py b/bench/format/plot.py
index <HASH>..<HASH> 100644
--- a/bench/format/plot.py
+++ b/bench/format/plot.py
@@ -176,11 +176,14 @@ class TimeSeriesCollection():
fig.set_dpi(300)
plt.savefig(out_fname + '_large')
- def plot(self, out_fname, normalize = False):
+ def plot(self, out_fname, large = False, normalize = False):
assert self.data
queries_formatter = FuncFormatter(lambda x, pos: '%1.fk' % (x*1e-3))
- font = fm.FontProperties(family=['sans-serif'],size='small',fname='/usr/share/fonts/truetype/aurulent_sans_regular.ttf')
+ if not large:
+ font = fm.FontProperties(family=['sans-serif'],size='small',fname='/usr/share/fonts/truetype/aurulent_sans_regular.ttf')
+ else:
+ font = fm.FontProperties(family=['sans-serif'],size=36,fname='/usr/share/fonts/truetype/aurulent_sans_regular.ttf')
fig = plt.figure()
# Set the margins for the plot to ensure a minimum of whitespace
ax = plt.axes([0.13,0.12,0.85,0.85])
@@ -209,12 +212,14 @@ class TimeSeriesCollection():
ax.set_ylim(0, max(self.data[self.data.keys()[0]]))
ax.grid(True)
plt.legend(tuple(map(lambda x: x[0], labels)), tuple(map(lambda x: x[1], labels)), loc=1, prop = font)
- fig.set_size_inches(5,3.7)
- fig.set_dpi(90)
- plt.savefig(out_fname, bbox_inches="tight")
- fig.set_size_inches(20,14.8)
- fig.set_dpi(300)
- plt.savefig(out_fname + '_large', bbox_inches="tight")
+ if not large:
+ fig.set_size_inches(5,3.7)
+ fig.set_dpi(90)
+ plt.savefig(out_fname, bbox_inches="tight")
+ else:
+ fig.set_size_inches(20,14.8)
+ fig.set_dpi(300)
+ plt.savefig(out_fname, bbox_inches="tight")
def stats(self):
res = {} | Bigger fonts on large graphs. | rethinkdb_rethinkdb | train |
add63e0c4c47a2d8dc622c6fd61dbede73b6d2e1 | diff --git a/lib/thinking_sphinx/middlewares/active_record_translator.rb b/lib/thinking_sphinx/middlewares/active_record_translator.rb
index <HASH>..<HASH> 100644
--- a/lib/thinking_sphinx/middlewares/active_record_translator.rb
+++ b/lib/thinking_sphinx/middlewares/active_record_translator.rb
@@ -49,7 +49,7 @@ class ThinkingSphinx::Middlewares::ActiveRecordTranslator <
def result_for(row)
results_for_models[row['sphinx_internal_class']].detect { |record|
- record.id == row['sphinx_internal_id']
+ record.public_send(context.configuration.settings['primary_key'] || model.primary_key || :id) == row['sphinx_internal_id']
}
end | Also updating `result_for` method in order to detect different primary_key | pat_thinking-sphinx | train |
9abb21bfe18fd1b7bc9297d3ac704906ddd962b2 | diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -1,5 +1,4 @@
var gutil = require('gulp-util')
- , Stream = require('stream')
, duplexer = require('plexer')
, svgicons2svgfont = require('gulp-svgicons2svgfont')
, svg2ttf = require('gulp-svg2ttf') | Removed stream require closes#8 | nfroidure_gulp-iconfont | train |
359947db548879500b1fbc1582fc2d41baddbfa6 | diff --git a/ykman/piv.py b/ykman/piv.py
index <HASH>..<HASH> 100644
--- a/ykman/piv.py
+++ b/ykman/piv.py
@@ -258,7 +258,7 @@ class SW(IntEnum):
@staticmethod
def is_verify_fail(sw):
- return 0x63c0 <= sw <= 0x63c3
+ return 0x63c0 <= sw <= 0x63cf
@staticmethod
def tries_left(sw): | Expand is_verify_fail to include all 0x<I>cX status words | Yubico_yubikey-manager | train |
6c66604fefdc5ac852291d613283193965e3abb7 | diff --git a/redis_metrics/static/redis_metrics/js/colors.js b/redis_metrics/static/redis_metrics/js/colors.js
index <HASH>..<HASH> 100644
--- a/redis_metrics/static/redis_metrics/js/colors.js
+++ b/redis_metrics/static/redis_metrics/js/colors.js
@@ -15,23 +15,23 @@ var Color = function(index) {
var colors = [
"255,102,102", // Red
"255,178,102", // Orange
- "255,255,102", // Yellow
"102,255,102", // Green
- "102,255,255", // Turquoise
"102,102,255", // Blue
+ "102,255,255", // Turquoise
"178,102,255", // Purple
"255,102,178", // Pink
+ "204,204,0", // Yellow
];
// Highlight Colors
var hl_colors = [
"255,0,0", // Red
"255,128,0", // Orange,
- "255,255,0", // Yellow
"0,255,0", // Green
- "0,255,255", // Turquoise
"0,0,255", // Blue
+ "0,255,255", // Turquoise
"127,0,255", // Purple
"255,0,127", // Pink
+ "255,255,0", // Yellow
];
return { | move yellow to the back of the list of colors, and darken it a bit because it's difficul to see. | bradmontgomery_django-redis-metrics | train |
7f86ce17bace28ff51e8b1e438221a562c32b651 | diff --git a/lib/moodlelib.php b/lib/moodlelib.php
index <HASH>..<HASH> 100644
--- a/lib/moodlelib.php
+++ b/lib/moodlelib.php
@@ -909,8 +909,12 @@ function email_to_user($user, $from, $subject, $messagetext, $messagehtml="", $a
$mail->Version = "Moodle"; // mailer version
$mail->PluginDir = "$CFG->libdir/phpmailer/"; // plugin directory (eg smtp plugin)
- $mail->IsSMTP(); // set mailer to use SMTP
- $mail->Host = "$CFG->smtphosts"; // specify main and backup servers
+ if ($CFG->smtphosts) {
+ $mail->IsSMTP(); // use SMTP directly
+ $mail->Host = "$CFG->smtphosts"; // specify main and backup servers
+ } else {
+ $mail->IsMail(); // use PHP mail() = sendmail
+ }
$mail->From = "$from->email";
$mail->FromName = "$from->firstname $from->lastname"; | If $CFG->smtphosts is empty, then mailer uses PHP mail() == sendmail. | moodle_moodle | train |
a51982819d9b7dc9685f003125bfc35e98112ef3 | diff --git a/assess_model_migration.py b/assess_model_migration.py
index <HASH>..<HASH> 100755
--- a/assess_model_migration.py
+++ b/assess_model_migration.py
@@ -5,6 +5,7 @@ from __future__ import print_function
import argparse
from contextlib import contextmanager
+from distutils.version import LooseVersion
import logging
import os
from subprocess import CalledProcessError
@@ -91,6 +92,10 @@ def client_is_at_least_2_1(client):
return not isinstance(client, ModelClient2_0)
+def after_22beta4(client_version):
+ return LooseVersion(client_version) >= LooseVersion('2.2-beta4')
+
+
def parse_args(argv):
"""Parse all arguments."""
parser = argparse.ArgumentParser(
@@ -337,9 +342,15 @@ def ensure_superuser_can_migrate_other_user_models(
attempt_client.env.environment,
attempt_client.env.user_name)
- source_client.controller_juju(
- 'migrate',
- (user_qualified_model_name, dest_client.env.controller.name))
+ if after_22beta4(source_client.version):
+ source_client.juju(
+ 'migrate',
+ (user_qualified_model_name, dest_client.env.controller.name),
+ include_e=False)
+ else:
+ source_client.controller_juju(
+ 'migrate',
+ (user_qualified_model_name, dest_client.env.controller.name))
migration_client = dest_client.clone(
dest_client.env.clone(user_qualified_model_name))
@@ -394,12 +405,30 @@ def migrate_model_to_controller(
source_client, dest_client, include_user_name=False):
log.info('Initiating migration process')
if include_user_name:
- model_name = '{}/{}'.format(
- source_client.env.user_name, source_client.env.environment)
+ if after_22beta4(source_client.version):
+ model_name = '{}:{}/{}'.format(
+ source_client.env.controller.name,
+ source_client.env.user_name,
+ source_client.env.environment)
+ else:
+ model_name = '{}/{}'.format(
+ source_client.env.user_name, source_client.env.environment)
else:
- model_name = source_client.env.environment
- source_client.controller_juju(
- 'migrate', (model_name, dest_client.env.controller.name))
+ if after_22beta4(source_client.version):
+ model_name = '{}:{}'.format(
+ source_client.env.controller.name,
+ source_client.env.environment)
+ else:
+ model_name = source_client.env.environment
+
+ if after_22beta4(source_client.version):
+ source_client.juju(
+ 'migrate',
+ (model_name, dest_client.env.controller.name),
+ include_e=False)
+ else:
+ source_client.controller_juju(
+ 'migrate', (model_name, dest_client.env.controller.name))
migration_target_client = dest_client.clone(
dest_client.env.clone(source_client.env.environment))
wait_for_model(migration_target_client, source_client.env.environment)
@@ -490,10 +519,15 @@ def ensure_migration_rolls_back_on_failure(source_client, dest_client):
"""
test_model, application = deploy_simple_server_to_new_model(
source_client, 'rollmeback')
- test_model.controller_juju(
- 'migrate',
- (test_model.env.environment,
- dest_client.env.controller.name))
+ if after_22beta4(source_client.version):
+ test_model.juju(
+ 'migrate',
+ (test_model.env.environment, dest_client.env.controller.name),
+ include_e=False)
+ else:
+ test_model.controller_juju(
+ 'migrate',
+ (test_model.env.environment, dest_client.env.controller.name))
# Once migration has started interrupt it
wait_for_migrating(test_model)
log.info('Disrupting target controller to force rollback')
@@ -599,9 +633,19 @@ def expect_migration_attempt_to_fail(source_client, dest_client):
appears in test logs.
"""
try:
- args = ['-c', source_client.env.controller.name,
+ if after_22beta4(source_client.version):
+ args = [
+ '{}:{}'.format(
+ source_client.env.controller.name,
+ source_client.env.environment),
+ dest_client.env.controller.name
+ ]
+ else:
+ args = [
+ '-c', source_client.env.controller.name,
source_client.env.environment,
- dest_client.env.controller.name]
+ dest_client.env.controller.name
+ ]
log_output = source_client.get_juju_output(
'migrate', *args, merge_stderr=True, include_e=False)
except CalledProcessError as e:
diff --git a/tests/test_assess_model_migration.py b/tests/test_assess_model_migration.py
index <HASH>..<HASH> 100644
--- a/tests/test_assess_model_migration.py
+++ b/tests/test_assess_model_migration.py
@@ -88,6 +88,20 @@ class TestParseArgs(TestCase):
"Test model migration feature", fake_stdout.getvalue())
+class TestAfter22Beta4(TestCase):
+
+ def test_returns_True_when_newer(self):
+ self.assertTrue(amm.after_22beta4('2.2-beta8-xenial-amd64'))
+ self.assertTrue(amm.after_22beta4('2.3-beta4-xenial-amd64'))
+
+ def test_returns_True_when_equal(self):
+ self.assertTrue(amm.after_22beta4('2.2-beta4-xenial-amd64'))
+
+ def test_returns_False_when_older(self):
+ self.assertFalse(amm.after_22beta4('2.1-beta8-xenial-amd64'))
+ self.assertFalse(amm.after_22beta4('2.2-beta2-xenial-amd64'))
+
+
class TestDeploySimpleResourceServer(TestCase):
def test_deploys_with_resource(self): | Make migrations work with new changes to migrate command (no longer using -c) | juju_juju | train |
a6cc4cd4726f534960ea5042fe8d7650df19cf3f | diff --git a/src/de/mrapp/android/preference/activity/view/ToolbarLarge.java b/src/de/mrapp/android/preference/activity/view/ToolbarLarge.java
index <HASH>..<HASH> 100644
--- a/src/de/mrapp/android/preference/activity/view/ToolbarLarge.java
+++ b/src/de/mrapp/android/preference/activity/view/ToolbarLarge.java
@@ -28,6 +28,7 @@ import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.util.AttributeSet;
+import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
@@ -356,6 +357,11 @@ public class ToolbarLarge extends FrameLayout {
shadowView.setVisibility(navigationHidden ? View.GONE : View.VISIBLE);
titleTextView.setVisibility(navigationHidden ? View.INVISIBLE
: View.VISIBLE);
+ float breadCrumbTextSize = getResources().getDimension(
+ navigationHidden ? R.dimen.toolbar_title_text_size
+ : R.dimen.bread_crumb_text_size);
+ breadCrumbTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
+ breadCrumbTextSize);
if (navigationHidden) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) overlayView | The bread crumb on tablets does now appear to be the activity's main title when the navigation is hidden. | michael-rapp_AndroidPreferenceActivity | train |
1ae58f038618b68912f4cd8ee83c42964ab91693 | diff --git a/src/Psalm/Checker/Statements/Expression/Fetch/ConstFetchChecker.php b/src/Psalm/Checker/Statements/Expression/Fetch/ConstFetchChecker.php
index <HASH>..<HASH> 100644
--- a/src/Psalm/Checker/Statements/Expression/Fetch/ConstFetchChecker.php
+++ b/src/Psalm/Checker/Statements/Expression/Fetch/ConstFetchChecker.php
@@ -21,7 +21,7 @@ class ConstFetchChecker
* @param PhpParser\Node\Expr\ConstFetch $stmt
* @param Context $context
*
- * @return false|null
+ * @return void
*/
public static function analyze(
StatementsChecker $statements_checker,
@@ -65,12 +65,10 @@ class ConstFetchChecker
),
$statements_checker->getSuppressedIssues()
)) {
- return false;
+ // fall through
}
}
}
-
- return null;
}
/**
diff --git a/src/Psalm/Checker/Statements/ExpressionChecker.php b/src/Psalm/Checker/Statements/ExpressionChecker.php
index <HASH>..<HASH> 100644
--- a/src/Psalm/Checker/Statements/ExpressionChecker.php
+++ b/src/Psalm/Checker/Statements/ExpressionChecker.php
@@ -104,9 +104,7 @@ class ExpressionChecker
return false;
}
} elseif ($stmt instanceof PhpParser\Node\Expr\ConstFetch) {
- if (ConstFetchChecker::analyze($statements_checker, $stmt, $context) === false) {
- return false;
- }
+ ConstFetchChecker::analyze($statements_checker, $stmt, $context);
} elseif ($stmt instanceof PhpParser\Node\Scalar\String_) {
$stmt->inferredType = Type::getString();
} elseif ($stmt instanceof PhpParser\Node\Scalar\EncapsedStringPart) {
diff --git a/tests/ConstantTest.php b/tests/ConstantTest.php
index <HASH>..<HASH> 100644
--- a/tests/ConstantTest.php
+++ b/tests/ConstantTest.php
@@ -82,6 +82,20 @@ class ConstantTest extends TestCase
'assertions' => [],
'error_levels' => ['MixedArgument'],
],
+ 'undefinedConstant' => [
+ '<?php
+ switch (rand(0, 50)) {
+ case FORTY: // Observed a valid UndeclaredConstant warning
+ $x = "value";
+ break;
+ default:
+ $x = "other";
+ }
+
+ echo $x;',
+ 'assertions' => [],
+ 'error_levels' => ['UndefinedConstant'],
+ ],
];
} | Fix #<I> - allow analysis to continue after bad constant check | vimeo_psalm | train |
ba5b11738adcef773fdd1a8e592770be3b7173d5 | diff --git a/addon/edit/closetag.js b/addon/edit/closetag.js
index <HASH>..<HASH> 100644
--- a/addon/edit/closetag.js
+++ b/addon/edit/closetag.js
@@ -57,7 +57,9 @@
tok.type == "string" && (tok.end != pos.ch || !/[\"\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) ||
tok.type == "tag" && state.type == "closeTag" ||
tok.string.indexOf("/") == (tok.string.length - 1) || // match something like <someTagName />
- dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1)
+ dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 ||
+ CodeMirror.scanForClosingTag && CodeMirror.scanForClosingTag(cm, pos, tagName,
+ Math.min(cm.lastLine() + 1, pos.line + 50)))
return CodeMirror.Pass;
var doIndent = indentTags && indexOf(indentTags, lowerTagName) > -1;
diff --git a/addon/fold/xml-fold.js b/addon/fold/xml-fold.js
index <HASH>..<HASH> 100644
--- a/addon/fold/xml-fold.js
+++ b/addon/fold/xml-fold.js
@@ -164,4 +164,10 @@
if (close) return {open: open, close: close};
}
};
+
+ // Used by addon/edit/closetag.js
+ CodeMirror.scanForClosingTag = function(cm, pos, name, end) {
+ var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null);
+ return !!findMatchingClose(iter, name);
+ };
})();
diff --git a/demo/closetag.html b/demo/closetag.html
index <HASH>..<HASH> 100644
--- a/demo/closetag.html
+++ b/demo/closetag.html
@@ -7,6 +7,7 @@
<link rel="stylesheet" href="../lib/codemirror.css">
<script src="../lib/codemirror.js"></script>
<script src="../addon/edit/closetag.js"></script>
+<script src="../addon/fold/xml-fold.js"></script>
<script src="../mode/xml/xml.js"></script>
<script src="../mode/javascript/javascript.js"></script>
<script src="../mode/css/css.js"></script> | [closetag addon] Scan forward in document to look for existing closing tag
Issue #<I> | codemirror_CodeMirror | train |
0a15ff94f704beef1e71b55a14c4a614a15434c7 | diff --git a/tests/testapp/management/commands/test_email_notification_command.py b/tests/testapp/management/commands/test_email_notification_command.py
index <HASH>..<HASH> 100644
--- a/tests/testapp/management/commands/test_email_notification_command.py
+++ b/tests/testapp/management/commands/test_email_notification_command.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
from django_extensions.management.email_notifications import EmailNotificationCommand | add coding: utf-8 | django-extensions_django-extensions | train |
409410e2006fd912c967c3b90b3739f0c3bb98c8 | diff --git a/packages/material-ui/src/FormLabel/FormLabel.js b/packages/material-ui/src/FormLabel/FormLabel.js
index <HASH>..<HASH> 100644
--- a/packages/material-ui/src/FormLabel/FormLabel.js
+++ b/packages/material-ui/src/FormLabel/FormLabel.js
@@ -42,6 +42,7 @@ export const FormLabelRoot = styled('label', {
...theme.typography.body1,
lineHeight: '1.4375em',
padding: 0,
+ position: 'relative',
[`&.${formLabelClasses.focused}`]: {
color: theme.palette[styleProps.color].main,
}, | [TextField] Fix label disappearing when focusing a button (#<I>) | mui-org_material-ui | train |
6e816f48a5b96dfabcf4153444f574e3b62566a1 | diff --git a/BAC0/core/utils/notes.py b/BAC0/core/utils/notes.py
index <HASH>..<HASH> 100644
--- a/BAC0/core/utils/notes.py
+++ b/BAC0/core/utils/notes.py
@@ -46,21 +46,28 @@ def note_and_log(cls):
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)
# Rotating File Handler
+ _PERMISSION_TO_WRITE = True
logUserPath = expanduser('~')
logSaveFilePath = r'%s\.BAC0' %(logUserPath)
logFile = r'%s\%s' % (logSaveFilePath,'BAC0.log')
if not os.path.exists(logSaveFilePath):
- os.makedirs(logSaveFilePath)
- fh = RotatingFileHandler(logFile, mode='a', maxBytes=1000000, backupCount=1, encoding=None, delay=False)
- fh.setLevel = logging.DEBUG
+ try:
+ os.makedirs(logSaveFilePath)
+ except:
+ _PERMISSION_TO_WRITE = False
+ if _PERMISSION_TO_WRITE:
+ fh = RotatingFileHandler(logFile, mode='a', maxBytes=1000000, backupCount=1, encoding=None, delay=False)
+ fh.setLevel = logging.DEBUG
+
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+ fh.setFormatter(formatter)
- formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
- fh.setFormatter(formatter)
ch.setFormatter(formatter)
# Add handlers the first time only...
if not len(cls._log.handlers):
- cls._log.addHandler(fh)
+ if _PERMISSION_TO_WRITE:
+ cls._log.addHandler(fh)
cls._log.addHandler(ch)
def log(self, note,*, level=logging.DEBUG): | Permission issue on Travis CI with log file | ChristianTremblay_BAC0 | train |
046347ee8fe176d02b75de9e51cb19b77231ec36 | diff --git a/reactor-core/src/test/java/reactor/core/scheduler/SchedulersTest.java b/reactor-core/src/test/java/reactor/core/scheduler/SchedulersTest.java
index <HASH>..<HASH> 100644
--- a/reactor-core/src/test/java/reactor/core/scheduler/SchedulersTest.java
+++ b/reactor-core/src/test/java/reactor/core/scheduler/SchedulersTest.java
@@ -39,6 +39,7 @@ import java.util.function.Supplier;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.Condition;
+import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
@@ -1228,7 +1229,11 @@ public class SchedulersTest {
disposable.dispose();
- assertThat(executorService.isAllTasksCancelledOrDone()).isTrue();
+// avoid race of checking the status of futures vs cancelling said futures
+ Awaitility.await().atMost(500, TimeUnit.MILLISECONDS)
+ .pollDelay(10, TimeUnit.MILLISECONDS)
+ .pollInterval(50, TimeUnit.MILLISECONDS)
+ .until(executorService::isAllTasksCancelledOrDone);
}
} | [test] Delay checking of task cancellation with instant periodic tasks (#<I>) | reactor_reactor-core | train |
635695329ac8bfef97cbf9366a08ec383e7279b7 | diff --git a/lib/rack-environmental.rb b/lib/rack-environmental.rb
index <HASH>..<HASH> 100644
--- a/lib/rack-environmental.rb
+++ b/lib/rack-environmental.rb
@@ -78,6 +78,7 @@ module Rack
style << "top: #{options[:top] || 5}px;"
style << "left: #{options[:left] || 5}px;"
style << "opacity: #{options[:opacity] || 0.7};"
+ style << "z-index: 1000;"
style << "-moz-border-radius: 5px; -khtml-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px;"
else
style << "margin: 0px;"
diff --git a/test/sinatraapp/app.rb b/test/sinatraapp/app.rb
index <HASH>..<HASH> 100644
--- a/test/sinatraapp/app.rb
+++ b/test/sinatraapp/app.rb
@@ -20,6 +20,10 @@ get '/' do
</head>
<body>
<div id="container">
+ <div style="position: fixed; top: 20px; left: 20px; background-color: yellow;">
+ This is a fixed position div. The environmental indicator should be on top
+ of this.
+ </div>
<p>
What my associate is trying to say is that our new brake pads are really cool.
You're not even gonna believe it. | Set the z-index of the indicator to be <I> so that it is displayed on top. | techiferous_rack-environmental | train |
c4b93ad7c8255201b72c93ee2a056a07d91dd74b | diff --git a/tests/bootstrap.php b/tests/bootstrap.php
index <HASH>..<HASH> 100644
--- a/tests/bootstrap.php
+++ b/tests/bootstrap.php
@@ -28,7 +28,9 @@ wei(array(
'http' => array(
'url' => 'http://localhost:8000/call.php',
// Set ip for WeiTest\HttpTest\::testIp
- 'ip' => '127.0.0.1'
+ 'ip' => '127.0.0.1',
+ 'header' => true,
+ 'throwException' => true,
),
'db' => array(
'driver' => 'sqlite',
diff --git a/tests/unit/HttpTest.php b/tests/unit/HttpTest.php
index <HASH>..<HASH> 100644
--- a/tests/unit/HttpTest.php
+++ b/tests/unit/HttpTest.php
@@ -30,11 +30,6 @@ class HttpTest extends TestCase
if (false === @fopen($this->url, 'r')) {
$this->markTestSkipped(sprintf('URL %s is not available', $this->url));
}
-
- $this->wei->setConfig('http', array(
- 'throwException' => false,
- 'header' => true
- ));
}
/** | moved http service options to bootstrap file | twinh_wei | train |
c5405e0e9a8b8421ef3a6abfde064784e12f1448 | diff --git a/flow-typed/npm/@emotion/unitless_vx.x.x.js b/flow-typed/npm/@emotion/unitless_vx.x.x.js
index <HASH>..<HASH> 100644
--- a/flow-typed/npm/@emotion/unitless_vx.x.x.js
+++ b/flow-typed/npm/@emotion/unitless_vx.x.x.js
@@ -1,3 +1,3 @@
declare module '@emotion/unitless' {
- declare module.exports: Object
+ declare module.exports: { [key: string]: 1 }
} | better typing for @emotion/unitless | styled-components_styled-components | train |
Subsets and Splits