hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
ce15e94ae0f71b48078e8ece6e917a7c6d9359da
diff --git a/examples/demo14.html b/examples/demo14.html index <HASH>..<HASH> 100644 --- a/examples/demo14.html +++ b/examples/demo14.html @@ -40,7 +40,7 @@ var app = angular.module('main', ['ngTable']). controller('DemoCtrl', function($interval, $http, $scope, $filter, NgTableParams) { - $scope.datasets = ["1","2", "3"]; + $scope.datasets = ["1","2"]; $scope.dataset = "1"; var self = this; self.data1 = [{name: "One", age: 50}, @@ -78,20 +78,6 @@ {name: "Nephi", age: 29}, {name: "Enos", age: 34}]; - self.data3 = []; - - $interval(function() { - $http.jsonp("http://www.filltext.com/?callback=JSON_CALLBACK&rows=5&name={firstName}&age={number|80}") - .success(function (data) { - self.data3 = data; - // $scope.tableParams.reload(); - }); - }, 5000); - - var getData = function() { - return self['data' + $scope.dataset]; - }; - $scope.$watch("dataset", function () { $scope.tableParams.reload(); }); @@ -103,16 +89,18 @@ name: 'asc' // initial sorting } }, { - total: function () { return getData().length; }, // length of data + total: 0, // we should calc it inside getData because data length is dynamic getData: function($defer, params) { - var filteredData = getData(); + + var data = self["data" + $scope.dataset]; + + var filteredData = data; var orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : filteredData; - + params.total(self["data" + $scope.dataset].length); $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); - }, - $scope: { $data: {} } + } }); }) </script> diff --git a/src/scripts/03-params.js b/src/scripts/03-params.js index <HASH>..<HASH> 100644 --- a/src/scripts/03-params.js +++ b/src/scripts/03-params.js @@ -403,8 +403,10 @@ app.factory('NgTableParams', ['$q', '$log', 'ngTableDefaults', function($q, $log self.data = data; if (settings.$scope) settings.$scope.$data = data; } - if (settings.$scope) settings.$scope.pages = self.generatePagesArray(self.page(), self.total(), self.count()); - settings.$scope.$emit('ngTableAfterReloadData'); + if (settings.$scope) { + settings.$scope.pages = self.generatePagesArray(self.page(), self.total(), self.count()); + settings.$scope.$emit('ngTableAfterReloadData'); + } return data; }); }; diff --git a/src/scripts/06-pagination.js b/src/scripts/06-pagination.js index <HASH>..<HASH> 100644 --- a/src/scripts/06-pagination.js +++ b/src/scripts/06-pagination.js @@ -25,7 +25,10 @@ app.directive('ngTablePagination', ['$compile', link: function(scope, element, attrs) { scope.params.settings().$scope.$on('ngTableAfterReloadData', function() { - scope.pages = scope.params.generatePagesArray(scope.params.page(), scope.params.total(), scope.params.count()); + var page = scope.params.page(), + total = scope.params.total(), + count = scope.params.count(); + scope.pages = scope.params.generatePagesArray(page, total, count); }, true); scope.$watch('templateUrl', function(templateUrl) { @@ -42,4 +45,4 @@ app.directive('ngTablePagination', ['$compile', } }; } -]); \ No newline at end of file +]);
fix(example): updated code due to documentation total should be a number
esvit_ng-table
train
1daa5407966cc13e33a59b6dd73a06d950134d06
diff --git a/pyoko/form.py b/pyoko/form.py index <HASH>..<HASH> 100644 --- a/pyoko/form.py +++ b/pyoko/form.py @@ -80,6 +80,7 @@ class ModelForm(object): # FIXME: investigate and integrate necessary security precautions on received data # ie: received keys should be defined in the form # compare with output of self._serialize() + self.prepare_fields() new_instance = self._model.__class__(self._model.context) new_instance.key = self._model.key for key, val in data.items(): @@ -119,6 +120,7 @@ class ModelForm(object): :return: list of serialized model fields :rtype: list """ + self.prepare_fields() self.readable = readable result = [] if self._config['fields']: @@ -205,6 +207,8 @@ class ModelForm(object): return val.strftime(DATE_TIME_FORMAT) elif isinstance(val, datetime.date): return val.strftime(DATE_FORMAT) + elif isinstance(val, BaseField): + return None else: return val or '' @@ -281,13 +285,19 @@ class Form(ModelForm): self._field_values = {} self.key = None self._ordered_fields = [] - for key, val in self.__class__.__dict__.items(): + super(Form, self).__init__(*args, **kwargs) + + def prepare_fields(self): + _items = list(self.__class__.__dict__.items()) + list(self.__dict__.items()) + for key, val in _items: if isinstance(val, BaseField): val.name = key self._fields[key] = val for v in sorted(self._fields.items(), key=lambda x: x[1]._order): self._ordered_fields.append((v[0], v[1])) - super(Form, self).__init__(*args, **kwargs) + + def get_humane_value(self, name): + return name def is_in_db(self): return False @@ -311,4 +321,3 @@ class Button(BaseField): super(Button, self).__init__(*args, **kwargs) solr_type = 'button' - pass
added ability to modify a form instance just before serialization
zetaops_pyoko
train
fcd89df102ccb16bb7862a23bc116788fd3b8558
diff --git a/buildbot/slave/commands.py b/buildbot/slave/commands.py index <HASH>..<HASH> 100755 --- a/buildbot/slave/commands.py +++ b/buildbot/slave/commands.py @@ -967,6 +967,7 @@ class SlaveDirectoryUploadCommand(Command): # create all directories on the master, to catch also empty ones for dirname in foundDirs: + dirname = os.path.split(dirname) self.writer.callRemote("createdir", dirname) for filename in foundFiles: @@ -978,7 +979,7 @@ class SlaveDirectoryUploadCommand(Command): """Write a file to the remote writer""" log.msg("_writeFile: %r" % (filename)) - self.writer.callRemote('open', filename) + self.writer.callRemote('open', os.path.split(filename)) data = open(os.path.join(self.baseRoot, filename), "r").read() self.writer.callRemote('write', data) self.writer.callRemote('close') diff --git a/buildbot/steps/transfer.py b/buildbot/steps/transfer.py index <HASH>..<HASH> 100644 --- a/buildbot/steps/transfer.py +++ b/buildbot/steps/transfer.py @@ -77,6 +77,7 @@ class _DirectoryWriter(pb.Referenceable): def remote_createdir(self, dirname): # This function is needed to transfer empty directories. + dirname = os.path.sep.join(dirname) dirname = os.path.join(self.destroot, dirname) dirname = os.path.abspath(dirname) if not os.path.exists(dirname): @@ -84,6 +85,7 @@ class _DirectoryWriter(pb.Referenceable): def remote_open(self, destfile): # Create missing directories. + destfile = os.path.sep.join(destfile) destfile = os.path.join(self.destroot, destfile) destfile = os.path.abspath(destfile) dirname = os.path.dirname(destfile)
Send filenames as list of path components. (See #<I>)
buildbot_buildbot
train
6f99e1e434eb54d5b4bb6aa976c7be1e95462d50
diff --git a/src/components/vault/EntryDetails.js b/src/components/vault/EntryDetails.js index <HASH>..<HASH> 100644 --- a/src/components/vault/EntryDetails.js +++ b/src/components/vault/EntryDetails.js @@ -1,4 +1,4 @@ -import React, { useContext, useMemo, useRef, useState } from 'react'; +import React, { useContext, useMemo, useEffect, useRef, useState } from 'react'; import styled from 'styled-components'; import cx from 'classnames'; import TextArea from 'react-textarea-autosize'; @@ -88,8 +88,7 @@ const AttachmentDropZone = styled.div` } `; const AttachmentItem = styled(Card)` - margin-right: 8px; - margin-bottom: 8px; + margin: 4px; padding: 4px; width: 104px; height: 110px; @@ -235,7 +234,7 @@ const Attachments = ({ entryFacade }) => { <AttachmentsContainer> <For each="attachment" of={attachments}> <AttachmentItem key={attachment.id} title={attachment.name}> - <Icon icon={attachment.icon} iconSize={60} color="rgba(0,0,0,0.7)" /> + <Icon icon={attachment.icon} iconSize={56} color="rgba(0,0,0,0.6)" /> <AttachmentItemSize>{attachment.sizeFriendly}</AttachmentItemSize> <AttachmentItemTitle>{attachment.name}</AttachmentItemTitle> </AttachmentItem> @@ -502,20 +501,6 @@ const EntryDetailsContent = () => { onSaveEdit } = useCurrentEntry(); const { onMoveEntryToTrash, trashID } = useGroups(); - const { - onAddAttachments - } = useContext(VaultContext); - const { - // acceptedFiles, - getInputProps, - getRootProps, - isDragActive - } = useDropzone({ - noClick: true, - onDrop: files => { - onAddAttachments(entry.id, files); - } - }); const editableFields = editing ? entry.fields.filter(item => item.propertyType === 'property') @@ -526,13 +511,7 @@ const EntryDetailsContent = () => { return ( <> <PaneHeader title={editing ? 'Edit Document' : title(entry)} /> - <PaneContent {...(editing ? {} : getRootProps())} overflow={isDragActive ? "hidden" : undefined}> - <AttachmentDropZone - visible={isDragActive} - > - <Icon icon="compressed" iconSize={30} /> - <span>Drop file(s) to add to vault</span> - </AttachmentDropZone> + <PaneContent> <FormContainer primary> <For each="field" of={mainFields}> <FieldRow @@ -573,7 +552,6 @@ const EntryDetailsContent = () => { <span>Attachments</span> </CustomFieldsHeading> <Attachments entryFacade={entry} /> - <input {...getInputProps()} /> </If> </PaneContent> <PaneFooter> @@ -608,10 +586,32 @@ const EntryDetailsContent = () => { }; const EntryDetails = () => { - const { entry } = useCurrentEntry(); + const { editing, entry } = useCurrentEntry(); + const { + onAddAttachments + } = useContext(VaultContext); + const { + getInputProps, + getRootProps, + isDragActive + } = useDropzone({ + noClick: true, + onDrop: files => { + onAddAttachments(entry.id, files); + } + }); return ( <ErrorBoundary> - <PaneContainer> + <PaneContainer {...(editing ? {} : getRootProps())}> + <If condition={!editing}> + <AttachmentDropZone + visible={isDragActive} + > + <Icon icon="compressed" iconSize={30} /> + <span>Drop file(s) to add to vault</span> + </AttachmentDropZone> + <input {...getInputProps()} /> + </If> <Choose> <When condition={entry}> <EntryDetailsContent />
Improve drag-n-drop modal for attachments
buttercup_ui
train
3e5733dd2bce8ede62238caf452edfc632ff9fb8
diff --git a/lib/ImportStatement.js b/lib/ImportStatement.js index <HASH>..<HASH> 100644 --- a/lib/ImportStatement.js +++ b/lib/ImportStatement.js @@ -221,7 +221,7 @@ class ImportStatement { // @return [Array] _equalsAndValue() { if (this.declarationKeyword === 'import') { - return ['from', `'${this.path}'`]; + return ['from', `'${this.path}';`]; } return ['=', `${this.importFunction}('${this.path}');`]; }
Add semicolon to generated ImportStatement strings This will make the resulting output a little more correct.
Galooshi_import-js
train
acecac1e28884bbf13e1c33a0c136e11147515e0
diff --git a/src/browserbox-imap.js b/src/browserbox-imap.js index <HASH>..<HASH> 100644 --- a/src/browserbox-imap.js +++ b/src/browserbox-imap.js @@ -206,7 +206,10 @@ }); // allows certificate handling for platform w/o native tls support - this.socket.oncert = this.oncert; + // oncert is non standard so setting it might throw if the socket object is immutable + try { + this.socket.oncert = this.oncert; + } catch (E) {} this.socket.onerror = this._onError.bind(this); this.socket.onopen = this._onOpen.bind(this); diff --git a/test/unit/browserbox-imap-test.js b/test/unit/browserbox-imap-test.js index <HASH>..<HASH> 100644 --- a/test/unit/browserbox-imap-test.js +++ b/test/unit/browserbox-imap-test.js @@ -50,6 +50,24 @@ TCPSocket.open.restore(); }); + describe('#connect', function() { + it('should not throw', function() { + var client = new ImapClient(host, port); + client._TCPSocket = { + open: function() { + var socket = { + onopen: function() {}, + onerror: function() {} + }; + // disallow setting new properties (eg. oncert) + Object.preventExtensions(socket); + return socket; + } + }; + client.connect(); + }); + }); + describe('#close', function() { it('should call socket.close', function() { client.socket.readyState = 'open';
[WO-<I>] Catch errors when setting oncert for the tcpsocket object
emailjs_emailjs-imap-client
train
70e8219f95e0375b7b83e29d5d6579130d1e4dc8
diff --git a/app/scripts/Inset.js b/app/scripts/Inset.js index <HASH>..<HASH> 100644 --- a/app/scripts/Inset.js +++ b/app/scripts/Inset.js @@ -3,7 +3,7 @@ import { color } from 'd3-color'; import clip from 'liang-barsky'; import * as PIXI from 'pixi.js'; -import { transition } from './services'; +import { transitionGroup } from './services/transition'; import { canvasLinearGradient, getAngleBetweenPoints } from './utils'; @@ -763,19 +763,6 @@ export default class Inset { const imPos = this.computeImagePosition(); - this.tweenStop = transition( - this.sprite, - { - x: imPos.x, - y: imPos.y, - scale: { - x: imPos.scaleX, - y: imPos.scaleY, - } - }, - 80 - ); - const [bX, bY] = this.computeBorder( this.x, this.y, @@ -783,14 +770,29 @@ export default class Inset { this.height, ); - this.tweenStop = transition( - this.border, - { - x: bX, - y: bY, - width: (this.data.width * imPos.scaleX) + this.borderPadding, - height: (this.data.height * imPos.scaleY) + this.borderPadding, - }, + this.tweenStop = transitionGroup( + [ + { + obj: this.sprite, + propsTo: { + x: imPos.x, + y: imPos.y, + scale: { + x: imPos.scaleX, + y: imPos.scaleY, + } + } + }, + { + obj: this.border, + propsTo: { + x: bX, + y: bY, + width: (this.data.width * imPos.scaleX) + this.borderPadding, + height: (this.data.height * imPos.scaleY) + this.borderPadding, + } + } + ], 80 ); }
Smoothiefy transitions through grouping
higlass_higlass
train
e5b1bf0c4f33f030e7efe03ba8c8e99a26f84e8a
diff --git a/tensorflow_probability/python/bijectors/restructure.py b/tensorflow_probability/python/bijectors/restructure.py index <HASH>..<HASH> 100644 --- a/tensorflow_probability/python/bijectors/restructure.py +++ b/tensorflow_probability/python/bijectors/restructure.py @@ -52,6 +52,7 @@ class Restructure(bijector.AutoCompositeTensorBijector): arguments to downstream multipart bijectors. Example Usage: + ```python # Pack a 3-element list of tensors into a dict. The output structure,
Fix docstring in tfb.Restructure. Code blocks need leading newline. PiperOrigin-RevId: <I>
tensorflow_probability
train
812bfe9f72a0a8afc157da3b8618c5b035b2abe5
diff --git a/einops/_backends.py b/einops/_backends.py index <HASH>..<HASH> 100644 --- a/einops/_backends.py +++ b/einops/_backends.py @@ -505,12 +505,13 @@ class KerasBackend(AbstractBackend): framework_name = 'keras' def __init__(self): - from tensorflow import keras - self.keras = keras - self.K = keras.backend + import tensorflow as tf + self.tf = tf + self.keras = tf.keras + self.K = tf.keras.backend def is_appropriate_type(self, tensor): - return self.K.is_tensor(tensor) and self.K.is_keras_tensor(tensor) + return self.tf.is_tensor(tensor) and self.K.is_keras_tensor(tensor) def create_symbol(self, shape): return self.keras.Input(batch_shape=shape) diff --git a/einops/layers/keras.py b/einops/layers/keras.py index <HASH>..<HASH> 100644 --- a/einops/layers/keras.py +++ b/einops/layers/keras.py @@ -1,4 +1,4 @@ -from keras.engine import Layer +from tensorflow.keras.layers import Layer from .._backends import UnknownSize from . import RearrangeMixin, ReduceMixin diff --git a/tests/test_layers.py b/tests/test_layers.py index <HASH>..<HASH> 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -229,9 +229,9 @@ def test_keras_layer(): if any(backend.framework_name == 'keras' for backend in collect_test_backends(symbolic=True, layers=True)): # checked that keras present - import keras - from keras.models import Sequential - from keras.layers import MaxPool2D as MaxPool2d, Conv2D as Conv2d, Dense as Linear, ReLU + import tensorflow as tf + from tensorflow.keras.models import Sequential + from tensorflow.keras.layers import MaxPool2D as MaxPool2d, Conv2D as Conv2d, Dense as Linear, ReLU from einops.layers.keras import Rearrange, Reduce, keras_custom_objects def create_model(): @@ -258,12 +258,12 @@ def test_keras_layer(): tmp_filename = f.name # save arch + weights print('temp_path_keras1', tmp_filename) - keras.models.save_model(model1, tmp_filename) - model3 = keras.models.load_model(tmp_filename, custom_objects=keras_custom_objects) + tf.keras.models.save_model(model1, tmp_filename) + model3 = tf.keras.models.load_model(tmp_filename, custom_objects=keras_custom_objects) assert numpy.allclose(model1.predict_on_batch(input), model3.predict_on_batch(input)) # save arch as json - model4 = keras.models.model_from_json(model1.to_json(), custom_objects=keras_custom_objects) + model4 = tf.keras.models.model_from_json(model1.to_json(), custom_objects=keras_custom_objects) model1.save_weights(tmp_filename) model4.load_weights(tmp_filename) model2.load_weights(tmp_filename) diff --git a/tests/test_ops.py b/tests/test_ops.py index <HASH>..<HASH> 100644 --- a/tests/test_ops.py +++ b/tests/test_ops.py @@ -311,7 +311,7 @@ def test_reduction_with_callable_imperatives(): return chainer.functions.logsumexp(x, tuple_of_axes) def logsumexp_keras(x, tuple_of_axes): - import keras.backend as k + import tensorflow.keras.backend as k return k.logsumexp(x, tuple_of_axes) def logsumexp_numpy(x, tuple_of_axes):
excluding keras as independent framework
arogozhnikov_einops
train
c923ce837a657760ec5ffd5c303e81e3db088a86
diff --git a/lib/formtastic.rb b/lib/formtastic.rb index <HASH>..<HASH> 100644 --- a/lib/formtastic.rb +++ b/lib/formtastic.rb @@ -105,7 +105,10 @@ module Formtastic #:nodoc: options[:label_html][:for] ||= options[:input_html][:id] end - list_item_content = @@inline_order.map do |type| + input_parts = @@inline_order.dup + input_parts.delete(:errors) if options[:as] == :hidden + + list_item_content = input_parts.map do |type| send(:"inline_#{type}_for", method, options) end.compact.join("\n") diff --git a/spec/formtastic_spec.rb b/spec/formtastic_spec.rb index <HASH>..<HASH> 100644 --- a/spec/formtastic_spec.rb +++ b/spec/formtastic_spec.rb @@ -1202,11 +1202,11 @@ describe 'Formtastic' do describe ":as => :hidden" do before do - @new_post.stub!(:hidden) + @new_post.stub!(:secret) @new_post.stub!(:column_for_attribute).and_return(mock('column', :type => :string)) semantic_form_for(@new_post) do |builder| - concat(builder.input(:hidden, :as => :hidden)) + concat(builder.input(:secret, :as => :hidden)) end end @@ -1215,7 +1215,7 @@ describe 'Formtastic' do end it 'should have a post_hidden_input id on the wrapper' do - output_buffer.should have_tag('form li#post_hidden_input') + output_buffer.should have_tag('form li#post_secret_input') end it 'should not generate a label for the input' do @@ -1223,10 +1223,24 @@ describe 'Formtastic' do end it "should generate a input field" do - output_buffer.should have_tag("form li input#post_hidden") + output_buffer.should have_tag("form li input#post_secret") output_buffer.should have_tag("form li input[@type=\"hidden\"]") - output_buffer.should have_tag("form li input[@name=\"post[hidden]\"]") + output_buffer.should have_tag("form li input[@name=\"post[secret]\"]") end + + it "should not render inline errors" do + @errors = mock('errors') + @errors.stub!(:[]).with(:secret).and_return(["foo", "bah"]) + @new_post.stub!(:errors).and_return(@errors) + + semantic_form_for(@new_post) do |builder| + concat(builder.input(:secret, :as => :hidden)) + end + + output_buffer.should_not have_tag("form li p.inline-errors") + output_buffer.should_not have_tag("form li ul.errors") + end + end describe ":as => :time_zone" do
inline errors will no longer be rendered for hidden inputs (resolves issue #<I>)
justinfrench_formtastic
train
04e2f64ba76de911d7695415963390ce4422ab35
diff --git a/src/cli.js b/src/cli.js index <HASH>..<HASH> 100755 --- a/src/cli.js +++ b/src/cli.js @@ -37,7 +37,7 @@ function checkInternet() { if (require.main === module) { program - .version(packageJson.version) + .version(packageJson.version, '--version, -V, -v') .arguments('<targetUrl> [dest]') .action((targetUrl, appDir) => { program.targetUrl = targetUrl;
Add Unix/Mac-conventional `-v` version flag (PR#<I>) Most Unix-based command line utilities respond to a _lowercase_ `-v` flag which outputs the current version. Adding that as an alias here in addition to the already present `--version` and `-V` flags :)
jiahaog_nativefier
train
1cf1d3eb11ae0702fb40eb3244befa5c1b06e7ec
diff --git a/Migrations/pdo_mysql/Version20141202123401.php b/Migrations/pdo_mysql/Version20141202123401.php index <HASH>..<HASH> 100755 --- a/Migrations/pdo_mysql/Version20141202123401.php +++ b/Migrations/pdo_mysql/Version20141202123401.php @@ -35,6 +35,16 @@ class Version20141202123401 extends AbstractMigration REFERENCES ujm_label (id) ON DELETE CASCADE "); + + $this->addSql(" + INSERT INTO iujm_proposal_label ( + proposal_id, label_id + ) + SELECT id, + label_id, + FROM ujm_proposal WHERE label_id IS NOT NULL + "); + $this->addSql(" ALTER TABLE ujm_proposal DROP FOREIGN KEY FK_2672B44B33B92F39
[ExoBundle] to update the migration for the matching question
claroline_Distribution
train
b88d7720390a19a96b2c9e05fbf3448a17623958
diff --git a/src/main/java/io/github/bonigarcia/wdm/WebDriverManager.java b/src/main/java/io/github/bonigarcia/wdm/WebDriverManager.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/github/bonigarcia/wdm/WebDriverManager.java +++ b/src/main/java/io/github/bonigarcia/wdm/WebDriverManager.java @@ -1309,7 +1309,6 @@ public abstract class WebDriverManager { String sessionId = webDriverCreator .getSessionId(driverBrowser.getDriver()); browserContainer.setSessionId(sessionId); - driverBrowser.addDockerContainer(browserContainer); if (config.isEnabledDockerVnc()) { String noVncImage = config.getDockerNoVncImage();
Remove duplicated Docker container in driver browser
bonigarcia_webdrivermanager
train
98e4e52ae6b992103473ffb2896240223108cabc
diff --git a/qunit-parameterize.js b/qunit-parameterize.js index <HASH>..<HASH> 100644 --- a/qunit-parameterize.js +++ b/qunit-parameterize.js @@ -1,3 +1,8 @@ +/* + * Parameterize v 0.1 + * A QUnit Addon For Running Parameterized Tests + * https://github.com/AStepaniuk/qunit-parameterize + */ QUnit.extend(QUnit, { cases : function(testCases) { var createTest = function(methodName, title, expected, callback, parameters) {
Version and link to repository is added to implementation file.
AStepaniuk_qunit-parameterize
train
cc5e72ed2d2cf290e5e6c8da859abf842f529155
diff --git a/openquake/commonlib/logictree.py b/openquake/commonlib/logictree.py index <HASH>..<HASH> 100644 --- a/openquake/commonlib/logictree.py +++ b/openquake/commonlib/logictree.py @@ -1027,6 +1027,7 @@ class GsimLogicTree(object): def _parse_lt(self): # do the parsing, called at instantiation time to populate .values fkeys = [] + branchsetids = set() nrml = node_from_xml(self.fname) for branching_level in nrml.logicTree: if len(branching_level) > 1: @@ -1038,6 +1039,12 @@ class GsimLogicTree(object): raise InvalidLogicTree( 'only uncertainties of type ' '"gmpeModel" are allowed in gmpe logic tree') + bsid = branchset['branchSetID'] + if bsid in branchsetids: + raise InvalidLogicTree( + 'Duplicated branchSetID %s' % bsid) + else: + branchsetids.add(bsid) fkey = branchset.attrib.get(self.branchset_filter) if fkey: fkeys.append(fkey) diff --git a/openquake/commonlib/tests/logictree_test.py b/openquake/commonlib/tests/logictree_test.py index <HASH>..<HASH> 100644 --- a/openquake/commonlib/tests/logictree_test.py +++ b/openquake/commonlib/tests/logictree_test.py @@ -1516,6 +1516,42 @@ class GsimLogicTreeTestCase(unittest.TestCase): self.parse_invalid(xml, logictree.InvalidLogicTree, 'Branching level bl1 has multiple branchsets') + def test_branchset_id_not_unique(self): + xml = _make_nrml("""\ + <logicTree logicTreeID="lt1"> + <logicTreeBranchingLevel branchingLevelID="bl1"> + <logicTreeBranchSet uncertaintyType="gmpeModel" + branchSetID="bs1" + applyToTectonicRegionType="Shield"> + <logicTreeBranch branchID="b1"> + <uncertaintyModel>ChiouYoungs2008</uncertaintyModel> + <uncertaintyWeight>0.7</uncertaintyWeight> + </logicTreeBranch> + <logicTreeBranch branchID="b2"> + <uncertaintyModel>SadighEtAl1997</uncertaintyModel> + <uncertaintyWeight>0.3</uncertaintyWeight> + </logicTreeBranch> + </logicTreeBranchSet> + </logicTreeBranchingLevel> + <logicTreeBranchingLevel branchingLevelID="bl2"> + <logicTreeBranchSet uncertaintyType="gmpeModel" + branchSetID="bs1" + applyToTectonicRegionType="Subduction Interface"> + <logicTreeBranch branchID="b3"> + <uncertaintyModel>ChiouYoungs2008</uncertaintyModel> + <uncertaintyWeight>0.6</uncertaintyWeight> + </logicTreeBranch> + <logicTreeBranch branchID="b4"> + <uncertaintyModel>SadighEtAl1997</uncertaintyModel> + <uncertaintyWeight>0.4</uncertaintyWeight> + </logicTreeBranch> + </logicTreeBranchSet> + </logicTreeBranchingLevel> + </logicTree> + """) + self.parse_invalid( + xml, logictree.InvalidLogicTree, "Duplicated branchSetID bs1") + def test_invalid_gsim(self): xml = _make_nrml("""\ <logicTree logicTreeID="lt1">
Added a check for duplicated branchset IDs
gem_oq-engine
train
83c47958707956a8812b2c5c91a4550f874cb055
diff --git a/lib/rb/lib/thrift/transport/socket.rb b/lib/rb/lib/thrift/transport/socket.rb index <HASH>..<HASH> 100644 --- a/lib/rb/lib/thrift/transport/socket.rb +++ b/lib/rb/lib/thrift/transport/socket.rb @@ -97,12 +97,13 @@ module Thrift data = @handle.readpartial(sz) else # it's possible to interrupt select for something other than the timeout - # so we need to ensure we've waited long enough + # so we need to ensure we've waited long enough, but not too long start = Time.now - rd = nil # scoping - loop do - rd, = IO.select([@handle], nil, nil, @timeout) - break if (rd and not rd.empty?) or Time.now - start >= @timeout + timespent = 0 + rd = loop do + rd, = IO.select([@handle], nil, nil, @timeout - timespent) + timespent = Time.now - start + break rd if (rd and not rd.empty?) or timespent >= @timeout end if rd.nil? or rd.empty? raise TransportException.new(TransportException::TIMED_OUT, "Socket: Timed out reading #{sz} bytes from #{@desc}") diff --git a/lib/rb/spec/socket_spec_shared.rb b/lib/rb/spec/socket_spec_shared.rb index <HASH>..<HASH> 100644 --- a/lib/rb/spec/socket_spec_shared.rb +++ b/lib/rb/spec/socket_spec_shared.rb @@ -91,7 +91,7 @@ shared_examples_for "a socket" do it "should raise an error when read times out" do @socket.timeout = 0.5 @socket.open - IO.should_receive(:select).with([@handle], nil, nil, 0.5).at_least(1).times.and_return(nil) + IO.should_receive(:select).once {sleep(0.5); nil} lambda { @socket.read(17) }.should raise_error(Thrift::TransportException) { |e| e.type.should == Thrift::TransportException::TIMED_OUT } end
THRIFT-<I>. rb: Ruby read timeouts can sometimes be 2x what they should be This patch makes sure that we don't wait longer than necessary for timeouts. Patch: Ryan King git-svn-id: <URL>
limingxinleo_thrift
train
65cb9e7bcc3c1a02308fcbfc7caa76c50bbc82ef
diff --git a/scripts/lateralus.component.js b/scripts/lateralus.component.js index <HASH>..<HASH> 100644 --- a/scripts/lateralus.component.js +++ b/scripts/lateralus.component.js @@ -124,7 +124,7 @@ define([ // A model instance provided to addComponent takes precendence over the // prototype property. if (this.Model && !viewOptions.model) { - augmentedViewOptions.model = new this.Model( + this.model = new this.Model( lateralus ,this.Model.__super__ ,this.Model.prototype.__proto @@ -132,6 +132,8 @@ define([ ,options.modelAttributes ,options.modelOptions ); + + augmentedViewOptions.model = this.model; } /**
Attach instantiated Model to Component instance.
Jellyvision_lateralus
train
a9ab778d3b01e5e2e522844341d1a3cc51b8d80f
diff --git a/models/exceptions.py b/models/exceptions.py index <HASH>..<HASH> 100644 --- a/models/exceptions.py +++ b/models/exceptions.py @@ -88,8 +88,8 @@ class RootParadigmIntersection(DBException): self.intersection = str(' '.join(map(str, self.intersection))) def __str__(self): - return 'Singular sequences intersection detected when adding the root paradigm : %s with the following ' \ - 'singular sequences : %s'%(str(self.to_add), str(self.intersection)) + return 'Singular sequences intersection detected when adding the following script as a root paradigm : %s ' \ + 'with the following root paradigms : %s'%(str(self.to_add), str(self.intersection)) class ParadigmAlreadyExist(DBException): diff --git a/models/relations/relations.py b/models/relations/relations.py index <HASH>..<HASH> 100644 --- a/models/relations/relations.py +++ b/models/relations/relations.py @@ -191,7 +191,7 @@ class RelationsConnector(DBConnector, metaclass=Singleton): raise SingularSequenceAlreadyExist(script_ast) # get all the singular sequence of the db to see if the singular sequence can be created - root_paradigm = self._compute_root(script_ast) + root_paradigm = self.compute_root(script_ast) # save the singular sequence insertion = { @@ -222,9 +222,9 @@ class RelationsConnector(DBConnector, metaclass=Singleton): raise ParadigmAlreadyExist(script_ast) # get all the singular sequence of the db to avoid intersection - if set.intersection(set(str(seq) for seq in script_ast.singular_sequences), self.singular_sequences()): - raise RootParadigmIntersection(script_ast, - set(str(seq) for seq in script_ast.singular_sequences) & set(self.singular_sequences())) + intersection = self.root_intersections(script_ast) + if intersection: + raise RootParadigmIntersection(script_ast, intersection) # save the root paradigm insertion = { @@ -248,7 +248,7 @@ class RelationsConnector(DBConnector, metaclass=Singleton): raise ParadigmAlreadyExist(script_ast) # get all the singular sequence of the db to check if we can create the paradigm - root_paradigm = self._compute_root(script_ast) + root_paradigm = self.compute_root(script_ast) insertion = { '_id': str(script_ast), @@ -260,7 +260,7 @@ class RelationsConnector(DBConnector, metaclass=Singleton): } self.relations.insert(insertion) - def _compute_root(self, script_ast): + def compute_root(self, script_ast): """ Prerequisite root exist in the collection. :param script_ast: @@ -274,3 +274,16 @@ class RelationsConnector(DBConnector, metaclass=Singleton): raise RootParadigmMissing(script_ast) return result['_id'] + + def root_intersections(self, script_ast): + """ + Return all the root paradigms that have an intersection in theirs singular sequences with the script in + parameter. + :param script_ast: the script to detect collision + :return: a list of str of the script of the root paradigms + """ + result = [e['_id'] for e in self.relations.find({ + 'TYPE': ROOT_PARADIGM_TYPE, + 'SINGULAR_SEQUENCES': {'$in': [str(seq) for seq in script_ast.singular_sequences]} + })] + return result \ No newline at end of file
Add a root_intersection method to retrieve all the root paradigms that have a singular sequence collision with a given script. Improve the RootParadigmIntersection exception.
IEMLdev_ieml
train
7a72cfbdf4b10de1e67b8e17b78fa1c0abd78fc4
diff --git a/lib/bolt/logger.rb b/lib/bolt/logger.rb index <HASH>..<HASH> 100644 --- a/lib/bolt/logger.rb +++ b/lib/bolt/logger.rb @@ -203,7 +203,7 @@ module Bolt def self.flush_queue @mutex.synchronize do @message_queue.each do |message| - log_message(message) + log_message(**message) end @message_queue.clear
(maint) Fix keyword parameters warning in logger ``` lib/bolt/logger.rb:<I>: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call ``` This line was invoking a method by passing a hash and expecting it to be implicitly interpreted as the the **kwargs argument. This behavior is deprecated and the hash needs to be explicitly passed as **kwargs. !no-release-note
puppetlabs_bolt
train
5e1615956c01063aa36d06ecdec232b88d49eff8
diff --git a/lib/Console/Command/ConfigurationBuild.php b/lib/Console/Command/ConfigurationBuild.php index <HASH>..<HASH> 100644 --- a/lib/Console/Command/ConfigurationBuild.php +++ b/lib/Console/Command/ConfigurationBuild.php @@ -25,8 +25,7 @@ class ConfigurationBuild extends Command ->setHelp( 'This command will build the configuration object based off of configuration files and ' . 'persistent storage data. By default, it will rebuild all contexts, but you can specify an ' - . 'individual context if you so like.') - ; + . 'individual context if you so like.'); $this->addArgument('context', InputArgument::OPTIONAL, 'Configuration Context (ignore to build all contexts)'); } @@ -52,11 +51,11 @@ class ConfigurationBuild extends Command $contexts = $factory->getContextFile()->getContexts(); $context = $input->getArgument('context'); if ($context) { - if (in_array($context, $contexts)) { + if (in_array($context, $contexts)) { $contexts = [$context]; - } } else { - throw new InvalidContextException('Context does not exist: ' . $context); + throw new InvalidContextException('Context does not exist: ' . $context); + } } foreach ($contexts as $context) { $output->writeln('Building context: ' . $context); diff --git a/tests/Command/ConfigurationBuilderTest.php b/tests/Command/ConfigurationBuilderTest.php index <HASH>..<HASH> 100644 --- a/tests/Command/ConfigurationBuilderTest.php +++ b/tests/Command/ConfigurationBuilderTest.php @@ -104,6 +104,27 @@ class ConfigurationBuilderTest extends CommandTestCase $this->executeTest($factory, $input); } + public function testOnlyProvidedContextIsRun() + { + $builder = $this->getBuilder(1); + $manager = $this->getManager(); + + $contextFile = $this->getMockBuilder(AbstractContextConfigurationFile::class)->disableOriginalConstructor()->getMock(); + $contextFile->expects(self::once())->method('getContexts')->willReturn([ + 'context1', + ]); + + $factory = $this->getFactory($builder, $manager, $contextFile); + /* @var $factory \Magium\Configuration\MagiumConfigurationFactoryInterface */ + + $input = $this->createMock(InputInterface::class); + + // The return value "context" does not match "context1" in the $contextFile mock, triggering the exception + $input->expects(self::once())->method('getArgument')->with(self::equalTo('context'))->willReturn('context1'); + + $this->executeTest($factory, $input); + } + protected function executeTest( MagiumConfigurationFactoryInterface $factory, InputInterface $input = null)
Fixed a line messup from Scrutinizer and added an additional test case
magium_configuration-manager
train
5b6c899df87937e702410acb7a8604f6fc03b29c
diff --git a/js/cointiger.js b/js/cointiger.js index <HASH>..<HASH> 100644 --- a/js/cointiger.js +++ b/js/cointiger.js @@ -4,7 +4,6 @@ const huobipro = require ('./huobipro.js'); const { ExchangeError, ExchangeNotAvailable, AuthenticationError, InvalidOrder, InsufficientFunds, OrderNotFound } = require ('./base/errors'); -const { ROUND } = require ('./base/functions/number'); // ---------------------------------------------------------------------------
cointiger removed references to ROUND
ccxt_ccxt
train
69eb0becfdf6b8500aed6af0e1da4d57fb683408
diff --git a/ui/admin/src/main/java/org/openengsb/ui/admin/WicketApplication.java b/ui/admin/src/main/java/org/openengsb/ui/admin/WicketApplication.java index <HASH>..<HASH> 100644 --- a/ui/admin/src/main/java/org/openengsb/ui/admin/WicketApplication.java +++ b/ui/admin/src/main/java/org/openengsb/ui/admin/WicketApplication.java @@ -41,7 +41,7 @@ public class WicketApplication extends OpenEngSBWicketApplication { SendEventPage.class, }; for (Class<? extends Page> page : pages) { - mount(new MixedParamUrlCodingStrategy(page.getSimpleName(), page, null)); + mount(new MixedParamUrlCodingStrategy(page.getSimpleName(), page, new String[0])); } }
[OPENENGSB-<I>] fix failing unit-test
openengsb_openengsb
train
4f170c2f2543e36c452b3babcc3f717833948aa2
diff --git a/lib/lifx/client.rb b/lib/lifx/client.rb index <HASH>..<HASH> 100644 --- a/lib/lifx/client.rb +++ b/lib/lifx/client.rb @@ -7,8 +7,18 @@ require 'lifx/light_collection' module LIFX class Client - def self.instance - @instance ||= new + class << self + def lan + @lan ||= new + end + + def virtual_bulb + @virtual_bulb ||= begin + @virtual_bulb_client = new(transport: :virtual_bulb) + @virtual_bulb_client.discover + @virtual_bulb_client.lights.first + end + end end LIFX_PORT = 56700 diff --git a/lib/lifx/transport_manager/virtual_bulb.rb b/lib/lifx/transport_manager/virtual_bulb.rb index <HASH>..<HASH> 100644 --- a/lib/lifx/transport_manager/virtual_bulb.rb +++ b/lib/lifx/transport_manager/virtual_bulb.rb @@ -26,6 +26,10 @@ module LIFX def stop @gateway.close end + + def flush(**options) + @gateway.flush(**options) + end end end end
LIFX::Client.virtual_bulb refers to virtual bulb light instance
LIFX_lifx-gem
train
d89c16dfe8b50ee03fb52515dfbcdfc80e315be7
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -131,7 +131,7 @@ tests_requirements = [ "flake8-bugbear", "flake8-comprehensions", "flake8-string-format", - "pylint", + "pylint==2.5.3", "pylint-pytest>=0.3.0", "pylint-plugin-utils", "wget",
deps: freeze pylint at <I>
iterative_dvc
train
a674b41d3c71cc1772b9c6593513be8d51cb1a59
diff --git a/src/src/org/renpy/android/Hardware.java b/src/src/org/renpy/android/Hardware.java index <HASH>..<HASH> 100644 --- a/src/src/org/renpy/android/Hardware.java +++ b/src/src/org/renpy/android/Hardware.java @@ -31,14 +31,14 @@ public class Hardware { /** * Vibrate for s seconds. */ - static void vibrate(double s) { + public static void vibrate(double s) { Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); if (v != null) { v.vibrate((int) (1000 * s)); } } - static SensorEvent lastEvent = null; + public static SensorEvent lastEvent = null; static class AccelListener implements SensorEventListener { public void onSensorChanged(SensorEvent ev) { @@ -55,7 +55,7 @@ public class Hardware { /** * Enable or Disable the accelerometer. */ - static void accelerometerEnable(boolean enable) { + public static void accelerometerEnable(boolean enable) { SensorManager sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); Sensor accel = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); @@ -72,7 +72,7 @@ public class Hardware { } - static float[] accelerometerReading() { + public static float[] accelerometerReading() { if (lastEvent != null) { return lastEvent.values; } else { @@ -86,14 +86,14 @@ public class Hardware { /** * Get display DPI. */ - static int getDPI() { + public static int getDPI() { return metrics.densityDpi; } /** * Show the soft keyboard. */ - static void showKeyboard() { + public static void showKeyboard() { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(view, InputMethodManager.SHOW_FORCED); } @@ -101,7 +101,7 @@ public class Hardware { /** * Hide the soft keyboard. */ - static void hideKeyboard() { + public static void hideKeyboard() { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } @@ -111,7 +111,7 @@ public class Hardware { */ static List<ScanResult> latestResult; - static void enableWifiScanner() + public static void enableWifiScanner() { IntentFilter i = new IntentFilter(); i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); @@ -129,7 +129,7 @@ public class Hardware { } - static String scanWifi() { + public static String scanWifi() { // Now you can call this and it should execute the broadcastReceiver's // onReceive()
some "public" declarations are necessary to get access by pyjnius
kivy_python-for-android
train
3c6b6553fb82734d9303beb8728c534f1b5d144e
diff --git a/network/default.go b/network/default.go index <HASH>..<HASH> 100644 --- a/network/default.go +++ b/network/default.go @@ -106,7 +106,7 @@ func newNetwork(opts ...Option) Network { // server is network server server := server.NewServer( server.Id(options.Id), - server.Address(address), + server.Address(peerAddress), server.Advertise(advertise), server.Name(options.Name), server.Transport(tunTransport),
Use peerAddress as the thing to listen on
micro_go-micro
train
932159cfd0c84ccf864e59be4e357e863fa7c79f
diff --git a/src/components/index.js b/src/components/index.js index <HASH>..<HASH> 100644 --- a/src/components/index.js +++ b/src/components/index.js @@ -1,2 +1,7 @@ -export Cube from './Cube' -export PushPaneLayout from './PushPaneLayout' +import Cube from './Cube' +import PushPaneLayout from './PushPaneLayout' + +export { + Cube, + PushPaneLayout, +} diff --git a/src/core/index.js b/src/core/index.js index <HASH>..<HASH> 100644 --- a/src/core/index.js +++ b/src/core/index.js @@ -1,13 +1,23 @@ -export ElementManager from './ElementManager' -export Motor from './Motor' -export Node from './Node' -export Scene from './Scene' -export Sizeable from './Sizeable' -export Transformable from './Transformable' -export TreeNode from './TreeNode' -export XYZValues from './XYZValues' +import ElementManager from './ElementManager' +import Motor from './Motor' +import Node from './Node' +import Scene from './Scene' +import Sizeable from './Sizeable' +import Transformable from './Transformable' +import TreeNode from './TreeNode' +import XYZValues from './XYZValues' import * as Utility from './Utility' + export { - Utility + ElementManager, + Motor, + Node, + Scene, + Sizeable, + Transformable, + TreeNode, + XYZValues, + + Utility, } diff --git a/src/html/index.js b/src/html/index.js index <HASH>..<HASH> 100644 --- a/src/html/index.js +++ b/src/html/index.js @@ -1,5 +1,13 @@ -export MotorHTMLBase from './base' -export MotorHTMLNode from './node' -export MotorHTMLPushPaneLayout from './push-pane-layout' -export MotorHTMLScene from './scene' -export WebComponent from './web-component' +import MotorHTMLBase from './base' +import MotorHTMLNode from './node' +import MotorHTMLPushPaneLayout from './push-pane-layout' +import MotorHTMLScene from './scene' +import WebComponent from './web-component' + +export { + MotorHTMLBase, + MotorHTMLNode, + MotorHTMLPushPaneLayout, + MotorHTMLScene, + WebComponent, +} diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -1,15 +1,23 @@ -export Calendar from './Calendar' -export DoubleSidedPlane from './DoubleSidedPlane' -export Grid from './Grid' -export Molecule from './Molecule' -export Plane from './Plane' -export PushMenuLayout from './PushMenuLayout' +import Calendar from './Calendar' +import DoubleSidedPlane from './DoubleSidedPlane' +import Grid from './Grid' +import Molecule from './Molecule' +import Plane from './Plane' +import PushMenuLayout from './PushMenuLayout' import * as utils from './utils' import * as core from './core' import * as html from './html' import * as components from './components' + export { + Calendar, + DoubleSidedPlane, + Grid, + Molecule, + Plane, + PushMenuLayout, + utils, core, html,
Convert exports into a format that Buble knows about
trusktr_infamous
train
41b9457887f8d0463ab0c2271b0d1adc53bdfb8c
diff --git a/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php b/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php +++ b/src/Symfony/Component/Form/Tests/Extension/Validator/Constraints/FormValidatorFunctionalTest.php @@ -17,6 +17,7 @@ use Symfony\Component\Form\CallbackTransformer; use Symfony\Component\Form\Exception\TransformationFailedException; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\FormType; +use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Validator\ValidatorExtension; use Symfony\Component\Form\FormBuilderInterface; @@ -28,6 +29,7 @@ use Symfony\Component\Validator\Constraints\Expression; use Symfony\Component\Validator\Constraints\GroupSequence; use Symfony\Component\Validator\Constraints\Length; use Symfony\Component\Validator\Constraints\NotBlank; +use Symfony\Component\Validator\Constraints\Valid; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory; use Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader; @@ -293,6 +295,39 @@ class FormValidatorFunctionalTest extends TestCase $this->assertSame('children[field2].data', $violations[1]->getPropertyPath()); } + public function testCascadeValidationToChildFormsWithTwoValidConstraints() + { + $form = $this->formFactory->create(ReviewType::class); + + $form->submit([ + 'rating' => 1, + 'title' => 'Sample Title', + ]); + + $violations = $this->validator->validate($form); + + $this->assertCount(1, $violations); + $this->assertSame('This value should not be blank.', $violations[0]->getMessage()); + $this->assertSame('children[author].data.email', $violations[0]->getPropertyPath()); + } + + public function testCascadeValidationToChildFormsWithTwoValidConstraints2() + { + $form = $this->formFactory->create(ReviewType::class); + + $form->submit([ + 'title' => 'Sample Title', + ]); + + $violations = $this->validator->validate($form); + + $this->assertCount(2, $violations); + $this->assertSame('This value should not be blank.', $violations[0]->getMessage()); + $this->assertSame('data.rating', $violations[0]->getPropertyPath()); + $this->assertSame('This value should not be blank.', $violations[1]->getMessage()); + $this->assertSame('children[author].data.email', $violations[1]->getPropertyPath()); + } + public function testCascadeValidationToChildFormsUsingPropertyPathsValidatedInSequence() { $form = $this->formFactory->create(FormType::class, null, [ @@ -451,3 +486,62 @@ class FooType extends AbstractType $resolver->setDefault('data_class', Foo::class); } } + +class Review +{ + public $rating; + public $title; + public $author; + + public static function loadValidatorMetadata(ClassMetadata $metadata) + { + $metadata->addPropertyConstraint('title', new NotBlank()); + $metadata->addPropertyConstraint('rating', new NotBlank()); + } +} + +class ReviewType extends AbstractType +{ + public function buildForm(FormBuilderInterface $builder, array $options) + { + $builder + ->add('rating', IntegerType::class, [ + 'constraints' => [new Valid()], + ]) + ->add('title') + ->add('author', CustomerType::class, [ + 'constraints' => [new Valid()], + ]) + ; + } + + public function configureOptions(OptionsResolver $resolver) + { + $resolver->setDefault('data_class', Review::class); + } +} + +class Customer +{ + public $email; + + public static function loadValidatorMetadata(ClassMetadata $metadata) + { + $metadata->addPropertyConstraint('email', new NotBlank()); + } +} + +class CustomerType extends AbstractType +{ + public function buildForm(FormBuilderInterface $builder, array $options) + { + $builder + ->add('email') + ; + } + + public function configureOptions(OptionsResolver $resolver) + { + $resolver->setDefault('data_class', Customer::class); + } +}
[Test] Reproduce issue with cascading validation
symfony_symfony
train
8730271dc310c12b19d45666da06e023d652b2ee
diff --git a/metpy/plots/tests/test_skewt.py b/metpy/plots/tests/test_skewt.py index <HASH>..<HASH> 100644 --- a/metpy/plots/tests/test_skewt.py +++ b/metpy/plots/tests/test_skewt.py @@ -14,7 +14,9 @@ from metpy.units import units # TODO: Need at some point to do image-based comparison, but that's a lot to # bite off right now class TestSkewT(object): - def test_api(self): + 'Test SkewT' + @staticmethod + def test_api(): 'Test the SkewT api' fig = Figure(figsize=(9, 9)) skew = SkewT(fig) @@ -35,14 +37,16 @@ class TestSkewT(object): with tempfile.NamedTemporaryFile() as f: FigureCanvasAgg(fig).print_png(f.name) - def test_subplot(self): + @staticmethod + def test_subplot(): 'Test using SkewT on a sub-plot' fig = Figure(figsize=(9, 9)) SkewT(fig, subplot=(2, 2, 1)) with tempfile.NamedTemporaryFile() as f: FigureCanvasAgg(fig).print_png(f.name) - def test_gridspec(self): + @staticmethod + def test_gridspec(): 'Test using SkewT on a sub-plot' fig = Figure(figsize=(9, 9)) gs = GridSpec(1, 2) @@ -52,6 +56,7 @@ class TestSkewT(object): class TestHodograph(object): + 'Test Hodograph' @staticmethod def test_basic_api(): 'Basic test of Hodograph API'
Clean-ups for skewt tests.
Unidata_MetPy
train
7eb8acbc75c819e5dc4fe3f429885d91c222b8d2
diff --git a/sentinelhub/decoding.py b/sentinelhub/decoding.py index <HASH>..<HASH> 100644 --- a/sentinelhub/decoding.py +++ b/sentinelhub/decoding.py @@ -44,13 +44,12 @@ def decode_data(response_content, data_type): try: return { - MimeType.TAR: decode_tar, MimeType.RAW: response_content, MimeType.TXT: response_content, MimeType.ZIP: BytesIO(response_content) }[data_type] except KeyError as exception: - raise ValueError('Unknown response data type {}'.format(data_type)) from exception + raise ValueError(f'Decoding data format {data_type} is not supported') from exception def decode_image(data, image_type): @@ -156,8 +155,8 @@ def fix_jp2_image(image, bit_depth): raise IOError('Failed to read JPEG 2000 image correctly. Most likely reason is that Pillow did not ' 'install OpenJPEG library correctly. Try reinstalling Pillow from a wheel') from exception - raise ValueError('Bit depth {} of jp2 image is currently not supported. ' - 'Please raise an issue on package Github page'.format(bit_depth)) + raise ValueError(f'Bit depth {bit_depth} of jp2 image is currently not supported. ' + 'Please raise an issue on package Github page') def get_data_format(filename): diff --git a/sentinelhub/io_utils.py b/sentinelhub/io_utils.py index <HASH>..<HASH> 100644 --- a/sentinelhub/io_utils.py +++ b/sentinelhub/io_utils.py @@ -39,33 +39,43 @@ def read_data(filename, data_format=None): :raises: exception if filename does not exist """ if not os.path.exists(filename): - raise ValueError('Filename {} does not exist'.format(filename)) + raise FileNotFoundError(f'Filename {filename} does not exist') if not isinstance(data_format, MimeType): data_format = get_data_format(filename) - if data_format is MimeType.RAW: - with open(filename, 'rb') as file: - return file.read() + reader = _get_reader(data_format) + try: + return reader(filename) + except BaseException as exception: + # In case a procedure would read a lot of files and one would be corrupt this helps us figure out which one + LOGGER.debug('Failed to read from file: %s', filename) + raise exception + + +def _get_reader(data_format): + """ Provides a function for reading data in a given data format + """ if data_format is MimeType.TIFF: - return read_tiff_image(filename) + return read_tiff_image if data_format is MimeType.JP2: - return read_jp2_image(filename) + return read_jp2_image if data_format.is_image_format(): - return read_image(filename) + return read_image try: return { MimeType.TAR: read_tar, MimeType.TXT: read_text, + MimeType.RAW: _read_binary, MimeType.CSV: read_csv, MimeType.JSON: read_json, MimeType.XML: read_xml, MimeType.GML: read_xml, MimeType.SAFE: read_xml - }[data_format](filename) + }[data_format] except KeyError as exception: - raise ValueError('Reading data format .{} is not supported'.format(data_format.value)) from exception + raise ValueError(f'Reading data format {data_format} is not supported') from exception def read_tar(filename): @@ -120,7 +130,14 @@ def read_text(filename): :return: data stored in text file """ with open(filename, 'r') as file: - return file.read() # file.readline() for reading 1 line + return file.read() + + +def _read_binary(filename): + """ Reads data in bytes + """ + with open(filename, 'rb') as file: + return file.read() def read_csv(filename, delimiter=CSV_DELIMITER): @@ -143,7 +160,7 @@ def read_json(filename): :type filename: str :return: data stored in JSON file """ - with open(filename, 'r') as file: + with open(filename, 'rb') as file: return json.load(file) @@ -207,7 +224,7 @@ def write_data(filename, data, data_format=None, compress=False, add=False): MimeType.GML: write_xml }[data_format](filename, data) except KeyError as exception: - raise ValueError('Writing data format .{} is not supported'.format(data_format.value)) from exception + raise ValueError(f'Writing data format {data_format} is not supported') from exception def write_tiff_image(filename, image, compress=False): @@ -221,7 +238,7 @@ def write_tiff_image(filename, image, compress=False): :type compress: bool """ if compress: - return tiff.imsave(filename, image, compress='lzma') # loseless compression, works very well on masks + return tiff.imsave(filename, image, compress='lzma') # lossless compression, works very well on masks return tiff.imsave(filename, image)
io and decoding updates, logging failed reads
sentinel-hub_sentinelhub-py
train
c8ec8301f67991cbcc9a6220889f3e1e92baaaa2
diff --git a/bundles/org.eclipse.orion.client.editor/web/orion/editor/textView.js b/bundles/org.eclipse.orion.client.editor/web/orion/editor/textView.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.editor/web/orion/editor/textView.js +++ b/bundles/org.eclipse.orion.client.editor/web/orion/editor/textView.js @@ -6412,19 +6412,6 @@ define("orion/editor/textView", [ //$NON-NLS-0$ var viewPad = this._getViewPadding(); var lineCount = model.getLineCount(); var lineHeight = this._getLineHeight(); - var clientWidth = this._getClientWidth(), clientWidthNoScroll, clientWidthScroll; - if (!this._singleMode && !this._wrapMode) { - if (viewDiv.style.overflowY === "scroll") { //$NON-NLS-0$ - clientWidthNoScroll = clientWidth + this._metrics.scrollWidth; - clientWidthScroll = clientWidth; - } else { - clientWidthNoScroll = clientWidth; - clientWidthScroll = clientWidth - this._metrics.scrollWidth; - } - if (this._wrapMode) { - clientDiv.style.width = clientWidth + "px"; //$NON-NLS-0$ - } - } /* * topIndex - top line index of the view (maybe be particialy visible) @@ -6434,7 +6421,7 @@ define("orion/editor/textView", [ //$NON-NLS-0$ */ var topIndex, lineStart, top, topIndexY, leftWidth, leftRect, - clientHeight, scrollWidth, scrollHeight, + clientWidth, clientHeight, scrollWidth, scrollHeight, totalHeight = 0, totalLineIndex = 0, tempLineHeight; if (this._lineHeight) { while (totalLineIndex < lineCount) { @@ -6463,23 +6450,14 @@ define("orion/editor/textView", [ //$NON-NLS-0$ var parent = this._parent; var parentWidth = parent.clientWidth; var parentHeight = parent.clientHeight; - clientHeight = this._getClientHeight(); - var clientHeightNoScroll, clientHeightScroll; - if (!this._singleMode && !this._wrapMode) { - if (viewDiv.style.overflowX === "scroll") { //$NON-NLS-0$ - clientHeightNoScroll = clientHeight + this._metrics.scrollWidth; - clientHeightScroll = clientHeight; - } else { - clientHeightNoScroll = clientHeight; - clientHeightScroll = clientHeight - this._metrics.scrollWidth; - } - } if (hScrollOnly) { leftWidth = 0; if (this._leftDiv) { leftRect = this._leftDiv.getBoundingClientRect(); leftWidth = leftRect.right - leftRect.left; } + clientWidth = this._getClientWidth(); + clientHeight = this._getClientHeight(); scrollWidth = clientWidth; if (!this._wrapMode) { scrollWidth = Math.max(this._maxLineWidth, scrollWidth); @@ -6491,6 +6469,7 @@ define("orion/editor/textView", [ //$NON-NLS-0$ } scrollHeight = totalHeight; } else { + clientHeight = this._getClientHeight(); var linesPerPage = Math.floor((clientHeight + topIndexY) / lineHeight); var bottomIndex = Math.min(topIndex + linesPerPage, lineCount - 1); @@ -6623,7 +6602,24 @@ define("orion/editor/textView", [ //$NON-NLS-0$ var scrollDiv = this._scrollDiv; scrollDiv.style.height = scrollHeight + "px"; //$NON-NLS-0$ + clientWidth = this._getClientWidth(); if (!this._singleMode && !this._wrapMode) { + var clientHeightNoScroll, clientHeightScroll; + if (viewDiv.style.overflowX === "scroll") { //$NON-NLS-0$ + clientHeightNoScroll = clientHeight + this._metrics.scrollWidth; + clientHeightScroll = clientHeight; + } else { + clientHeightNoScroll = clientHeight; + clientHeightScroll = clientHeight - this._metrics.scrollWidth; + } + var clientWidthNoScroll, clientWidthScroll; + if (viewDiv.style.overflowY === "scroll") { //$NON-NLS-0$ + clientWidthNoScroll = clientWidth + this._metrics.scrollWidth; + clientWidthScroll = clientWidth; + } else { + clientWidthNoScroll = clientWidth; + clientWidthScroll = clientWidth - this._metrics.scrollWidth; + } var hScroll = false, vScroll = false; clientHeight = clientHeightNoScroll; clientWidth = clientWidthNoScroll; @@ -6746,11 +6742,8 @@ define("orion/editor/textView", [ //$NON-NLS-0$ var ensureCaretVisible = this._ensureCaretVisible; this._ensureCaretVisible = false; - if (clientHeight !== this._getClientHeight() || clientWidth !== this._getClientWidth()) { - this._update(); - if (ensureCaretVisible) { - this._showCaret(); - } + if (ensureCaretVisible) { + this._showCaret(); } }, _updateOverflow: function() {
Bug <I> - Editor infinite loop on IE 9 and IE <I> (more improvements)
eclipse_orion.client
train
c8edcde2d571cf546640082d79d9e8c6e1b92763
diff --git a/internal/graphics/command.go b/internal/graphics/command.go index <HASH>..<HASH> 100644 --- a/internal/graphics/command.go +++ b/internal/graphics/command.go @@ -275,11 +275,11 @@ func adjustImageForTexture(img *image.RGBA) *image.RGBA { func (c *newImageFromImageCommand) Exec(context *opengl.Context, indexOffsetInBytes int) error { origSize := c.img.Bounds().Size() - if origSize.X < 4 { - return errors.New("graphics: width must be equal or more than 4.") + if origSize.X < 1 { + return errors.New("graphics: width must be equal or more than 1.") } - if origSize.Y < 4 { - return errors.New("graphics: height must be equal or more than 4.") + if origSize.Y < 1 { + return errors.New("graphics: height must be equal or more than 1.") } adjustedImage := adjustImageForTexture(c.img) size := adjustedImage.Bounds().Size() @@ -307,11 +307,11 @@ type newImageCommand struct { func (c *newImageCommand) Exec(context *opengl.Context, indexOffsetInBytes int) error { w := int(NextPowerOf2Int32(int32(c.width))) h := int(NextPowerOf2Int32(int32(c.height))) - if w < 4 { - return errors.New("graphics: width must be equal or more than 4.") + if w < 1 { + return errors.New("graphics: width must be equal or more than 1.") } - if h < 4 { - return errors.New("graphics: height must be equal or more than 4.") + if h < 1 { + return errors.New("graphics: height must be equal or more than 1.") } native, err := context.NewTexture(w, h, nil, c.filter) if err != nil { @@ -334,11 +334,11 @@ type newScreenFramebufferImageCommand struct { } func (c *newScreenFramebufferImageCommand) Exec(context *opengl.Context, indexOffsetInBytes int) error { - if c.width < 4 { - return errors.New("graphics: width must be equal or more than 4.") + if c.width < 1 { + return errors.New("graphics: width must be equal or more than 1.") } - if c.height < 4 { - return errors.New("graphics: height must be equal or more than 4.") + if c.height < 1 { + return errors.New("graphics: height must be equal or more than 1.") } f := &framebuffer{ native: context.ScreenFramebuffer(),
graphics: Image minimum size changed to 1
hajimehoshi_ebiten
train
091f5394e2d7c38ea891b3997e214c8bc0c62994
diff --git a/simanneal/anneal.py b/simanneal/anneal.py index <HASH>..<HASH> 100644 --- a/simanneal/anneal.py +++ b/simanneal/anneal.py @@ -43,7 +43,7 @@ class Annealer(object): save_state_on_exit = True def __init__(self, initial_state=None, load_state=None): - if initial_state: + if len(initial_state) > 0: self.state = self.copy_state(initial_state) elif load_state: with open(load_state, 'rb') as fh:
Support state variable of type numpy.ndarray Fix the error with numpy arrays
perrygeo_simanneal
train
d7f780e0664ebb939ce76d987cd30c6eec496dc7
diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index <HASH>..<HASH> 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Fix for deep includes on the same association. [richcollins@gmail.com] + * Tweak fixtures so they don't try to use a non-ActiveRecord class. [Kevin Clark] * Remove ActiveRecord::Base.reset since Dispatcher doesn't use it anymore. [Rick Olson] diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index <HASH>..<HASH> 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1393,11 +1393,13 @@ module ActiveRecord unless join_dependency.table_aliases[aliased_table_name].zero? # if the table name has been used, then use an alias - @aliased_table_name = active_record.connection.table_alias_for "#{pluralize(reflection.name)}_#{parent_table_name}" + @aliased_table_name = cascade_alias table_index = join_dependency.table_aliases[aliased_table_name] + join_dependency.table_aliases[@aliased_table_name] += 1 @aliased_table_name = @aliased_table_name[0..active_record.connection.table_alias_length-3] + "_#{table_index+1}" if table_index > 0 + else + join_dependency.table_aliases[aliased_table_name] += 1 end - join_dependency.table_aliases[aliased_table_name] += 1 if reflection.macro == :has_and_belongs_to_many || (reflection.macro == :has_many && reflection.options[:through]) @aliased_join_table_name = reflection.macro == :has_and_belongs_to_many ? reflection.options[:join_table] : reflection.through_reflection.klass.table_name @@ -1529,6 +1531,11 @@ module ActiveRecord def interpolate_sql(sql) instance_eval("%@#{sql.gsub('@', '\@')}@") end + + private + def cascade_alias + active_record.connection.table_alias_for "#{pluralize(reflection.name)}_#{parent_table_name}" + end end end end diff --git a/activerecord/test/associations_cascaded_eager_loading_test.rb b/activerecord/test/associations_cascaded_eager_loading_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/associations_cascaded_eager_loading_test.rb +++ b/activerecord/test/associations_cascaded_eager_loading_test.rb @@ -103,4 +103,9 @@ class CascadedEagerLoadingTest < Test::Unit::TestCase authors.first.posts.first.special_comments.first.post.very_special_comment end end + + def test_eager_association_loading_with_recursive_cascaded_three_levels + root_node = RecursivelyCascadedTreeMixin.find(:first, :include=>{:children=>{:children=>:children}}, :order => 'mixins.id') + assert_equal mixins(:recursively_cascaded_tree_4), assert_no_queries { root_node.children.first.children.first.children.first } + end end diff --git a/activerecord/test/fixtures/mixin.rb b/activerecord/test/fixtures/mixin.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/fixtures/mixin.rb +++ b/activerecord/test/fixtures/mixin.rb @@ -10,6 +10,10 @@ class TreeMixinWithoutOrder < Mixin acts_as_tree :foreign_key => "parent_id" end +class RecursivelyCascadedTreeMixin < Mixin + acts_as_tree :foreign_key => "parent_id" +end + class ListMixin < Mixin acts_as_list :column => "pos", :scope => :parent diff --git a/activerecord/test/fixtures/mixins.yml b/activerecord/test/fixtures/mixins.yml index <HASH>..<HASH> 100644 --- a/activerecord/test/fixtures/mixins.yml +++ b/activerecord/test/fixtures/mixins.yml @@ -39,6 +39,26 @@ tree_without_order_2: type: TreeMixinWithoutOrder parent_id: +recursively_cascaded_tree_1: + id: 5005 + type: RecursivelyCascadedTreeMixin + parent_id: + +recursively_cascaded_tree_2: + id: 5006 + type: RecursivelyCascadedTreeMixin + parent_id: 5005 + +recursively_cascaded_tree_3: + id: 5007 + type: RecursivelyCascadedTreeMixin + parent_id: 5006 + +recursively_cascaded_tree_4: + id: 5008 + type: RecursivelyCascadedTreeMixin + parent_id: 5007 + # List mixins <% (1..4).each do |counter| %>
Fix for deep includes on the same association. git-svn-id: <URL>
rails_rails
train
d77895846efcd0db7da64e1db046b1e02d8c35c7
diff --git a/org/postgresql/core/v3/SimpleParameterList.java b/org/postgresql/core/v3/SimpleParameterList.java index <HASH>..<HASH> 100644 --- a/org/postgresql/core/v3/SimpleParameterList.java +++ b/org/postgresql/core/v3/SimpleParameterList.java @@ -4,7 +4,7 @@ * Copyright (c) 2004, Open Cloud Limited. * * IDENTIFICATION -* $PostgreSQL: pgjdbc/org/postgresql/core/v3/SimpleParameterList.java,v 1.12 2006/05/22 09:52:37 jurka Exp $ +* $PostgreSQL: pgjdbc/org/postgresql/core/v3/SimpleParameterList.java,v 1.13 2006/05/23 23:05:21 jurka Exp $ * *------------------------------------------------------------------------- */ @@ -193,7 +193,7 @@ class SimpleParameterList implements V3ParameterList { if (paramTypes[index-1] == Oid.UNSPECIFIED) { paramTypes[index-1] = oid; } else if (paramTypes[index-1] != oid) { - throw new IllegalArgumentException("Can't change resolved type for param: " + index + " from " + paramTypes[index] + " to " + oid); + throw new IllegalArgumentException("Can't change resolved type for param: " + index + " from " + paramTypes[index-1] + " to " + oid); } }
Error message has the wrong index into the paramTypes array. Nathan Keynes
pgjdbc_pgjdbc
train
b2dde77bb3ed132325a4cb5590e7679b70f53eab
diff --git a/src/lib/shortcuts.js b/src/lib/shortcuts.js index <HASH>..<HASH> 100644 --- a/src/lib/shortcuts.js +++ b/src/lib/shortcuts.js @@ -1,6 +1,6 @@ /* globals AFRAME */ var Events = require('./Events'); -import {removeSelectedEntity, cloneSelectedEntity} from '../actions/entity'; +import {removeSelectedEntity, cloneSelectedEntity, cloneEntity} from '../actions/entity'; function shouldCaptureKeyEvent (event) { if (event.metaKey) { return false; } @@ -57,11 +57,29 @@ module.exports = { if (event.keyCode === 68) { cloneSelectedEntity(); } + + }, + onKeyDown: function (event) { + // c: copy selected entity + if (event.keyCode === 67) { + if(AFRAME.INSPECTOR.selected && (event.ctrlKey || event.metaKey) && document.activeElement.tagName !== "INPUT") { + AFRAME.INSPECTOR.copiedEntity = AFRAME.INSPECTOR.selectedEntity; + } + } + + // v: paste copied entity + if (event.keyCode === 86) { + if(AFRAME.INSPECTOR.copiedEntity && (event.ctrlKey || event.metaKey) && document.activeElement.tagName !== "INPUT") { + cloneEntity(AFRAME.INSPECTOR.copiedEntity); + } + } }, enable: function () { window.addEventListener('keyup', this.onKeyUp, false); + window.addEventListener('keydown', this.onKeyDown, false); }, disable: function () { window.removeEventListener('keyup', this.onKeyUp); + window.removeEventListener('keydown', this.onKeyDown); } };
Added functionality to copy and paste entities (#<I>) * Shifted to metaKey and ctrlKey to detect if control or command is pressed * Added copy paste functionality * Reset controlPressed on releasing control key * Added check to consider focussed inputs while copying and pasting entities
aframevr_aframe-inspector
train
1934fc73e8608a846afcf4e6e06aa4d0b61cac56
diff --git a/cmd/mungedocs/links.go b/cmd/mungedocs/links.go index <HASH>..<HASH> 100644 --- a/cmd/mungedocs/links.go +++ b/cmd/mungedocs/links.go @@ -17,6 +17,7 @@ limitations under the License. package main import ( + "errors" "fmt" "net/url" "os" @@ -33,11 +34,12 @@ var ( ) func processLink(in string, filePath string) (string, error) { - var err error + var errs []string out := linkRE.ReplaceAllStringFunc(in, func(in string) string { + var err error match := linkRE.FindStringSubmatch(in) if match == nil { - err = fmt.Errorf("Detected this line had a link, but unable to parse, %v", in) + errs = append(errs, fmt.Sprintf("Detected this line had a link, but unable to parse, %v", in)) return "" } // match[0] is the entire expression; @@ -56,8 +58,8 @@ func processLink(in string, filePath string) (string, error) { u, terr := url.Parse(linkText) if terr != nil { - err = fmt.Errorf("link %q is unparsable: %v", linkText, terr) - return "" + errs = append(errs, fmt.Sprintf("link %q is unparsable: %v", linkText, terr)) + return in } if u.Host != "" && u.Host != "github.com" { @@ -69,8 +71,8 @@ func processLink(in string, filePath string) (string, error) { if u.Path != "" && !strings.HasPrefix(linkText, "TODO:") { newPath, targetExists := checkPath(filePath, path.Clean(u.Path)) if !targetExists { - err = fmt.Errorf("%q: target not found", linkText) - return "" + errs = append(errs, fmt.Sprintf("%q: target not found", linkText)) + return in } u.Path = newPath if strings.HasPrefix(u.Path, "/") { @@ -87,7 +89,8 @@ func processLink(in string, filePath string) (string, error) { dir := path.Dir(filePath) suggestedVisibleText, err = makeRepoRelative(path.Join(dir, u.Path), filePath) if err != nil { - return "" + errs = append(errs, fmt.Sprintf("%q: unable to make path relative", filePath)) + return in } } else { suggestedVisibleText = u.Path @@ -109,8 +112,8 @@ func processLink(in string, filePath string) (string, error) { return fmt.Sprintf("[%s](%s)", visibleText, linkText+altText) }) - if out == "" { - return in, err + if len(errs) != 0 { + return "", errors.New(strings.Join(errs, ",")) } return out, nil }
mungedocs: fix ignored errors in link checker Before this change the link checker would ignore errors in a file if the last link in a file was correct. The last link would wipe out the error variable and set it to nil. Furthermore, it replaced errored links with the empty string. If we find an error that we can't correct, append the error message to an an errs slice and leave the string as is.
kubernetes_kubernetes
train
f82c98424d55f338e31e09edf3d924fcd8c71236
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.6.1 + +* Fixed bug in `\Awesomite\ErrorDumper\Handlers\ErrorHandler::handleError` - POLICY_ALL didn't work properly + ## 0.6.0 Version `0.6.0` is **incompatible** with `0.5.0`. diff --git a/src/Awesomite/ErrorDumper/Handlers/ErrorHandler.php b/src/Awesomite/ErrorDumper/Handlers/ErrorHandler.php index <HASH>..<HASH> 100644 --- a/src/Awesomite/ErrorDumper/Handlers/ErrorHandler.php +++ b/src/Awesomite/ErrorDumper/Handlers/ErrorHandler.php @@ -108,7 +108,7 @@ class ErrorHandler implements ErrorHandlerInterface { if ( ($this->mode & $code) - && ((error_reporting() & $code) || ($this->mode === static::POLICY_ALL)) + && ((error_reporting() & $code) || ($this->policy === static::POLICY_ALL)) ) { $this->onError(new ErrorException($message, $code, $file, $line)); } diff --git a/tests/Awesomite/ErrorDumper/Handlers/ErrorHandlerTest.php b/tests/Awesomite/ErrorDumper/Handlers/ErrorHandlerTest.php index <HASH>..<HASH> 100644 --- a/tests/Awesomite/ErrorDumper/Handlers/ErrorHandlerTest.php +++ b/tests/Awesomite/ErrorDumper/Handlers/ErrorHandlerTest.php @@ -94,6 +94,16 @@ class ErrorHandlerTest extends TestBase $this->assertSame(0, $beeper->countBeeps()); $errorHandler->handleError(E_ERROR, 'Test', __FILE__, __LINE__); $this->assertSame(1, $beeper->countBeeps()); + + $beeper->reset(); + $secondErrorHandler = $this->createTestErrorHandler($beeper, null, ErrorHandler::POLICY_ALL); + $secondErrorHandler->handleError(E_NOTICE, 'E_NOTICE', __FILE__, __LINE__); + $this->assertSame(1, $beeper->countBeeps()); + + $beeper->reset(); + $thirdErrorHandler = $this->createTestErrorHandler($beeper, E_ALL ^ E_NOTICE, ErrorHandler::POLICY_ALL); + $thirdErrorHandler->handleError(E_NOTICE, 'E_NOTICE', __FILE__, __LINE__); + $this->assertSame(0, $beeper->countBeeps()); } public function testSkippedError()
Fixed bug in `\Awesomite\ErrorDumper\Handlers\ErrorHandler::handleError` - POLICY_ALL didn't work properly
awesomite_error-dumper
train
d245adf7a7f7877ab3036e41596ece6fcee5e68a
diff --git a/chef/lib/chef/provider/package/easy_install.rb b/chef/lib/chef/provider/package/easy_install.rb index <HASH>..<HASH> 100644 --- a/chef/lib/chef/provider/package/easy_install.rb +++ b/chef/lib/chef/provider/package/easy_install.rb @@ -62,16 +62,15 @@ class Chef end def candidate_version - return @candidate_version if @candidate_version - @canidate_version = @new_resource.version - @candidate_version + no_version = "" + no_version end def install_package(name, version) - if version - run_command(:command => "#{easy_install_binary_path} \"#{name}==#{version}\"") - else + if version == "" run_command(:command => "#{easy_install_binary_path} #{name}") + else + run_command(:command => "#{easy_install_binary_path} \"#{name}==#{version}\"") end end diff --git a/chef/lib/chef/resource/easy_install_package.rb b/chef/lib/chef/resource/easy_install_package.rb index <HASH>..<HASH> 100644 --- a/chef/lib/chef/resource/easy_install_package.rb +++ b/chef/lib/chef/resource/easy_install_package.rb @@ -20,7 +20,7 @@ require 'chef/resource/package' class Chef class Resource - class EasyInstall < Chef::Resource::Package + class EasyInstallPackage < Chef::Resource::Package def initialize(name, collection=nil, node=nil) super(name, collection, node) @@ -28,7 +28,6 @@ class Chef @provider = Chef::Provider::Package::EasyInstall end - # Sets a custom easy_install_binary to run for easy_install commands. def easy_install_binary(arg=nil) set_or_return( :easy_install_binary,
added in actions but package version stuff broken
chef_chef
train
78f83865a337efdf330d17c3bdff531b070c4013
diff --git a/test/test_git_deploy.go b/test/test_git_deploy.go index <HASH>..<HASH> 100644 --- a/test/test_git_deploy.go +++ b/test/test_git_deploy.go @@ -78,7 +78,7 @@ func (r *gitRepo) git(args ...string) *CmdResult { } var Attempts = attempt.Strategy{ - Total: 20 * time.Second, + Total: 60 * time.Second, Delay: 500 * time.Millisecond, }
test: Increase buildpack test HTTP request attempts
flynn_flynn
train
1f26420d392a5ab4c7b7fe1911c0268b45d01ab8
diff --git a/hugolib/permalinks.go b/hugolib/permalinks.go index <HASH>..<HASH> 100644 --- a/hugolib/permalinks.go +++ b/hugolib/permalinks.go @@ -16,6 +16,7 @@ package hugolib import ( "errors" "fmt" + "path" "regexp" "strconv" "strings" @@ -182,6 +183,12 @@ func pageToPermalinkSection(p *Page, _ string) (string, error) { return p.Section(), nil } +func pageToPermalinkSections(p *Page, _ string) (string, error) { + // TODO(bep) we have some superflous URLize in this file, but let's + // deal with that later. + return path.Join(p.current().sections...), nil +} + func init() { knownPermalinkAttributes = map[string]pageToPermaAttribute{ "year": pageToPermalinkDate, @@ -192,6 +199,7 @@ func init() { "weekdayname": pageToPermalinkDate, "yearday": pageToPermalinkDate, "section": pageToPermalinkSection, + "sections": pageToPermalinkSections, "title": pageToPermalinkTitle, "slug": pageToPermalinkSlugElseTitle, "filename": pageToPermalinkFilename, diff --git a/hugolib/site_sections_test.go b/hugolib/site_sections_test.go index <HASH>..<HASH> 100644 --- a/hugolib/site_sections_test.go +++ b/hugolib/site_sections_test.go @@ -32,6 +32,10 @@ func TestNestedSections(t *testing.T) { th = testHelper{cfg, fs, t} ) + cfg.Set("permalinks", map[string]string{ + "perm a": ":sections/:title", + }) + pageTemplate := `--- title: T%d_%d --- @@ -64,6 +68,15 @@ Content writeSource(t, fs, filepath.Join("content", "empty3", "b", "c", "d", "_index.md"), fmt.Sprintf(pageTemplate, 41, -1)) writeSource(t, fs, filepath.Join("content", "empty3", "b", "empty3.md"), fmt.Sprintf(pageTemplate, 3, -1)) + // Section with permalink config + writeSource(t, fs, filepath.Join("content", "perm a", "link", "_index.md"), fmt.Sprintf(pageTemplate, 9, -1)) + for i := 1; i < 4; i++ { + writeSource(t, fs, filepath.Join("content", "perm a", "link", fmt.Sprintf("page_%d.md", i)), + fmt.Sprintf(pageTemplate, 1, i)) + } + writeSource(t, fs, filepath.Join("content", "perm a", "link", "regular", fmt.Sprintf("page_%d.md", 5)), + fmt.Sprintf(pageTemplate, 1, 5)) + writeSource(t, fs, filepath.Join("content", "l1", "l2", "_index.md"), fmt.Sprintf(pageTemplate, 2, -1)) writeSource(t, fs, filepath.Join("content", "l1", "l2_2", "_index.md"), fmt.Sprintf(pageTemplate, 22, -1)) writeSource(t, fs, filepath.Join("content", "l1", "l2", "l3", "_index.md"), fmt.Sprintf(pageTemplate, 3, -1)) @@ -96,7 +109,7 @@ PAG|{{ .Title }}|{{ $sect.InSection . }} cfg.Set("paginate", 2) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) - require.Len(t, s.RegularPages, 14) + require.Len(t, s.RegularPages, 18) tests := []struct { sections string @@ -185,6 +198,18 @@ PAG|{{ .Title }}|{{ $sect.InSection . }} assert.Equal("T2_-1", p.Parent().Title) assert.Len(p.Sections(), 0) }}, + {"perm a,link", func(p *Page) { + assert.Equal("T9_-1", p.Title) + assert.Equal("/perm-a/link/", p.RelPermalink()) + assert.Len(p.Pages, 4) + first := p.Pages[0] + assert.Equal("/perm-a/link/t1_1/", first.RelPermalink()) + th.assertFileContent("public/perm-a/link/t1_1/index.html", "Single|T1_1") + + last := p.Pages[3] + assert.Equal("/perm-a/link/t1_5/", last.RelPermalink()) + + }}, } for _, test := range tests { @@ -203,7 +228,7 @@ PAG|{{ .Title }}|{{ $sect.InSection . }} assert.NotNil(home) - assert.Len(home.Sections(), 6) + assert.Len(home.Sections(), 7) rootPage := s.getPage(KindPage, "mypage.md") assert.NotNil(rootPage)
hugolib: Support sub-sections in permalink settings This enables both the variants below: Current (first level only): ``` "blog": ":section/:title", ``` Nested (all levels): ``` "blog": ":sections/:title", ``` Should ideally been part of Hugo <I>, but better late than never ... Fixes #<I>
gohugoio_hugo
train
d042a5d99bd59ab1e665c9bf8f8ed559439ebc59
diff --git a/lib/kindle_manager/adapters/base_adapter.rb b/lib/kindle_manager/adapters/base_adapter.rb index <HASH>..<HASH> 100644 --- a/lib/kindle_manager/adapters/base_adapter.rb +++ b/lib/kindle_manager/adapters/base_adapter.rb @@ -2,7 +2,7 @@ module KindleManager class BaseAdapter include AmazonAuth::CommonExtension - attr_accessor :store, :session + attr_accessor :store, :session, :options def initialize(options) @options = options
Expose options of adapters to accept manual changes
kyamaguchi_kindle_manager
train
902d6e6b03158548a8e77a3c04bf426dfffce37c
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,9 +1,8 @@ -from setuptools import setup, find_packages -import pydle +from setuptools import setup setup( - name=pydle.__name__, - version=pydle.__version__, + name='pydle', + version='0.8.0', packages=[ 'pydle', 'pydle.features', @@ -12,7 +11,7 @@ setup( 'pydle.features.ircv3_2', 'pydle.utils' ], - requires=['tornado'], + install_requires=['tornado'], extras_require={ 'sasl': 'pure-sasl >=0.1.6', # for pydle.features.sasl 'docs': 'sphinx_rtd_theme', # the Sphinx theme we use @@ -32,7 +31,7 @@ setup( url='https://github.com/Shizmob/pydle', keywords='irc library python3 compact flexible', description='A compact, flexible and standards-abiding IRC library for Python 3.', - license=pydle.__license__, + license='BSD', zip_safe=True, test_suite='tests'
Clean up setup.py script.
Shizmob_pydle
train
a66e86b1bb2113195c57d95cdd735e5d6ae1ad4a
diff --git a/src/Generators/ModuleGenerator.php b/src/Generators/ModuleGenerator.php index <HASH>..<HASH> 100644 --- a/src/Generators/ModuleGenerator.php +++ b/src/Generators/ModuleGenerator.php @@ -276,6 +276,10 @@ class ModuleGenerator extends Generator public function generateFolders() { foreach ($this->getFolders() as $folder) { + if ($folder === false) { + return; + } + $path = $this->module->getModulePath($this->getName()) . '/' . $folder; $this->filesystem->makeDirectory($path, 0755, true); diff --git a/tests/Commands/ModuleGeneratorTest.php b/tests/Commands/ModuleGeneratorTest.php index <HASH>..<HASH> 100644 --- a/tests/Commands/ModuleGeneratorTest.php +++ b/tests/Commands/ModuleGeneratorTest.php @@ -171,6 +171,18 @@ class ModuleGeneratorTest extends BaseTestCase $this->assertTrue(str_contains($output, 'Module [Blog] created successfully.')); } + /** @test */ + public function it_can_ignore_some_folders_to_generate() + { + $this->app['config']->set('modules.paths.generator.assets', false); + $this->app['config']->set('modules.paths.generator.emails', false); + + $this->artisan('module:make', ['name' => ['Blog']]); + + $this->assertFalse(is_dir($this->modulePath . '/Assets')); + $this->assertFalse(is_dir($this->modulePath . '/Emails')); + } + private function getExpectedComposerJson() { return <<<TEXT
Add the ability to ignore some folders to generate
nWidart_laravel-modules
train
b915cb1243b6b97656a4052b19daf141753c40c0
diff --git a/hobby.gemspec b/hobby.gemspec index <HASH>..<HASH> 100644 --- a/hobby.gemspec +++ b/hobby.gemspec @@ -26,4 +26,5 @@ Gem::Specification.new do |spec| spec.add_development_dependency 'rake' spec.add_development_dependency 'minitest' spec.add_development_dependency 'minitest-power_assert' + spec.add_development_dependency 'pry' end diff --git a/lib/hobby/app.rb b/lib/hobby/app.rb index <HASH>..<HASH> 100644 --- a/lib/hobby/app.rb +++ b/lib/hobby/app.rb @@ -6,8 +6,8 @@ module Hobby class << subclass Verbs.each do |verb| - define_method verb.downcase do |path, &route| - self::Router.add_route verb, path, &route + define_method verb.downcase do |path = nil, &route| + self::Router.add_route verb, *path, &route end end diff --git a/lib/hobby/router.rb b/lib/hobby/router.rb index <HASH>..<HASH> 100644 --- a/lib/hobby/router.rb +++ b/lib/hobby/router.rb @@ -14,13 +14,13 @@ module Hobby end end - def add_route verb, path, &route + def add_route verb, path = '/', &route @patterns[verb] << Pattern.new(path, route) self end def route_for request - verb, path = request.request_method, request.path_info + verb, path = request.request_method, (request.path_info.empty? ? '/' : request.path_info) route, params = @routes[verb][path] request.params.merge! params if params route diff --git a/test/test_app.rb b/test/test_app.rb index <HASH>..<HASH> 100644 --- a/test/test_app.rb +++ b/test/test_app.rb @@ -184,4 +184,19 @@ describe Hobby::App do assert { last_response.body == 'it works' } end end + + describe :without_path do + before do + mock_app do + get do + 'root' + end + end + end + + it 'is accessible as /' do + get '/' + assert { last_response.body == 'root' } + end + end end diff --git a/test/test_router.rb b/test/test_router.rb index <HASH>..<HASH> 100644 --- a/test/test_router.rb +++ b/test/test_router.rb @@ -62,4 +62,12 @@ describe Hobby::Router do assert { route.to_proc.call == :wrapped } assert { request.params[:id] == '42' } end + + it 'handle empty path as /' do + @router.add_route 'GET' do :root end + + request = Hobby::Request.new Rack::MockRequest.env_for 'http://localhost' + route = @router.route_for request + assert { route.call == :root } + end end
Treat an empty path as a root path
ch1c0t_hobby
train
7693524076ac1164bc60bfd1d719a0ed2593d3ae
diff --git a/src/Models/Category.php b/src/Models/Category.php index <HASH>..<HASH> 100644 --- a/src/Models/Category.php +++ b/src/Models/Category.php @@ -114,7 +114,7 @@ class Category extends BaseCategory $this->setRules([ 'name' => 'required|string|max:150', 'description' => 'nullable|string|max:10000', - 'slug' => 'required|alpha_dash|max:150|unique_model:'.config('rinvex.categories.models.category').',slug', + 'slug' => 'required|alpha_dash|max:150|unique:'.config('rinvex.categories.tables.categories').',slug', NestedSet::LFT => 'sometimes|required|integer', NestedSet::RGT => 'sometimes|required|integer', NestedSet::PARENT_ID => 'nullable|integer',
Revert unique & exists validation rules to native after overriding presence verifier to use eloquent by default
rinvex_cortex-categories
train
ddf316e36c1749095313225ac3b0939140a9afb8
diff --git a/pcef/core/modes/pygments_syntax_highlighter.py b/pcef/core/modes/pygments_syntax_highlighter.py index <HASH>..<HASH> 100644 --- a/pcef/core/modes/pygments_syntax_highlighter.py +++ b/pcef/core/modes/pygments_syntax_highlighter.py @@ -34,11 +34,14 @@ from pygments.lexers.other import BatchLexer from pygments.lexers.other import HtmlLexer from pygments.lexers.compiled import CythonLexer from pygments.lexers.web import XmlLexer -from pygments.lexers.web import JsonLexer from pygments.lexers.dotnet import BooLexer from pygments.lexers.text import MakefileLexer from pygments.lexers.text import CMakeLexer from pygments.lexers.text import RstLexer +try: + from pygments.lexers.web import JsonLexer +except ImportError: # too new on some systems + JsonLexer = "NoLexerFound" from pygments.lexers.dotnet import CSharpLexer from pygments.lexers.web import ActionScriptLexer @@ -58,6 +61,8 @@ from pygments.lexers.compiled import ObjectiveCLexer from pygments.lexers.compiled import ObjectiveCppLexer from pygments.lexers.compiled import ValaLexer + + from pygments.styles import get_style_by_name from pygments.token import Whitespace, Comment from pygments.util import ClassNotFound
Fix travis build error (pygments version does not have JsonLexer)
pyQode_pyqode.core
train
bea254ed84b30f081db17e84d21d314b364dcf8f
diff --git a/functions.php b/functions.php index <HASH>..<HASH> 100644 --- a/functions.php +++ b/functions.php @@ -124,17 +124,13 @@ function pb_custom_stylesheet_imports_base() { } if ( $custom_file ) { - $custom_file_contents = file( $custom_file ); - foreach ( $custom_file_contents as $line ) { - if ( strpos( $line, '@import' ) !== false ) { - // Search for url("*.css"), url('*.css'), and url(*.css) - preg_match_all( '/url\(([\s])?([\"|\'])?(.*?)\.css([\"|\'])?([\s])?\)/i', $line, $matches, PREG_PATTERN_ORDER ); - foreach ( $matches[3] as $url ) { - if ( strpos( $url, 'themes-book/pressbooks-book/style' ) !== false ) { - $_res = true; - break 2; - } - } + $custom_file_contents = file_get_contents( $custom_file ); + // Search for @import url("*.css"), @import url('*.css'), and @import url(*.css) + preg_match_all( '/@import url\(([\s])?([\"|\'])?(.*?)\.css([\"|\'])?([\s])?\)/i', $custom_file_contents, $matches, PREG_PATTERN_ORDER ); + foreach ( $matches[3] as $url ) { + if ( stripos( $url, 'themes-book/pressbooks-book/style' ) !== false ) { + $_res = true; + break; } } }
Shorten code, imrpove reliability.
pressbooks_pressbooks
train
0da16fe23859c68c8985a36dd4909065c2e6bbae
diff --git a/src/I18n.php b/src/I18n.php index <HASH>..<HASH> 100644 --- a/src/I18n.php +++ b/src/I18n.php @@ -125,7 +125,7 @@ class I18n extends Adapter implements ServiceAwareInterface $localeFiles = array_merge(glob($localeDir . '/*.php'), glob($localeDir . '/*/*.php')); foreach ($localeFiles as $file) { $package = pathinfo($file, PATHINFO_FILENAME); - in_array($package, ['error_code']) and $package = 'error_codes'; + $package == 'error_code' and $package = 'error_codes'; $packageLocale = (array)include $file; isset($packages[$package]) or $packages[$package] = []; $packages[$package] = array_replace($packages[$package], $packageLocale); @@ -151,6 +151,7 @@ class I18n extends Adapter implements ServiceAwareInterface public function query($string, $params = null, $package = null) { $locale = $this->currentLocale; + $package == 'error_code' and $package = 'error_codes'; if ($package && isset($this->locale[$locale]['packages'][$package][$string])) { $translation = $this->locale[$locale]['packages'][$package][$string]; } elseif (isset($this->locale[$locale]['combined'][$string])) {
fix(i<I>n): make package `error_code` as alias of `error_codes`
phwoolcon_phwoolcon
train
831716e38d368c9d2a5642b3d12967685099568d
diff --git a/lib/core.js b/lib/core.js index <HASH>..<HASH> 100644 --- a/lib/core.js +++ b/lib/core.js @@ -1,7 +1,8 @@ var async = require('async'); -var funkit = require('funkit'); -var otozip = funkit.functional.otozip; -var is = require('is-js'); +var is = require('annois'); +var string = require('annostring'); +var zip = require('annozip'); + function init(app, prefix, apis, queries) { @@ -11,12 +12,12 @@ function init(app, prefix, apis, queries) { }; var context; - prefix = funkit.string.rtrim('/', prefix); + prefix = string.rtrim('/', prefix); app.get(prefix, initHandler('', handlers.pre, function(req, res) { var api = {}; - async.parallel(otozip(apis).map(function(v) { + async.parallel(zip(apis).map(function(v) { return function(cb) { queries.getMeta(v[1], function(err, d) { if(err) return console.error(err); @@ -56,7 +57,7 @@ function initAPI(app, prefix, resource, model, queries, handlers) { queries.getAll(model, req.query, operator(req, res)); }, put: function(req, res) { - var data = is.empty(req.body)? req.query: req.body; + var data = is.defined(req.body)? req.body: req.query; queries.update(model, data._id, data, operator(req, res)); }, diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -5,12 +5,14 @@ "version": "0.6.3", "dependencies": { "async": "0.2.9", - "funkit": "0.7.8", - "is-js": "0.1.1" + "annostring": "~0.2.2", + "annois": "~0.3.0", + "annozip": "~0.2.1" }, "devDependencies": { "request": "2.30.0", - "object-sugar": "0.7.1" + "object-sugar": "0.7.1", + "annofp": "~0.2.1" }, "main": "./lib", "repository": { @@ -33,4 +35,4 @@ "url": "https://github.com/sugarjs/rest-sugar/blob/master/LICENSE" } ] -} \ No newline at end of file +} diff --git a/tests/queries.js b/tests/queries.js index <HASH>..<HASH> 100644 --- a/tests/queries.js +++ b/tests/queries.js @@ -2,7 +2,7 @@ var assert = require('assert'); var request = require('request'); var sugar = require('object-sugar'); -var merge = require('funkit').common.merge; +var merge = require('annofp').merge; var utils = require('./utils');
Replace `funkit` and `is-js` with `anno` tools
sugarjs_rest-sugar
train
e5723726b587cc1d935b90de6ccc32b13db6bc36
diff --git a/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterConfigurationServiceBuilder.java b/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterConfigurationServiceBuilder.java index <HASH>..<HASH> 100644 --- a/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterConfigurationServiceBuilder.java +++ b/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterConfigurationServiceBuilder.java @@ -163,7 +163,19 @@ public class ModClusterConfigurationServiceBuilder implements ResourceServiceBui trimmedContext = parts[1].trim(); } - String path = trimmedContext.equals("ROOT") ? "" : "/" + trimmedContext; + String path; + switch (trimmedContext) { + case "ROOT": + ROOT_LOGGER.excludedContextsUseSlashInsteadROOT(); + case "/": + path = ""; + break; + default: + // normalize the context by pre-pending or removing trailing slash + trimmedContext = trimmedContext.startsWith("/") ? trimmedContext : ("/" + trimmedContext); + path = trimmedContext.endsWith("/") ? trimmedContext.substring(0, trimmedContext.length() - 1) : trimmedContext; + break; + } Set<String> paths = excludedContextsPerHost.computeIfAbsent(host, k -> new HashSet<>()); diff --git a/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterLogger.java b/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterLogger.java index <HASH>..<HASH> 100644 --- a/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterLogger.java +++ b/mod_cluster/extension/src/main/java/org/wildfly/extension/mod_cluster/ModClusterLogger.java @@ -185,7 +185,7 @@ interface ModClusterLogger extends BasicLogger { * * @param trimmedContexts value which is in the wrong format */ - @Message(id = 19, value = "'%s' is not a valid value for 'excludedContexts'.") + @Message(id = 19, value = "'%s' is not a valid value for excluded-contexts.") IllegalArgumentException excludedContextsWrongFormat(String trimmedContexts); /** @@ -193,4 +193,9 @@ interface ModClusterLogger extends BasicLogger { */ @Message(id = 20, value = "Only one of 'ssl-context' attribute or 'ssl' resource can be defined!") IllegalStateException bothElytronAndLegacySslContextDefined(); + + @LogMessage(level = WARN) + @Message(id = 21, value = "Value 'ROOT' for excluded-contexts is deprecated, to exclude the root context use '/' instead.") + void excludedContextsUseSlashInsteadROOT(); + }
WFLY-<I> mod_cluster excluded-contexts doesn't exclude slash prefixed /contexts; should perform normalization
wildfly_wildfly
train
44bc72e55d6c0f141a270c1840398e0353508757
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ shortcuts.cv_factory( # Try out two algorithms model=[ sklearn.ensemble.RandomForestClassifier( - n_estimators=20, compute_importances=True), + n_estimators=20), sklearn.linear_model.LogisticRegression(), ], diff --git a/examples/iris.py b/examples/iris.py index <HASH>..<HASH> 100644 --- a/examples/iris.py +++ b/examples/iris.py @@ -51,7 +51,7 @@ ramp.shortcuts.cv_factory( # Try out two algorithms estimator=[ sklearn.ensemble.RandomForestClassifier( - n_estimators=20, compute_importances=True), + n_estimators=20), sklearn.linear_model.LogisticRegression(), ], diff --git a/ramp/selectors.py b/ramp/selectors.py index <HASH>..<HASH> 100644 --- a/ramp/selectors.py +++ b/ramp/selectors.py @@ -45,7 +45,6 @@ class RandomForestSelector(Selector): if self.classifier: cls = ensemble.RandomForestClassifier rf = cls(n_estimators=self.n, - compute_importances=True, random_state=self.seed, n_jobs=-1) rf.fit(x.values, y.values) @@ -74,7 +73,6 @@ class RandomForestSelector(Selector): if self.classifier: cls = ensemble.RandomForestClassifier rf = cls(n_estimators=self.n, - compute_importances=True, random_state=self.seed, n_jobs=-1) rf.fit(x.values[train], y.values[train])
Drop compute_importances, deprecated since scikit_learn <I>
kvh_ramp
train
d85937fab357d25f3313cf6eb64ab9948b2418bd
diff --git a/liquibase-core/src/main/java/liquibase/diff/output/changelog/DiffToChangeLog.java b/liquibase-core/src/main/java/liquibase/diff/output/changelog/DiffToChangeLog.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/diff/output/changelog/DiffToChangeLog.java +++ b/liquibase-core/src/main/java/liquibase/diff/output/changelog/DiffToChangeLog.java @@ -439,43 +439,26 @@ public class DiffToChangeLog { }); for (DatabaseObject notSort : toNotSort) { - final String objName = notSort.toString(); - String matchedAttribute = null; - for (DatabaseObject obj : objects) { - if (obj instanceof Table) { - continue; - } - Set<String> attributes = obj.getAttributes(); - matchedAttribute = - attributes.stream() - .filter(sa -> { - if (sa.toLowerCase().contains("columns")) { - Object attrValueObj = obj.getAttribute(sa, Object.class); - if (attrValueObj instanceof ArrayList) { - ArrayList<Column> values = (ArrayList<Column>) attrValueObj; - Column matchColumn = - values.stream() - .filter(col -> { - return col == notSort; - }) - .findFirst() - .orElse(null); - return matchColumn != null; - } else { - String attrValue = (String)attrValueObj; - return attrValue.contains(objName); - } - } - return false; - }) - .findFirst() - .orElse(null); - if (matchedAttribute != null) { - toSort.add(0, notSort); - break; - } - } - if (matchedAttribute == null) { + final String notSortName = notSort.toString(); + DatabaseObject matchedObject = + objects.stream() + .filter(obj -> ! (obj instanceof Table)) + .filter(obj -> { + Set<String> attributes = obj.getAttributes(); + String matched = + attributes.stream() + .filter(sa -> { + return handleColumnDependency(notSort, notSortName, obj, sa); + }) + .findFirst() + .orElse(null); + return matched != null; + }) + .findFirst() + .orElse(null); + if (matchedObject != null) { + toSort.add(0, notSort); + } else { toSort.add(notSort); } } @@ -490,6 +473,20 @@ public class DiffToChangeLog { return new ArrayList<>(objects); } + private boolean handleColumnDependency(final DatabaseObject notSort, String objName, DatabaseObject obj, String sa) { + Object attrValueObj = obj.getAttribute(sa, Object.class); + if (attrValueObj instanceof ArrayList) { + List<Object> values = (List<Object>) attrValueObj; + return + values.stream() + .filter(item -> item instanceof Column) + .anyMatch(item -> item == notSort); + } else if (attrValueObj instanceof Column) { + return attrValueObj == notSort; + } + return false; + } + private List<Map<String, ?>> queryForDependenciesOracle(Executor executor, List<String> schemas) throws DatabaseException { List<Map<String, ?>> rs = null;
Handle ordering issue LB-<I> (cherry picked from commit b3fca<I>cd4a1d<I>c4ad<I>a<I>c6bd<I>b5c)
liquibase_liquibase
train
f27b2d1fac09203faf08549bf64203a34f59f6ca
diff --git a/src/controllers/now.js b/src/controllers/now.js index <HASH>..<HASH> 100644 --- a/src/controllers/now.js +++ b/src/controllers/now.js @@ -40,12 +40,12 @@ async function getOnlineUsers(uw) { const { User } = uw.models; const userIDs = await uw.redis.lrange('users', 0, -1); + /** @type {Omit<import('../models/User').LeanUser, 'activePlaylist' | 'exiled' | 'level'>[]} */ const users = await User.find({ _id: { $in: userIDs } }) .select({ activePlaylist: 0, exiled: 0, level: 0, - updatedAt: 0, __v: 0, }) .lean(); @@ -120,7 +120,12 @@ async function getState(req) { }; const stateKeys = Object.keys(stateShape); - const stateValues = await Promise.all(Object.values(stateShape)); + // This is a little dirty but maintaining the exact type shape is very hard here. + // We could solve that in the future by using a `p-props` style function. The npm + // module `p-props` is a bit wasteful though. + /** @type {any} */ + const values = Object.values(stateShape); + const stateValues = await Promise.all(values); const state = Object.create(null); for (let i = 0; i < stateKeys.length; i += 1) { diff --git a/src/utils/serialize.js b/src/utils/serialize.js index <HASH>..<HASH> 100644 --- a/src/utils/serialize.js +++ b/src/utils/serialize.js @@ -15,7 +15,9 @@ function serializePlaylist(model) { } /** - * @param {import('../models').User} model + * @param {Pick<import('../models').User, + * '_id' | 'username' | 'slug' | 'roles' | 'avatar' | + * 'createdAt' | 'updatedAt' | 'lastSeenAt'>} model */ function serializeUser(model) { return {
fix user serialization in /api/now
u-wave_core
train
e278b98e70b1e14e5a9bfd4a0160461b80233b7d
diff --git a/src-gwt/org/opencms/ade/contenteditor/client/CmsContentEditor.java b/src-gwt/org/opencms/ade/contenteditor/client/CmsContentEditor.java index <HASH>..<HASH> 100644 --- a/src-gwt/org/opencms/ade/contenteditor/client/CmsContentEditor.java +++ b/src-gwt/org/opencms/ade/contenteditor/client/CmsContentEditor.java @@ -2083,7 +2083,7 @@ public final class CmsContentEditor extends CmsEditorBase { */ void updateEditorValues(CmsEntity previous, CmsEntity updated) { - if (updated.getId().equals(m_entityId)) { + if (!m_isDirectEdit && updated.getId().equals(m_entityId)) { // only apply the changes to the same locale entity updateEditorValues(previous, updated, getEntity(), Collections.<String> emptyList()); }
Fixing issue where editor change handlers caused exceptions when inline editing.
alkacon_opencms-core
train
9ac332a22ed4b21a28a7fbcfaa220f45f701fa16
diff --git a/src/main/java/edu/one/core/infra/security/UserUtils.java b/src/main/java/edu/one/core/infra/security/UserUtils.java index <HASH>..<HASH> 100644 --- a/src/main/java/edu/one/core/infra/security/UserUtils.java +++ b/src/main/java/edu/one/core/infra/security/UserUtils.java @@ -116,7 +116,8 @@ public class UserUtils { .putString("sessionId", oneSessionId); } else { // remote user (oauth) findSession.putString("action", "findByUserId") - .putString("userId", remoteUserId); + .putString("userId", remoteUserId) + .putBoolean("allowDisconnectedUser", true); } eb.send(SESSION_ADDRESS, findSession, new Handler<Message<JsonObject>>() {
get userinfo with oauth2 flow for disconnected users
opendigitaleducation_web-utils
train
f68b2963db4ac7b8f0943d8b9ea101fdcbd451a5
diff --git a/moto/sts/responses.py b/moto/sts/responses.py index <HASH>..<HASH> 100644 --- a/moto/sts/responses.py +++ b/moto/sts/responses.py @@ -39,6 +39,9 @@ class TokenResponse(BaseResponse): template = self.response_template(ASSUME_ROLE_RESPONSE) return template.render(role=role) + def get_caller_identity(self): + template = self.response_template(GET_CALLER_IDENTITY_RESPONSE) + return template.render() GET_SESSION_TOKEN_RESPONSE = """<GetSessionTokenResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"> <GetSessionTokenResult> @@ -95,3 +98,15 @@ ASSUME_ROLE_RESPONSE = """<AssumeRoleResponse xmlns="https://sts.amazonaws.com/d <RequestId>c6104cbe-af31-11e0-8154-cbc7ccf896c7</RequestId> </ResponseMetadata> </AssumeRoleResponse>""" + +GET_CALLER_IDENTITY_RESPONSE = """<GetCallerIdentityResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"> + <GetCallerIdentityResult> + <Arn>arn:aws:sts::123456789012:user/moto</Arn> + <UserId>AKIAIOSFODNN7EXAMPLE</UserId> + <Account>123456789012</Account> + </GetCallerIdentityResult> + <ResponseMetadata> + <RequestId>c6104cbe-af31-11e0-8154-cbc7ccf896c7</RequestId> + </ResponseMetadata> +</GetCallerIdentityResponse> +""" diff --git a/tests/test_sts/test_server.py b/tests/test_sts/test_server.py index <HASH>..<HASH> 100644 --- a/tests/test_sts/test_server.py +++ b/tests/test_sts/test_server.py @@ -26,3 +26,14 @@ def test_sts_get_federation_token(): res.status_code.should.equal(200) res.data.should.contain(b"SessionToken") res.data.should.contain(b"AccessKeyId") + + +def test_sts_get_caller_identity(): + backend = server.create_backend_app("sts") + test_client = backend.test_client() + + res = test_client.get('/?Action=GetCallerIdentity') + res.status_code.should.equal(200) + res.data.should.contain(b"Arn") + res.data.should.contain(b"UserId") + res.data.should.contain(b"Account") diff --git a/tests/test_sts/test_sts.py b/tests/test_sts/test_sts.py index <HASH>..<HASH> 100644 --- a/tests/test_sts/test_sts.py +++ b/tests/test_sts/test_sts.py @@ -2,6 +2,7 @@ from __future__ import unicode_literals import json import boto +import boto3 from freezegun import freeze_time import sure # noqa @@ -64,3 +65,11 @@ def test_assume_role(): role.user.arn.should.equal("arn:aws:iam::123456789012:role/test-role") role.user.assume_role_id.should.contain("session-name") + +@mock_sts +def test_get_caller_identity(): + identity = boto3.client("sts").get_caller_identity() + + identity['Arn'].should.equal('arn:aws:sts::123456789012:user/moto') + identity['UserId'].should.equal('AKIAIOSFODNN7EXAMPLE') + identity['Account'].should.equal('123456789012')
sts: Implement get_caller_identity (#<I>) Return a canned response
spulec_moto
train
4fbc42b6df77f21f51baa7d88830738010e36a10
diff --git a/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/SelectResultSet.java b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/SelectResultSet.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/SelectResultSet.java +++ b/src/main/java/org/mariadb/jdbc/internal/com/read/resultset/SelectResultSet.java @@ -1051,9 +1051,12 @@ public class SelectResultSet implements ResultSet { if (isBinaryEncoded) { Date date = getInternalDate(columnInfo, cal); if (date == null) { - //specific for "zero-date", getString will return "zero-date" value -> wasNull() must then return false - lastValueNull ^= BIT_LAST_ZERO_DATE; - return new String(row.buf, row.pos, row.length, StandardCharsets.UTF_8); + if (!isBinaryEncoded) { + //specific for "zero-date", getString will return "zero-date" value -> wasNull() must then return false + lastValueNull ^= BIT_LAST_ZERO_DATE; + return new String(row.buf, row.pos, row.length, StandardCharsets.UTF_8); + } + return null; } return date.toString(); } @@ -1071,9 +1074,12 @@ public class SelectResultSet implements ResultSet { case DATETIME: Timestamp timestamp = getInternalTimestamp(columnInfo, cal); if (timestamp == null) { - //specific for "zero-date", getString will return "zero-date" value -> wasNull() must then return false - lastValueNull ^= BIT_LAST_ZERO_DATE; - return new String(row.buf, row.pos, row.length, StandardCharsets.UTF_8); + if (!isBinaryEncoded) { + //specific for "zero-date", getString will return "zero-date" value -> wasNull() must then return false + lastValueNull ^= BIT_LAST_ZERO_DATE; + return new String(row.buf, row.pos, row.length, StandardCharsets.UTF_8); + } + return null; } return timestamp.toString(); case DECIMAL: diff --git a/src/test/java/org/mariadb/jdbc/DateTest.java b/src/test/java/org/mariadb/jdbc/DateTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/mariadb/jdbc/DateTest.java +++ b/src/test/java/org/mariadb/jdbc/DateTest.java @@ -583,10 +583,14 @@ public class DateTest extends BaseTest { assertTrue(rs.next()); if (sharedUsePrepare()) { assertNull(rs.getString(1)); + assertTrue(rs.wasNull()); assertNull(rs.getDate(1)); + assertTrue(rs.wasNull()); } else { assertEquals("0000-00-00", rs.getString(1)); + assertFalse(rs.wasNull()); assertNull(rs.getDate(1)); + assertTrue(rs.wasNull()); } } catch (SQLDataException sqldataException) { //'0000-00-00' doesn't work anymore on mysql 5.7. @@ -646,8 +650,10 @@ public class DateTest extends BaseTest { assertEquals(null, resultSet.getDate(1)); if (sharedUsePrepare()) { assertEquals(null, resultSet.getString(1)); + assertTrue(resultSet.wasNull()); } else { assertTrue(resultSet.getString(1).contains("0000-00-00 00:00:00")); + assertFalse(resultSet.wasNull()); } }
[CONJ-<I>] ResultSet method wasNull() always return true after a call on a "null-date" field binary protocol handling
MariaDB_mariadb-connector-j
train
e9b268af87e514156567852a6e351c92d4208178
diff --git a/packages/veui/src/utils/dom.js b/packages/veui/src/utils/dom.js index <HASH>..<HASH> 100644 --- a/packages/veui/src/utils/dom.js +++ b/packages/veui/src/utils/dom.js @@ -19,9 +19,10 @@ export function closest (element, selectors) { return element } -let needIndeterminatePatch = null - function testIndeterminate () { + if (typeof document === 'undefined') { + return null + } let checkbox = document.createElement('input') checkbox.type = 'checkbox' checkbox.indeterminate = true @@ -32,14 +33,13 @@ function testIndeterminate () { return needPatch } +// cache test result for repeated use +let needIndeterminatePatch = testIndeterminate() + // IE won't trigger change event for indeterminate checkboxes // Problem see http://stackoverflow.com/questions/33523130/ie-does-not-fire-change-event-on-indeterminate-checkbox-when-you-click-on-it // A more thorough compatibility fix here: export function patchIndeterminate (element) { - if (needIndeterminatePatch == null) { - needIndeterminatePatch = testIndeterminate() - } - if ( !needIndeterminatePatch || !element.tagName ||
fix: test the need for indeterminate patch from the beginning instead of upon checkbox mounted to trigger unexpected events
ecomfe_veui
train
d3c095dc95f8b7da7f113a0afeb536c176d2a348
diff --git a/Library/Configuration/PlatformConfigurationHandler.php b/Library/Configuration/PlatformConfigurationHandler.php index <HASH>..<HASH> 100644 --- a/Library/Configuration/PlatformConfigurationHandler.php +++ b/Library/Configuration/PlatformConfigurationHandler.php @@ -72,7 +72,9 @@ class PlatformConfigurationHandler 'is_notification_active' => true, 'createPersonnalWorkspace' => true, 'max_storage_size' => Workspace::DEFAULT_MAX_STORAGE_SIZE, - 'max_upload_resources' => Workspace::DEFAULT_MAX_FILE_COUNT + 'max_upload_resources' => Workspace::DEFAULT_MAX_FILE_COUNT, + 'confirm_send_datas' => null, + 'token' => null ); /** diff --git a/Twig/SendDatasConfirmExtension.php b/Twig/SendDatasConfirmExtension.php index <HASH>..<HASH> 100644 --- a/Twig/SendDatasConfirmExtension.php +++ b/Twig/SendDatasConfirmExtension.php @@ -44,7 +44,7 @@ class SendDatasConfirmExtension extends \Twig_Extension public function isSendDatasConfirmed() { - return $this->platformConfigHandler->hasParameter('confirm_send_datas'); + return !is_null($this->platformConfigHandler->getParameter('confirm_send_datas')); } /**
[CoreBundle] Check if datas sending has been confirmed in platform parameters file
claroline_Distribution
train
b1bf62f0ffa9a517331336c07a6fe0445c954a2d
diff --git a/decouple.py b/decouple.py index <HASH>..<HASH> 100644 --- a/decouple.py +++ b/decouple.py @@ -2,7 +2,27 @@ from ConfigParser import SafeConfigParser -class ConfigIni(object): +class ConfigBase(object): + """ + Base class to make the API explicit. + """ + def __init__(self, config_file): + raise NotImplemented + + def get(self, option, default=u'', cast=unicode): + """ + Return the value for option or default option is not defined. + """ + raise NotImplemented + + def __call__(self, *args, **kwargs): + """ + Convenient shortcut to get. + """ + return self.get(*args, **kwargs) + + +class ConfigIni(ConfigBase): """ Wrapper around SafeConfigParser to deal with Django environment settings. """ @@ -36,12 +56,6 @@ class ConfigIni(object): return cast(getter(self.SECTION, option)) - def __call__(self, *args, **kwargs): - """ - Convenient shortcut to get. - """ - return self.get(*args, **kwargs) - def set(self, option, value): """ Add a config value to configuration instance. @@ -71,7 +85,7 @@ class ConfigIni(object): self.parser.write(f) -class ConfigEnv(object): +class ConfigEnv(ConfigBase): """ Handle .env file format used by Foreman. """ @@ -117,9 +131,4 @@ class ConfigEnv(object): return cast(self.data[option]) - def __call__(self, *args, **kwargs): - """ - Convenient shortcut to get. - """ - return self.get(*args, **kwargs)
Extract the basic API to a base class
henriquebastos_django-decouple
train
5701582fb6f02daa571edaf45de2ff22eccd1011
diff --git a/Bundle/InstallableBundle.php b/Bundle/InstallableBundle.php index <HASH>..<HASH> 100644 --- a/Bundle/InstallableBundle.php +++ b/Bundle/InstallableBundle.php @@ -75,6 +75,14 @@ abstract class InstallableBundle extends Bundle implements InstallableInterface return null; } + public function getLicense() + { + $data = $this->getComposer(); + if (property_exists($data, 'license')) return $data->license; + + return array(); + } + public function getComposer() { $ds = DIRECTORY_SEPARATOR; diff --git a/Manager/InstallationManager.php b/Manager/InstallationManager.php index <HASH>..<HASH> 100644 --- a/Manager/InstallationManager.php +++ b/Manager/InstallationManager.php @@ -165,6 +165,7 @@ class InstallationManager $entity->setAuthors($bundle->getAuthors()); $entity->setType($bundle->getType()); $entity->setDescription($bundle->getDescription()); + $entity->setLicense($bundle->getLicense()); $om->persist($entity); $this->log("Updating {$bundle->getName()} info..."); $om->flush();
[InstallationBundle] Bundle tracking.
claroline_Distribution
train
c7cbbc9da45537a0dc77466f16c9478e88b5d934
diff --git a/bin/determine-basal.js b/bin/determine-basal.js index <HASH>..<HASH> 100644 --- a/bin/determine-basal.js +++ b/bin/determine-basal.js @@ -175,6 +175,7 @@ if (!module.parent) { var insulinReq = Math.min(0, (snoozeBG - target_bg) / profile_data.sens); // rate required to deliver insulinReq less insulin over 30m: var rate = profile_data.current_basal + (2 * insulinReq); + rate = Math.round( rate * 1000 ) / 1000; // if required temp < existing temp basal if (typeof temps_data.rate !== 'undefined' && (temps_data.duration > 0 && rate > temps_data.rate - 0.1)) { reason = temps_data.rate + "<~" + rate; @@ -202,6 +203,7 @@ if (!module.parent) { // rate required to deliver insulinReq more insulin over 30m: var rate = profile_data.current_basal + (2 * insulinReq); + rate = Math.round( rate * 1000 ) / 1000; maxSafeBasal = Math.min(profile_data.max_basal, 3 * profile_data.max_daily_basal, 4 * profile_data.current_basal); if (rate > maxSafeBasal) { rate = maxSafeBasal;
round off the rate to 3 digits
openaps_oref0
train
043df6d65ada6ad1096882a1ad0bbae6ce55485c
diff --git a/src/collectors/libvirtkvm/libvirtkvm.py b/src/collectors/libvirtkvm/libvirtkvm.py index <HASH>..<HASH> 100644 --- a/src/collectors/libvirtkvm/libvirtkvm.py +++ b/src/collectors/libvirtkvm/libvirtkvm.py @@ -49,6 +49,9 @@ class LibvirtKVMCollector(diamond.collector.Collector): 'uri': """The libvirt connection URI. By default it's 'qemu:///system'. One decent option is 'qemu+unix:///system?socket=/var/run/libvirt/libvit-sock-ro'.""", + 'sort_by_uuid': """Use the <uuid> of the instance instead of the + default <name>, useful in Openstack deploments where <name> is only +specific to the compute node""", 'cpu_absolute': """CPU stats reported as percentage by default, or as cummulative nanoseconds since VM creation if this is True.""" }) @@ -61,6 +64,7 @@ as cummulative nanoseconds since VM creation if this is True.""" config = super(LibvirtKVMCollector, self).get_default_config() config.update({ 'path': 'libvirt-kvm', + 'sort_by_uuid': True, 'uri': 'qemu:///system', 'cpu_absolute': False }) @@ -103,7 +107,10 @@ as cummulative nanoseconds since VM creation if this is True.""" conn = libvirt.openReadOnly(self.config['uri']) for dom in [conn.lookupByID(n) for n in conn.listDomainsID()]: - name = dom.name() + if self.config['sort_by_uuid']: + name = dom.UUIDString() + else: + name = dom.name() # CPU stats vcpus = dom.getCPUStats(True, 0)
Add option to sort instances by UUID rather than name, useful for OpenStack deployments where the name in not guaranteed to be unique but UUID is
python-diamond_Diamond
train
843948dfb3366a5ea9bf052e1b8e9183cbb442e9
diff --git a/cltk/tag/pos.py b/cltk/tag/pos.py index <HASH>..<HASH> 100644 --- a/cltk/tag/pos.py +++ b/cltk/tag/pos.py @@ -1,4 +1,4 @@ -"""Tags part of speech (POS).""" +"""Tag part of speech (POS) using CLTK taggers.""" __author__ = 'Kyle P. Johnson <kyle@kyle-p-johnson.com>' __license__ = 'MIT License. See LICENSE.' @@ -53,7 +53,7 @@ class POSTag(object): return tagger_paths def tag_unigram(self, untagged_string: str): - """Loads unigram tagger pickle file and tags an untagged string. + """Tag POS with unigram tagger. :type untagged_string: str :param : An untagged, untokenized string of text. :rtype tagged_text: str @@ -65,7 +65,7 @@ class POSTag(object): return tagged_text def tag_bigram(self, untagged_string: str): - """Loads bigram tagger pickle file and tags an untagged string. + """Tag POS with bigram tagger. :type untagged_string: str :param : An untagged, untokenized string of text. :rtype tagged_text: str @@ -77,7 +77,7 @@ class POSTag(object): return tagged_text def tag_trigram(self, untagged_string: str): - """Loads trigram tagger pickle file and tags an untagged string. + """Tag POS with trigram tagger. :type untagged_string: str :param : An untagged, untokenized string of text. :rtype tagged_text: str @@ -89,8 +89,7 @@ class POSTag(object): return tagged_text def tag_ngram_123_backoff(self, untagged_string: str): - """Loads ngram_123_backoff tagger pickle file and tags an untagged - string. + """Tag POS with 1-, 2-, 3-gram tagger. :type untagged_string: str :param : An untagged, untokenized string of text. :rtype tagged_text: str @@ -102,7 +101,7 @@ class POSTag(object): return tagged_text def tag_tnt(self, untagged_string: str): - """Loads tnt tagger pickle file and tags an untagged string. + """Tag POS with TnT tagger. :type untagged_string: str :param : An untagged, untokenized string of text. :rtype tagged_text: str diff --git a/cltk/tokenize/sentence.py b/cltk/tokenize/sentence.py index <HASH>..<HASH> 100644 --- a/cltk/tokenize/sentence.py +++ b/cltk/tokenize/sentence.py @@ -1,4 +1,4 @@ -"""Tokenizes sentences.""" +"""Tokenize sentences.""" __author__ = 'Kyle P. Johnson <kyle@kyle-p-johnson.com>' __license__ = 'MIT License. See LICENSE.'
ch docstrings to imperative mood
cltk_cltk
train
232277c2aff1d1e60d129bc26a88bc998b237db6
diff --git a/src/main/java/org/zeroturnaround/zip/ZipUtil.java b/src/main/java/org/zeroturnaround/zip/ZipUtil.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/zeroturnaround/zip/ZipUtil.java +++ b/src/main/java/org/zeroturnaround/zip/ZipUtil.java @@ -2297,6 +2297,32 @@ public final class ZipUtil { IOUtils.closeQuietly(out); } } + + /** + * Copies an existing ZIP file and removes entries with given paths. + * + * @param zip + * an existing ZIP file (only read) + * @param paths + * paths of the entries to remove + * @param destOut + * new ZIP destination output stream + * @since 1.14 + */ + public static void removeEntries(File zip, String[] paths, OutputStream destOut) { + if (log.isDebugEnabled()) { + log.debug("Copying '" + zip + "' to an output stream and removing paths " + Arrays.asList(paths) + "."); + } + + ZipOutputStream out = null; + try { + out = new ZipOutputStream(destOut); + copyEntries(zip, out, new HashSet<String>(Arrays.asList(paths))); + } + finally { + IOUtils.closeQuietly(out); + } + } /** * Changes an existing ZIP file: removes entries with given paths. diff --git a/src/test/java/org/zeroturnaround/zip/ZipUtilTest.java b/src/test/java/org/zeroturnaround/zip/ZipUtilTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/zeroturnaround/zip/ZipUtilTest.java +++ b/src/test/java/org/zeroturnaround/zip/ZipUtilTest.java @@ -549,6 +549,28 @@ public class ZipUtilTest extends TestCase { FileUtils.deleteQuietly(dest); } } + + public void testRemoveDirsOutputStream() throws IOException { + File src = file("demo-dirs.zip"); + + File dest = File.createTempFile("temp", null); + FileOutputStream out = null; + try { + out = new FileOutputStream(dest); + ZipUtil.removeEntries(src, new String[] { "bar.txt", "a/b" }, out); + + assertFalse("Result zip still contains 'bar.txt'", ZipUtil.containsEntry(dest, "bar.txt")); + assertFalse("Result zip still contains dir 'a/b'", ZipUtil.containsEntry(dest, "a/b")); + assertTrue("Result doesn't contain 'attic'", ZipUtil.containsEntry(dest, "attic/treasure.txt")); + assertTrue("Entry whose prefix is dir name is removed too: 'b.txt'", ZipUtil.containsEntry(dest, "a/b.txt")); + assertFalse("Entry in a removed dir is still there: 'a/b/c.txt'", ZipUtil.containsEntry(dest, "a/b/c.txt")); + + } + finally { + IOUtils.closeQuietly(out); + FileUtils.deleteQuietly(dest); + } + } public void testHandle() { File src = file("demo.zip");
#<I> Add removeEntries variant that copies to an OutputStream
zeroturnaround_zt-zip
train
75ce334c6af0d699cb698453d3603bc279788704
diff --git a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosClientException.java b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosClientException.java index <HASH>..<HASH> 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosClientException.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/CosmosClientException.java @@ -3,6 +3,7 @@ package com.azure.cosmos; +import com.azure.core.exception.AzureException; import com.azure.cosmos.implementation.Constants; import com.azure.cosmos.implementation.HttpConstants; import com.azure.cosmos.implementation.RequestTimeline; @@ -31,7 +32,7 @@ import java.util.Map; * When a transport level error happens that request is not able to reach the * service, an IllegalStateException is thrown instead of CosmosClientException. */ -public class CosmosClientException extends RuntimeException { +public class CosmosClientException extends AzureException { private static final long serialVersionUID = 1L; private final int statusCode; diff --git a/sdk/cosmos/azure-cosmos/src/main/java/module-info.java b/sdk/cosmos/azure-cosmos/src/main/java/module-info.java index <HASH>..<HASH> 100644 --- a/sdk/cosmos/azure-cosmos/src/main/java/module-info.java +++ b/sdk/cosmos/azure-cosmos/src/main/java/module-info.java @@ -17,12 +17,12 @@ module com.azure.cosmos { requires io.netty.transport.epoll; requires io.netty.handler.proxy; requires reactor.netty; - requires org.slf4j; requires com.codahale.metrics; requires com.fasterxml.jackson.module.afterburner; requires java.management; requires jdk.management; requires micrometer.core; + // This is only required by guava shaded libraries requires java.logging; // public API surface area
Extended AzureException by CosmosClientException, updated module-info (#<I>)
Azure_azure-sdk-for-java
train
1d499076d0cfc3d4d8c755c380c475d9b4f10b9f
diff --git a/site/index.js b/site/index.js index <HASH>..<HASH> 100644 --- a/site/index.js +++ b/site/index.js @@ -10,7 +10,6 @@ import "./style.css"; import { NotFound } from "./error"; - const app = document.getElementById("app"); @@ -30,7 +29,7 @@ class Site extends ShallowComponent { <Navbar inverse> <a href="https://github.com/robeio/robe-react-ui"> <img - style={{ position: "absolute", top: "0px", right: "0px", border: "0px" }} + style={{ position: "absolute", top: "0px", right: "0px", border: "0px", zIndex: 1 }} alt="Fork me on GitHub" src="./forkme_right_orange_ff7600.png" />
"Fork me on GitHub" image z-index added.
robeio_robe-react-ui
train
5b494bed944ca58b2392d2f10a69db101a5c3f62
diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/MySQLKeywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/MySQLKeywords.php index <HASH>..<HASH> 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/MySQLKeywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/MySQLKeywords.php @@ -190,6 +190,7 @@ class MySQLKeywords extends KeywordList 'PROCEDURE', 'PURGE', 'RAID0', + 'RANGE', 'READ', 'READS', 'REAL', diff --git a/lib/Doctrine/DBAL/Platforms/Keywords/OracleKeywords.php b/lib/Doctrine/DBAL/Platforms/Keywords/OracleKeywords.php index <HASH>..<HASH> 100644 --- a/lib/Doctrine/DBAL/Platforms/Keywords/OracleKeywords.php +++ b/lib/Doctrine/DBAL/Platforms/Keywords/OracleKeywords.php @@ -151,6 +151,7 @@ class OracleKeywords extends KeywordList 'MODE', 'ROWS', 'WITH', + 'RANGE', ); } }
[DBAL-<I>] Add RANGE keyword to MySQL and Oracle reserved keywords lists.
doctrine_dbal
train
d5e4ac38a1a9f61cc3b3ca95d1f6a0791f9628b4
diff --git a/opentracing-kafka-spring/src/main/java/io/opentracing/contrib/kafka/spring/TracingProducerFactory.java b/opentracing-kafka-spring/src/main/java/io/opentracing/contrib/kafka/spring/TracingProducerFactory.java index <HASH>..<HASH> 100644 --- a/opentracing-kafka-spring/src/main/java/io/opentracing/contrib/kafka/spring/TracingProducerFactory.java +++ b/opentracing-kafka-spring/src/main/java/io/opentracing/contrib/kafka/spring/TracingProducerFactory.java @@ -16,13 +16,13 @@ package io.opentracing.contrib.kafka.spring; import io.opentracing.Tracer; import io.opentracing.contrib.kafka.ClientSpanNameProvider; import io.opentracing.contrib.kafka.TracingKafkaProducer; +import java.util.function.BiFunction; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; +import org.springframework.beans.factory.DisposableBean; import org.springframework.kafka.core.ProducerFactory; -import java.util.function.BiFunction; - -public class TracingProducerFactory<K, V> implements ProducerFactory<K, V> { +public class TracingProducerFactory<K, V> implements ProducerFactory<K, V>, DisposableBean { private final ProducerFactory<K, V> producerFactory; private final Tracer tracer; @@ -35,21 +35,29 @@ public class TracingProducerFactory<K, V> implements ProducerFactory<K, V> { } public TracingProducerFactory(ProducerFactory<K, V> producerFactory, Tracer tracer, - BiFunction<String, ProducerRecord, String> producerSpanNameProvider) { + BiFunction<String, ProducerRecord, String> producerSpanNameProvider) { this.producerFactory = producerFactory; this.tracer = tracer; this.producerSpanNameProvider = (producerSpanNameProvider == null) - ? ClientSpanNameProvider.PRODUCER_OPERATION_NAME - : producerSpanNameProvider; + ? ClientSpanNameProvider.PRODUCER_OPERATION_NAME + : producerSpanNameProvider; } @Override public Producer<K, V> createProducer() { - return new TracingKafkaProducer<>(producerFactory.createProducer(), tracer, producerSpanNameProvider); + return new TracingKafkaProducer<>(producerFactory.createProducer(), tracer, + producerSpanNameProvider); } @Override public boolean transactionCapable() { return producerFactory.transactionCapable(); } + + @Override + public void destroy() throws Exception { + if (producerFactory instanceof DisposableBean) { + ((DisposableBean) producerFactory).destroy(); + } + } }
#<I> destroy underlying ProducerFactory
opentracing-contrib_java-kafka-client
train
e6747d5cf1f25702df959e1e60e2516fb1efb83e
diff --git a/graphql_jwt/exceptions.py b/graphql_jwt/exceptions.py index <HASH>..<HASH> 100644 --- a/graphql_jwt/exceptions.py +++ b/graphql_jwt/exceptions.py @@ -1,3 +1,15 @@ +from django.utils.translation import ugettext_lazy as _ + class GraphQLJWTError(Exception): - """Raise GraphQL JWT exception""" + default_message = None + + def __init__(self, message=None): + if message is None: + message = self.default_message + + super(GraphQLJWTError, self).__init__(message) + + +class PermissionDenied(GraphQLJWTError): + default_message = _('You do not have permission to perform this action')
Added PermissionDenied exception
flavors_django-graphql-jwt
train
a80117a4eea4f468433f4e0c5e5a46475570db41
diff --git a/lib/Doctrine/ORM/Tools/Pagination/Paginator.php b/lib/Doctrine/ORM/Tools/Pagination/Paginator.php index <HASH>..<HASH> 100755 --- a/lib/Doctrine/ORM/Tools/Pagination/Paginator.php +++ b/lib/Doctrine/ORM/Tools/Pagination/Paginator.php @@ -118,12 +118,8 @@ class Paginator implements \Countable, \IteratorAggregate public function count() { if ($this->count === null) { - $countQuery = $this->getCountQuery(); - try { - $data = $countQuery->getScalarResult(); - $data = array_map('current', $data); - $this->count = array_sum($data); + $this->count = array_sum(array_map('current', $this->getCountQuery()->getScalarResult())); } catch(NoResultException $e) { $this->count = 0; }
#<I> - removing unused variable assignments
doctrine_orm
train
01fdbbc17ebf927f09b186b4cb5e231cdcc2f8d0
diff --git a/webpack/webpack.config.lib.js b/webpack/webpack.config.lib.js index <HASH>..<HASH> 100644 --- a/webpack/webpack.config.lib.js +++ b/webpack/webpack.config.lib.js @@ -13,7 +13,7 @@ module.exports = webpackUtils.merge(base.defaults, { ] }, output: { - path: path.join(__dirname, './lib'), + path: path.join(__dirname, './../lib'), filename: 'index.js', library: 'rosemary-ui', libraryTarget: 'umd'
Update webpack.config.lib.js
ctco_rosemary-ui
train
5305aea90d10ba8c89422ccae0d75a8b22baa806
diff --git a/src/lib/run.js b/src/lib/run.js index <HASH>..<HASH> 100644 --- a/src/lib/run.js +++ b/src/lib/run.js @@ -11,7 +11,9 @@ exports.module = function runModule(modulePath) { require('register-module')({ name: packageJson.name, path: path.resolve('src'), - main: packageJson.main || 'index.js' + main: packageJson.main ? + packageJson.main.replace('src/', '') : + 'index.js' }); require('babel-register')(babelOptions); require(modulePath);
Remove src/ from package.json in development
vinsonchuong_dist-es6
train
a28be7c3c0a4565207373afaacb9534653814f90
diff --git a/bench/throughput.js b/bench/throughput.js index <HASH>..<HASH> 100644 --- a/bench/throughput.js +++ b/bench/throughput.js @@ -33,10 +33,10 @@ function makeSuite(warmer, name, template, handlebarsOnly) { ecoOut, mustacheOut; - var handlebar = Handlebars.compile(template.handlebars), + var handlebar = Handlebars.compile(template.handlebars, {data: false}), options = {helpers: template.helpers}; _.each(template.partials && template.partials.handlebars, function(partial, name) { - Handlebars.registerPartial(name, partial); + Handlebars.registerPartial(name, Handlebars.compile(partial, {data: false})); }); handlebarsOut = handlebar(context, options);
Default data to off for performance tests
wycats_handlebars.js
train
0a3e538bdafc36a2771f3bde51231dbd97396a60
diff --git a/neuropythy/__init__.py b/neuropythy/__init__.py index <HASH>..<HASH> 100644 --- a/neuropythy/__init__.py +++ b/neuropythy/__init__.py @@ -95,7 +95,7 @@ try: except Exception: pass # Version information... -__version__ = '0.10.6' +__version__ = '0.10.7' diff --git a/neuropythy/geometry/__init__.py b/neuropythy/geometry/__init__.py index <HASH>..<HASH> 100644 --- a/neuropythy/geometry/__init__.py +++ b/neuropythy/geometry/__init__.py @@ -48,7 +48,7 @@ from .mesh import (VertexSet, Tesselation, Mesh, Topology, MapProjection, Path, map_projection, is_map_projection, load_map_projection, load_projections_from_path, projections_path, map_projections, - path_trace, is_path_trace, close_path_traces, + path_trace, is_path_trace, close_path_traces, paths_to_labels, to_tess, to_mesh, to_property, to_mask, isolines, smooth_lines, to_map_projection, to_flatmap)
upped micro-version number and fixed up the imports for paths_to_labels
noahbenson_neuropythy
train
08fb31fbc318551749d5f294417fa83dd792ef3b
diff --git a/satpy/readers/nc_nwcsaf_msg.py b/satpy/readers/nc_nwcsaf_msg.py index <HASH>..<HASH> 100644 --- a/satpy/readers/nc_nwcsaf_msg.py +++ b/satpy/readers/nc_nwcsaf_msg.py @@ -51,7 +51,10 @@ class NcNWCSAFMSG(BaseFileHandler): self.nc = h5netcdf.File(filename, 'r') self.sensor = 'seviri' sat_id = self.nc.attrs['satellite_identifier'] - self.platform_name = PLATFORM_NAMES[sat_id] + try: + self.platform_name = PLATFORM_NAMES[sat_id] + except KeyError: + self.platform_name = PLATFORM_NAMES[sat_id.astype(str)] def get_dataset(self, key, info): """Load a dataset.""" @@ -90,8 +93,10 @@ class NcNWCSAFMSG(BaseFileHandler): """Get the area definition of the datasets in the file.""" if dsid.name.endswith('_pal'): raise NotImplementedError - - proj_str = self.nc.attrs['gdal_projection'] + ' +units=km' + try: + proj_str = self.nc.attrs['gdal_projection'] + ' +units=km' + except TypeError: + proj_str = self.nc.attrs['gdal_projection'].decode() + ' +units=km' nlines, ncols = self.nc[dsid.name].shape @@ -112,8 +117,18 @@ class NcNWCSAFMSG(BaseFileHandler): @property def start_time(self): - return datetime.strptime(self.nc.attrs['time_coverage_start'], '%Y-%m-%dT%H:%M:%SZ') + try: + return datetime.strptime(self.nc.attrs['time_coverage_start'], + '%Y-%m-%dT%H:%M:%SZ') + except TypeError: + return datetime.strptime(self.nc.attrs['time_coverage_start'].astype(str), + '%Y-%m-%dT%H:%M:%SZ') @property def end_time(self): - return datetime.strptime(self.nc.attrs['time_coverage_end'], '%Y-%m-%dT%H:%M:%SZ') + try: + return datetime.strptime(self.nc.attrs['time_coverage_end'], + '%Y-%m-%dT%H:%M:%SZ') + except TypeError: + return datetime.strptime(self.nc.attrs['time_coverage_end'].astype(str), + '%Y-%m-%dT%H:%M:%SZ')
Fix h5py py3 issues with byte arrays as strings
pytroll_satpy
train
c2381236b1fe89a983ce0eb2633c8072711834c9
diff --git a/lib/resources/events.js b/lib/resources/events.js index <HASH>..<HASH> 100644 --- a/lib/resources/events.js +++ b/lib/resources/events.js @@ -6,19 +6,19 @@ var Events = require('./gen/events'); * changes to a resource. * @param {Number} resourceId The id of the resource to get events for * @param {String} [syncToken] Token from a previous sync, if any + * @param {Object} [params] Parameters for the request * @return {Promise} The result of the API call: * {String} sync The new sync token to use for the next request * {Object[]} [data] The changes on the resource since the last sync, * may not exist if sync token is new. */ -Events.prototype.get = function(resourceId, syncToken) { - var params = { - resource: resourceId - }; +Events.prototype.get = function(resourceId, syncToken, params) { + var requestParams = params || {}; + requestParams.resource = resourceId; if (syncToken) { - params.sync = syncToken; + requestParams.sync = syncToken; } - return this.dispatcher.get('/events', params); + return this.dispatcher.get('/events', requestParams); }; /**
feat: params to the events.get
Asana_node-asana
train
7e49714c3dc9723e0cc18544b9c3c104467a09ff
diff --git a/builtin/providers/cloudstack/resource_cloudstack_instance.go b/builtin/providers/cloudstack/resource_cloudstack_instance.go index <HASH>..<HASH> 100644 --- a/builtin/providers/cloudstack/resource_cloudstack_instance.go +++ b/builtin/providers/cloudstack/resource_cloudstack_instance.go @@ -82,11 +82,13 @@ func resourceCloudStackInstance() *schema.Resource { Optional: true, Default: false, }, - "project_name": &schema.Schema{ + + "project": &schema.Schema{ Type: schema.TypeString, Optional: true, - Default: nil, + ForceNew: true, }, + }, } } @@ -153,15 +155,14 @@ func resourceCloudStackInstanceCreate(d *schema.ResourceData, meta interface{}) p.SetUserdata(ud) } - // If the project_name contains any info, we retreive the project_id - if projectName, ok := d.GetOk("project_name"); ok { - project, _, err := cs.Project.GetProjectByName(projectName.(string)) - if err != nil { - return err + // If project contains any info, we retreive the project id + if project, ok := d.GetOk("project"); ok { + projectid, e := retrieveUUID(cs, "project", project.(string)) + if e != nil { + return e.Error() } - log.Printf("[DEBUG] project id %s", project.Id) - p.SetProjectid(project.Id) - d.Set("project_id", project.Id) + log.Printf("[DEBUG] project id %s", projectid) + p.SetProjectid(projectid) } // Create the new instance @@ -206,7 +207,8 @@ func resourceCloudStackInstanceRead(d *schema.ResourceData, meta interface{}) er setValueOrUUID(d, "network", vm.Nic[0].Networkname, vm.Nic[0].Networkid) setValueOrUUID(d, "service_offering", vm.Serviceofferingname, vm.Serviceofferingid) setValueOrUUID(d, "template", vm.Templatename, vm.Templateid) - + setValueOrUUID(d, "project", vm.Project, vm.Projectid) + return nil } diff --git a/builtin/providers/cloudstack/resources.go b/builtin/providers/cloudstack/resources.go index <HASH>..<HASH> 100644 --- a/builtin/providers/cloudstack/resources.go +++ b/builtin/providers/cloudstack/resources.go @@ -79,6 +79,8 @@ func retrieveUUID(cs *cloudstack.CloudStackClient, name, value string) (uuid str break } err = fmt.Errorf("Could not find UUID of OS Type: %s", value) + case "project": + uuid, err = cs.Project.GetProjectID(value) default: return uuid, &retrieveError{name: name, value: value, err: fmt.Errorf("Unknown request: %s", name)}
fixed project schema, added project support to retrieveUUID
hashicorp_terraform
train
bea94699e8d47074a40486a10e5b949875c3b030
diff --git a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/scoping/impl/ImportNormalizer.java b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/scoping/impl/ImportNormalizer.java index <HASH>..<HASH> 100644 --- a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/scoping/impl/ImportNormalizer.java +++ b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/scoping/impl/ImportNormalizer.java @@ -56,6 +56,8 @@ public class ImportNormalizer { } public QualifiedName resolve(QualifiedName relativeName) { + if (relativeName.isEmpty()) + return null; if (hasWildCard) { return importedNamespacePrefix.append(relativeName); } else { diff --git a/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/naming/QualifiedNameTest.java b/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/naming/QualifiedNameTest.java index <HASH>..<HASH> 100644 --- a/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/naming/QualifiedNameTest.java +++ b/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/naming/QualifiedNameTest.java @@ -7,6 +7,8 @@ *******************************************************************************/ package org.eclipse.xtext.naming; +import org.eclipse.xtext.naming.IQualifiedNameConverter.DefaultImpl; +import org.eclipse.xtext.scoping.impl.ImportNormalizer; import org.junit.Assert; import org.junit.Test; @@ -16,6 +18,13 @@ import com.google.common.base.Function; * @author Jan Koehnlein - Initial contribution and API */ public class QualifiedNameTest extends Assert { + + @Test public void testBug354473() { + DefaultImpl impl = new IQualifiedNameConverter.DefaultImpl(); + QualifiedName name = impl.toQualifiedName("."); + ImportNormalizer normalizer = new ImportNormalizer(QualifiedName.create("Test"), true, false); + assertNull(normalizer.resolve(name)); + } @Test public void testCreateNull() { assertEquals(QualifiedName.EMPTY, QualifiedName.create());
ImportNormalizer now returns null when 'resolve' is invoked with an empty string. (see #<I>)
eclipse_xtext-core
train
989f63b8f3f9e4271bf5e7e01cbb6d3b5e529625
diff --git a/examples/show_hids.py b/examples/show_hids.py index <HASH>..<HASH> 100644 --- a/examples/show_hids.py +++ b/examples/show_hids.py @@ -5,26 +5,18 @@ """ Show all HID devices information """ +import sys import pywinusb.hid as hid -def encoding_hack(): - "Setup display rough unicode decoder" - # first be kind with local encodings - import sys - if sys.version_info >= (3,): - # as is, don't handle unicodes - unicode = str - raw_input = input - else: - # allow to show encoded strings - import codecs - sys.stdout = codecs.getwriter('mbcs')(sys.stdout) - print_all() - -def print_all(): - hid.core.show_hids() - if __name__ == '__main__': - encoding_hack() - print_all() + if sys.version_info < (3,): + import codecs + output = codecs.getwriter('mbcs')(sys.stdout) + else: + # python3, you have to deal with encodings, try redirecting to any file + output = sys.stdout + try: + hid.core.show_hids(output = output) + except UnicodeEncodeError: + print("\nError: Can't manage encodings on terminal, try to run the script on PyScripter or IDLE") diff --git a/pywinusb/hid/core.py b/pywinusb/hid/core.py index <HASH>..<HASH> 100644 --- a/pywinusb/hid/core.py +++ b/pywinusb/hid/core.py @@ -1536,10 +1536,9 @@ class HidPUsageCaps(object): def show_hids(target_vid = 0, target_pid = 0, output = None): """Check all HID devices conected to PC hosts.""" # first be kind with local encodings - import codecs if not output: + # beware your script should manage encodings output = sys.stdout - output = codecs.getwriter('mbcs')(output) # then the big cheese... from . import tools all_hids = None diff --git a/pywinusb/hid/tools.py b/pywinusb/hid/tools.py index <HASH>..<HASH> 100644 --- a/pywinusb/hid/tools.py +++ b/pywinusb/hid/tools.py @@ -31,7 +31,7 @@ def write_documentation(self, output_file): return new_var dev_vars = vars(self) dev_vars['main_usage_str'] = repr( - usage_pages.HidUsage(self.hid_caps.usage_page, + usage_pages.HidUsage(self.hid_caps.usage_page, self.hid_caps.usage) ) output_file.write( """\n\ HID device documentation report @@ -80,7 +80,7 @@ Values: %(hid_caps.number_feature_value_caps)d value(s) """ % CompundVarDict(dev_vars)) #better than vars()! #return # inspect caps - for report_kind in [winapi.HidP_Input, + for report_kind in [winapi.HidP_Input, winapi.HidP_Output, winapi.HidP_Feature]: all_usages = self.usages_storage.get(report_kind, []) if all_usages: @@ -117,20 +117,20 @@ Values: %(hid_caps.number_feature_value_caps)d value(s) usage = (all_items["usage_min"], all_items["usage_max"]) output_file.write(" Usage Range {0}~{1} ({0:#x}~{1:#x})," " Page {2:#x} ({3})\n".format( - usage[0], usage[1], usage_page, + usage[0], usage[1], usage_page, str(usage_pages.UsagePage(usage_page))) ) del all_items["usage_min"] del all_items["usage_max"] else: raise AttributeError("Expecting any usage id") - attribs = all_items.keys() + attribs = list( all_items.keys() ) attribs.sort() for key in attribs: if 'usage' in key: - output_file.write("{0}{1}: {2} ({2:#x})\n".format(' '*8, + output_file.write("{0}{1}: {2} ({2:#x})\n".format(' '*8, key, all_items[key])) else: - output_file.write("{0}{1}: {2}\n".format(' '*8, + output_file.write("{0}{1}: {2}\n".format(' '*8, key, all_items[key])) output_file.write('\n')
Leaving stdout encodings management out of library
rene-aguirre_pywinusb
train
4c0bff4de3986ebe9553eb89097417ede7aef220
diff --git a/Build/Gruntfile.js b/Build/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Build/Gruntfile.js +++ b/Build/Gruntfile.js @@ -137,6 +137,10 @@ module.exports = function(grunt) { src: '<%= paths.contrib %>modernizr/modernizr.min.js', dest: '<%= paths.contrib %>modernizr/modernizr.min.js' }, + bootstrapAccordion: { + src: '<%= paths.js %>Src/bootstrap.accordion.js', + dest: '<%= paths.js %>Dist/bootstrap.accordion.min.js' + }, bootstrapForm: { src: '<%= paths.js %>Src/bootstrap.form.js', dest: '<%= paths.js %>Dist/bootstrap.form.min.js' diff --git a/Resources/Public/JavaScript/Dist/bootstrap.accordion.min.js b/Resources/Public/JavaScript/Dist/bootstrap.accordion.min.js index <HASH>..<HASH> 100644 --- a/Resources/Public/JavaScript/Dist/bootstrap.accordion.min.js +++ b/Resources/Public/JavaScript/Dist/bootstrap.accordion.min.js @@ -1 +1 @@ -$(".accordion").on("hide.bs.collapse",function(o){var a=$(o.target).prev(".accordion-header").offset().top-5;a<$(window).scrollTop()&&$("html,body").animate({scrollTop:a},500)}); \ No newline at end of file +$(".accordion").on("hide.bs.collapse",function(o){var a=$(o.target).prev(".accordion-header");if(0<a.length){var e=a.offset().top-5;e<$(window).scrollTop()&&$("html,body").animate({scrollTop:e},500)}}); \ No newline at end of file diff --git a/Resources/Public/JavaScript/Src/bootstrap.accordion.js b/Resources/Public/JavaScript/Src/bootstrap.accordion.js index <HASH>..<HASH> 100644 --- a/Resources/Public/JavaScript/Src/bootstrap.accordion.js +++ b/Resources/Public/JavaScript/Src/bootstrap.accordion.js @@ -2,11 +2,15 @@ * Scroll to top of collapsed/expanded accordion item */ $('.accordion').on('hide.bs.collapse', function (e) { - var headingTop = $(e.target).prev('.accordion-header').offset().top - 5; - var visibleTop = $(window).scrollTop(); - if (headingTop < visibleTop) { - $('html,body').animate({ - scrollTop: headingTop - }, 500); + var $accordionHeader = $(e.target).prev('.accordion-header') + if ($accordionHeader.length > 0) { + var headingTop = $accordionHeader.offset().top - 5; + var visibleTop = $(window).scrollTop(); + if (headingTop < visibleTop) { + $('html,body').animate({ + scrollTop: headingTop + }, 500); + } } }); +
[BUGFIX] Resolve plain bootstrap 4 accordion conflicts (#<I>)
benjaminkott_bootstrap_package
train
653d12961f05c3f4e933c27cb529170d76b0f8fc
diff --git a/httpserver/httpserver.py b/httpserver/httpserver.py index <HASH>..<HASH> 100644 --- a/httpserver/httpserver.py +++ b/httpserver/httpserver.py @@ -10,6 +10,7 @@ import mimetypes import asyncio import logging import socket +import hashlib logger = logging.getLogger(__name__) @@ -178,8 +179,13 @@ class HttpProtocol(asyncio.Protocol): response['headers']['Content-Type'] = mimetypes.guess_type( filename)[0] or 'text/plain' + sha1 = hashlib.sha1() + with open(filename, 'rb') as fp: response['body'] = fp.read() + sha1.update(response['body']) + + response['headers']['Etag'] = '"{}"'.format(sha1.hexdigest()) self._write_response(response)
Add Etag to headers when file exists
thomwiggers_httpserver
train
36437bfb0f05f21ac3c901c494b9c0e39c8dcdf6
diff --git a/pycine/cli/pfs_raw.py b/pycine/cli/pfs_raw.py index <HASH>..<HASH> 100755 --- a/pycine/cli/pfs_raw.py +++ b/pycine/cli/pfs_raw.py @@ -3,6 +3,7 @@ import os import click import cv2 +import numpy as np from pycine.color import color_pipeline, resize from pycine.raw import read_frames @@ -14,23 +15,34 @@ def display(image_8bit): cv2.destroyAllWindows() -def save(rgb_image, outfile): - cv2.imwrite(outfile, rgb_image * 255) - - @click.command() @click.option("--file-format", default=".png", type=click.Choice([".png", ".jpg", ".tif"])) @click.option("--start-frame", default=1, type=click.INT) -@click.option("--count", default=1, type=click.INT) +@click.option("--count", default=None, type=click.INT) @click.argument("cine_file", type=click.Path(exists=True, readable=True, dir_okay=False, file_okay=True)) @click.argument("out_path", required=False, type=click.Path(exists=True, dir_okay=True, file_okay=False)) @click.version_option() -def cli(file_format, start_frame, count, out_path, cine_file): +def cli( + file_format: str, + start_frame: int, + count: int, + out_path: str, + cine_file: str, +): raw_images, setup, bpp = read_frames(cine_file, start_frame=start_frame, count=count) - rgb_images = (color_pipeline(raw_image, setup=setup, bpp=bpp) for raw_image in raw_images) - for i, rgb_image in enumerate(rgb_images): - frame = start_frame + i + if setup.CFA in [3, 4]: + # FIXME: the color pipeline is not at all ready for production! + images = (color_pipeline(raw_image, setup=setup, bpp=bpp) for raw_image in raw_images) + + elif setup.CFA == 0: + images = raw_images + + else: + raise ValueError("Sensor not supported") + + for i, rgb_image in enumerate(images): + frame_number = start_frame + i if setup.EnableCrop: rgb_image = rgb_image[ @@ -43,14 +55,14 @@ def cli(file_format, start_frame, count, out_path, cine_file): if out_path: ending = file_format.strip(".") name = os.path.splitext(os.path.basename(cine_file))[0] - out_name = "{}-{:06d}.{}".format(name, frame, ending) + out_name = f"{name}-{frame_number:06d}.{ending}" out_file = os.path.join(out_path, out_name) - print("Writing File {}".format(out_file)) - save(rgb_image, out_file) + print(f"Writing File {out_file}") + interpolated = np.interp(rgb_image, [0, 2 ** bpp - 1], [0, 2 ** 16 - 1]).astype(np.uint16) + cv2.imwrite(out_file, interpolated) else: display(resize(rgb_image, 720)) - break if __name__ == "__main__":
pfs_raw: support monochrome sensors
OTTOMATIC-IO_pycine
train
6ea896f004f26fe34b70fc51e0014f77a7ed5594
diff --git a/lib/Webpcss.js b/lib/Webpcss.js index <HASH>..<HASH> 100644 --- a/lib/Webpcss.js +++ b/lib/Webpcss.js @@ -8,8 +8,14 @@ */ import WebpBase64 from "./WebpBase64"; import libpath from "path"; -import PromiseA from "bluebird"; -const fs = PromiseA.promisifyAll(require("fs")); +import {Promise as PromiseA} from "es6-promise"; +import {readFile} from "fs"; + +function readFileAsync(path) { + return new PromiseA((resolve, reject)=> { + readFile(path, (err, data)=> err ? reject(err) : resolve(data)); + }); +} const rxHtml = /^html[_\.#\[]{1}/; const DEFAULTS = { @@ -77,7 +83,7 @@ class Webpcss { libpath.resolve(libpath.join(options.image_root, url)) : /* url(../images.png) or url(image.png) - relative css path */ libpath.resolve(libpath.join(options.css_root, url)); - return fs.readFileAsync(urlPath) + return readFileAsync(urlPath) .then((data)=> { return base64.convert(data, options.cwebp_configurator) .then((buffer)=> { @@ -125,8 +131,9 @@ class Webpcss { nodes .filter((decl)=> decl) .forEach((decl)=> css.append(decl)); + cb(); }) - .finally(()=> cb()); + .catch(()=> cb()); } } diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -9,7 +9,8 @@ import postcss from "postcss"; import Webpcss from "./Webpcss"; -import PromiseA from "bluebird"; +import {Promise as PromiseA, polyfill} from "es6-promise"; +polyfill(); let defaultWebpcss = null; export default Webpcss; diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -28,8 +28,8 @@ }, "license": "MIT", "dependencies": { - "bluebird": "^2.10.0", "cwebp": "^1.0.5", + "es6-promise": "^3.0.2", "postcss": "^5.0.4", "urldata": "0.0.1" },
Fix: node support <I> revert es6-promise
lexich_webpcss
train
7b88767b6e82c0fdb5ca688629f9718eefcd5fd3
diff --git a/api/charmhub/data.go b/api/charmhub/data.go index <HASH>..<HASH> 100644 --- a/api/charmhub/data.go +++ b/api/charmhub/data.go @@ -176,6 +176,6 @@ type Bundle struct { } type BundleCharm struct { - Name string `json:"name"` - Revision int `json:"revision"` + Name string `json:"name"` + PackageID string `json:"package-id"` } diff --git a/apiserver/facades/client/charmhub/convert.go b/apiserver/facades/client/charmhub/convert.go index <HASH>..<HASH> 100644 --- a/apiserver/facades/client/charmhub/convert.go +++ b/apiserver/facades/client/charmhub/convert.go @@ -27,7 +27,7 @@ func convertCharmInfoResult(info transport.InfoResponse) params.InfoResponse { } switch ir.Type { case "bundle": - ir.Bundle = convertBundle() + ir.Bundle = convertBundle(info.Entity.Charms) // TODO (stickupkid): Get the Bundle.Series and set it to the // InfoResponse at a high level. case "charm": @@ -200,8 +200,15 @@ func formatRelationPart(rels map[string]charm.Relation) (map[string]string, bool return relations, true } -func convertBundle() *params.CharmHubBundle { - // TODO (hml) 2020-07-06 - // Implemented once how to get charms in a bundle is defined by the api. - return nil +func convertBundle(charms []transport.Charm) *params.CharmHubBundle { + bundle := &params.CharmHubBundle{ + Charms: make([]params.BundleCharm, len(charms)), + } + for i, v := range charms { + bundle.Charms[i] = params.BundleCharm{ + Name: v.Name, + PackageID: v.PackageID, + } + } + return bundle } diff --git a/apiserver/facades/schema.json b/apiserver/facades/schema.json index <HASH>..<HASH> 100644 --- a/apiserver/facades/schema.json +++ b/apiserver/facades/schema.json @@ -11976,14 +11976,14 @@ "name": { "type": "string" }, - "revision": { - "type": "integer" + "package-id": { + "type": "string" } }, "additionalProperties": false, "required": [ "name", - "revision" + "package-id" ] }, "Channel": { diff --git a/apiserver/params/charmhub.go b/apiserver/params/charmhub.go index <HASH>..<HASH> 100644 --- a/apiserver/params/charmhub.go +++ b/apiserver/params/charmhub.go @@ -74,8 +74,8 @@ type CharmHubBundle struct { } type BundleCharm struct { - Name string `json:"name"` - Revision int `json:"revision"` + Name string `json:"name"` + PackageID string `json:"package-id"` } type ErrorResponse struct { diff --git a/cmd/juju/charmhub/data.go b/cmd/juju/charmhub/data.go index <HASH>..<HASH> 100644 --- a/cmd/juju/charmhub/data.go +++ b/cmd/juju/charmhub/data.go @@ -68,7 +68,7 @@ func convertBundle(in interface{}) (*Bundle, error) { Charms: make([]BundleCharm, len(inB.Charms)), } for i, c := range inB.Charms { - out.Charms[i] = BundleCharm(c) + out.Charms[i] = BundleCharm{Name: c.Name} } return &out, nil } @@ -166,6 +166,5 @@ type Bundle struct { } type BundleCharm struct { - Name string `json:"name" yaml:"name"` - Revision int `json:"revision" yaml:"revision"` + Name string `json:"name" yaml:"name"` }
Update bundle charm info to be name and package-id. Only print the name in the info output. Package-id may be used later to deploy bundles.
juju_juju
train
3e7e38d32305fec8920b85f4f29238c0f7cfcf93
diff --git a/config/config.php b/config/config.php index <HASH>..<HASH> 100644 --- a/config/config.php +++ b/config/config.php @@ -111,7 +111,7 @@ return [ 'views' => 'Resources/views', 'test' => 'Tests', 'jobs' => 'Jobs', - 'mail' => 'Mail', + 'emails' => 'Emails', ], ], /* diff --git a/src/Commands/GenerateMailCommand.php b/src/Commands/GenerateMailCommand.php index <HASH>..<HASH> 100644 --- a/src/Commands/GenerateMailCommand.php +++ b/src/Commands/GenerateMailCommand.php @@ -63,7 +63,7 @@ class GenerateMailCommand extends GeneratorCommand { $path = $this->laravel['modules']->getModulePath($this->getModuleName()); - $mailPath = $this->laravel['modules']->config('paths.generator.mail', 'Mail'); + $mailPath = $this->laravel['modules']->config('paths.generator.emails', 'Emails'); return $path . $mailPath . '/' . $this->getFileName() . '.php'; } @@ -81,6 +81,6 @@ class GenerateMailCommand extends GeneratorCommand */ public function getDefaultNamespace() { - return $this->laravel['modules']->config('paths.generator.mail', 'Mail'); + return $this->laravel['modules']->config('paths.generator.emails', 'Emails'); } } diff --git a/tests/BaseTestCase.php b/tests/BaseTestCase.php index <HASH>..<HASH> 100644 --- a/tests/BaseTestCase.php +++ b/tests/BaseTestCase.php @@ -64,7 +64,7 @@ abstract class BaseTestCase extends OrchestraTestCase 'views' => 'Resources/views', 'test' => 'Tests', 'jobs' => 'Jobs', - 'mail' => 'Mail', + 'emails' => 'Emails', ], ]); } diff --git a/tests/Commands/GenerateMailCommandTest.php b/tests/Commands/GenerateMailCommandTest.php index <HASH>..<HASH> 100644 --- a/tests/Commands/GenerateMailCommandTest.php +++ b/tests/Commands/GenerateMailCommandTest.php @@ -34,7 +34,7 @@ class GenerateMailCommandTest extends BaseTestCase { $this->artisan('module:make-mail', ['name' => 'SomeMail', 'module' => 'Blog']); - $this->assertTrue(is_file($this->modulePath . '/Mail/SomeMail.php')); + $this->assertTrue(is_file($this->modulePath . '/Emails/SomeMail.php')); } /** @test */ @@ -42,7 +42,7 @@ class GenerateMailCommandTest extends BaseTestCase { $this->artisan('module:make-mail', ['name' => 'SomeMail', 'module' => 'Blog']); - $file = $this->finder->get($this->modulePath . '/Mail/SomeMail.php'); + $file = $this->finder->get($this->modulePath . '/Emails/SomeMail.php'); $this->assertEquals($this->expectedContent(), $file); } @@ -52,7 +52,7 @@ class GenerateMailCommandTest extends BaseTestCase return <<<TEXT <?php -namespace Modules\Blog\Mail; +namespace Modules\Blog\Emails; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable;
Using Emails as default folder and namespace for emails
nWidart_laravel-modules
train
3c68b5679f910be5fbd8d738812b16cc75f7e066
diff --git a/lib/UnexpectedError.js b/lib/UnexpectedError.js index <HASH>..<HASH> 100644 --- a/lib/UnexpectedError.js +++ b/lib/UnexpectedError.js @@ -22,7 +22,7 @@ function UnexpectedError(expect, parent) { this.expect = expect; this.parent = parent || null; - this.name = 'UnexpectedError'; + this.name = 'Error'; } UnexpectedError.prototype = Object.create(Error.prototype); @@ -200,6 +200,16 @@ UnexpectedError.prototype.getErrorMessage = function (options) { } }; +function findStackStart(lines) { + for (var i = lines.length - 1; 0 <= i; i -= 1) { + if (lines[i] === '') { + return i + 1; + } + } + + return -1; +} + UnexpectedError.prototype.serializeMessage = function (outputFormat) { if (!this._hasSerializedErrorMessage) { var htmlFormat = outputFormat === 'html'; @@ -211,14 +221,17 @@ UnexpectedError.prototype.serializeMessage = function (outputFormat) { this.message = '\n' + this.getErrorMessage({ format: htmlFormat ? 'text' : outputFormat - }).toString(); + }).toString() + '\n'; if (!this.useFullStackTrace) { var newStack = []; var removedFrames = false; var lines = this.stack.split(/\n/); + + var stackStart = findStackStart(lines); + lines.forEach(function (line, i) { - if (i !== 0 && (/node_modules\/unexpected(?:-[^\/]+)?\//).test(line)) { + if (stackStart <= i && (/node_modules\/unexpected(?:-[^\/]+)?\//).test(line)) { removedFrames = true; } else { newStack.push(line); @@ -233,7 +246,6 @@ UnexpectedError.prototype.serializeMessage = function (outputFormat) { } else { newStack.push(indentation + 'set UNEXPECTED_FULL_TRACE=true to see the full stack trace'); } - } this.stack = newStack.join('\n'); diff --git a/test/api/fail.spec.js b/test/api/fail.spec.js index <HASH>..<HASH> 100644 --- a/test/api/fail.spec.js +++ b/test/api/fail.spec.js @@ -65,7 +65,7 @@ describe('fail assertion', function () { message: 'hey' }); }, 'to throw', { - message: '\nhey' + message: '\nhey\n' }); }); @@ -75,7 +75,7 @@ describe('fail assertion', function () { message: expect.output.clone().text('hey') }); }, 'to throw', { - message: '\nhey' + message: '\nhey\n' }); }); }); diff --git a/test/api/outputFormat.spec.js b/test/api/outputFormat.spec.js index <HASH>..<HASH> 100644 --- a/test/api/outputFormat.spec.js +++ b/test/api/outputFormat.spec.js @@ -16,7 +16,7 @@ describe('outputFormat', function () { var clonedExpect = expect.clone().outputFormat('ansi'); clonedExpect(42, 'to equal', 24); }, 'to throw', { - message: '\n\x1b[31m\x1b[1mexpected\x1b[22m\x1b[39m 42 \x1b[31m\x1b[1mto equal\x1b[22m\x1b[39m 24' + message: '\n\x1b[31m\x1b[1mexpected\x1b[22m\x1b[39m 42 \x1b[31m\x1b[1mto equal\x1b[22m\x1b[39m 24\n' }); }); });
Make unexpected errors more resilient to weird post processing of the stack
unexpectedjs_unexpected
train
c2211596b652d97ecf1fab6c0bed56da5cb940bf
diff --git a/src/com/google/javascript/jscomp/CompilationLevel.java b/src/com/google/javascript/jscomp/CompilationLevel.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/CompilationLevel.java +++ b/src/com/google/javascript/jscomp/CompilationLevel.java @@ -180,7 +180,6 @@ public enum CompilationLevel { options.setWarningLevel(DiagnosticGroups.GLOBAL_THIS, CheckLevel.WARNING); options.setRewriteFunctionExpressions(false); options.setSmartNameRemoval(true); - options.setExtraSmartNameRemoval(true); options.setInlineConstantVars(true); options.setInlineFunctions(Reach.ALL); options.setAssumeClosuresOnlyCaptureReferences(false); diff --git a/src/com/google/javascript/jscomp/DefaultPassConfig.java b/src/com/google/javascript/jscomp/DefaultPassConfig.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/DefaultPassConfig.java +++ b/src/com/google/javascript/jscomp/DefaultPassConfig.java @@ -635,7 +635,7 @@ public final class DefaultPassConfig extends PassConfig { // Running RemoveUnusedCode before disambiguate properties allows disambiguate properties to be // more effective if code that would prevent disambiguation can be removed. // TODO(b/66971163): Rename options since we're not actually using smartNameRemoval here now. - if (options.extraSmartNameRemoval && options.smartNameRemoval) { + if (options.smartNameRemoval) { // These passes remove code that is dead because of define flags. // If the dead code is weakly typed, running these passes before property diff --git a/test/com/google/javascript/jscomp/integration/AdvancedOptimizationsIntegrationTest.java b/test/com/google/javascript/jscomp/integration/AdvancedOptimizationsIntegrationTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/integration/AdvancedOptimizationsIntegrationTest.java +++ b/test/com/google/javascript/jscomp/integration/AdvancedOptimizationsIntegrationTest.java @@ -584,7 +584,6 @@ public final class AdvancedOptimizationsIntegrationTest extends IntegrationTestC options.setLanguageIn(LanguageMode.ECMASCRIPT_2015); options.setLanguageOut(LanguageMode.ECMASCRIPT_2015); CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options); - options.setExtraSmartNameRemoval(false); test(options, code, ""); } diff --git a/test/com/google/javascript/jscomp/integration/ClosureIntegrationTest.java b/test/com/google/javascript/jscomp/integration/ClosureIntegrationTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/integration/ClosureIntegrationTest.java +++ b/test/com/google/javascript/jscomp/integration/ClosureIntegrationTest.java @@ -200,7 +200,6 @@ public final class ClosureIntegrationTest extends IntegrationTestCase { CompilerOptions options = createCompilerOptions(); options.setSmartNameRemoval(true); - options.setExtraSmartNameRemoval(true); test(options, source, DiagnosticGroups.INVALID_CONST_PARAM); } diff --git a/test/com/google/javascript/jscomp/integration/IntegrationTest.java b/test/com/google/javascript/jscomp/integration/IntegrationTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/integration/IntegrationTest.java +++ b/test/com/google/javascript/jscomp/integration/IntegrationTest.java @@ -1603,7 +1603,6 @@ public final class IntegrationTest extends IntegrationTestCase { options.setRemoveUnusedVariables(Reach.ALL); options.setRemoveUnusedPrototypeProperties(true); options.setSmartNameRemoval(true); - options.setExtraSmartNameRemoval(true); options.setWarningLevel(DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.OFF); String code = "/** @constructor */ function A() {} " + @@ -1650,7 +1649,6 @@ public final class IntegrationTest extends IntegrationTestCase { options.setRemoveUnusedVariables(Reach.ALL); options.setRemoveUnusedPrototypeProperties(true); options.setSmartNameRemoval(true); - options.setExtraSmartNameRemoval(true); options.setFoldConstants(true); options.setInlineVariables(true); options.setWarningLevel(DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.OFF); @@ -1825,7 +1823,6 @@ public final class IntegrationTest extends IntegrationTestCase { options.setCheckTypes(true); options.setSmartNameRemoval(true); options.setFoldConstants(true); - options.setExtraSmartNameRemoval(true); options.setInlineVariables(true); options.setDisambiguateProperties(true); @@ -1876,7 +1873,6 @@ public final class IntegrationTest extends IntegrationTestCase { options.setCheckTypes(true); options.setSmartNameRemoval(true); options.setFoldConstants(true); - options.setExtraSmartNameRemoval(true); options.setInlineVariables(true); options.setDisambiguateProperties(true);
Make CompilerOptions#setExtraSmartNameRemoval() a noop in preparation for its removal. "extra smart name removal" is now always enabled with "smart name removal". PiperOrigin-RevId: <I>
google_closure-compiler
train
4c4b71d7e6e6d02d194ee45b48c208b7a7c183c9
diff --git a/main.js b/main.js index <HASH>..<HASH> 100644 --- a/main.js +++ b/main.js @@ -36,10 +36,8 @@ }); function getStyleComponentName(component) { - var camelize = Ember.String.camelize; - var dasherize = Ember.String.dasherize; - var name = component.toString().split('.')[1].split(':')[0]; - return dasherize(camelize(name)).replace('-component', '-css'); + // do not use _debugContainerKey without permission from Stefan Penner + return component._debugContainerKey.split(':')[1]+'-css'; } function lookupStyleComponent(component) {
don't depend on global namespace to work
instructure_ic-styled
train
538a87f541befac3d2b86764d40142ca06b6003e
diff --git a/util/util.go b/util/util.go index <HASH>..<HASH> 100644 --- a/util/util.go +++ b/util/util.go @@ -12,7 +12,7 @@ const ( ) var ( - byteSize = make([]byte, bytesPerInt) // Made for reusing in FormSize + bSize = make([]byte, bytesPerInt) // Made for reusing in FormSize ErrInvalidSizeFormat = errors.New("parsing size: invalid format of tag's/frame's size") ErrSizeOverflow = errors.New("forming size: size of tag/frame is more than allowed in id3 tag") @@ -20,37 +20,36 @@ var ( // FormSize transforms int to byte slice with ID3v2 size (4 * 0b0xxxxxxx). // -// If size more than allowed (256MB), then method returns SizeOverflow. +// If size more than allowed (256MB), then method returns ErrSizeOverflow. func FormSize(n int) ([]byte, error) { - allowedSize := 268435455 // 0b11111... (28 digits) - if n > allowedSize { + maxN := 268435455 // 0b11111... (28 digits) + if n > maxN { return nil, ErrSizeOverflow } mask := 1<<sizeBase - 1 - for i := range byteSize { - byteSize[len(byteSize)-i-1] = byte(n & mask) + for i := range bSize { + bSize[len(bSize)-1-i] = byte(n & mask) n >>= sizeBase } - return byteSize, nil + return bSize, nil } // ParseSize parses byte slice with ID3v2 size (4 * 0b0xxxxxxx) and returns // int64. // // If length of slice is more than 4 or if there is invalid size format (e.g. -// one byte in slice is like 0b1xxxxxxx), then method return InvalidSizeFormat. +// one byte in slice is like 0b1xxxxxxx), then method returns ErrInvalidSizeFormat. func ParseSize(data []byte) (int64, error) { - var size int64 - if len(data) > bytesPerInt { return 0, ErrInvalidSizeFormat } + var size int64 for _, b := range data { - if b&0x80 > 0 { // 0x80 = 0b1000_0000 + if b&128 > 0 { // 128 = 0b1000_0000 return 0, ErrInvalidSizeFormat }
Make some improvements for Form-/ParseSize
bogem_id3v2
train
6da34a6ba5ef97891fcf581cf9275fe16503a5d8
diff --git a/types.go b/types.go index <HASH>..<HASH> 100644 --- a/types.go +++ b/types.go @@ -112,6 +112,11 @@ func (m *Message) IsGroup() bool { return m.From.ID != m.Chat.ID } +// IsGroup returns if the message was sent to a group. +func (m *Message) IsCommand() bool { + return m.Text != "" && m.Text[0] == '/' +} + // PhotoSize contains information about photos, including ID and Width and Height. type PhotoSize struct { FileID string `json:"file_id"`
Message IsCommand method added
go-telegram-bot-api_telegram-bot-api
train
363fec59f7f72cef88735851573c9f2b4e3f2e61
diff --git a/src/CartSubItem.php b/src/CartSubItem.php index <HASH>..<HASH> 100644 --- a/src/CartSubItem.php +++ b/src/CartSubItem.php @@ -11,6 +11,8 @@ use LukePOLO\LaraCart\Traits\CartOptionsMagicMethodsTrait; */ class CartSubItem { + const ITEMS = 'items'; + use CartOptionsMagicMethodsTrait; private $itemHash; @@ -26,10 +28,16 @@ class CartSubItem public function __construct($options) { $this->itemHash = app(LaraCart::HASH, $options); - if (isset($options[LaraCart::PRICE]) === true) { + if (isset($options[LaraCart::PRICE])) { $this->price = $options[LaraCart::PRICE]; array_forget($options, LaraCart::PRICE); } + + if (isset($options[self::ITEMS])) { + $this->items = $options[self::ITEMS]; + array_forget($options, self::ITEMS); + } + $this->options = $options; }
Fixing issue if somone put items into the subItem Array
lukepolo_laracart
train
f03c5b5d1717f2ebec64032d269316dc74476056
diff --git a/lib/audited/auditor.rb b/lib/audited/auditor.rb index <HASH>..<HASH> 100644 --- a/lib/audited/auditor.rb +++ b/lib/audited/auditor.rb @@ -175,12 +175,13 @@ module Audited private def audited_changes + all_changes = respond_to?(:attributes_in_database) ? attributes_in_database : changed_attributes collection = if audited_options[:only] audited_columns = self.class.audited_columns.map(&:name) - changed_attributes.slice(*audited_columns) + all_changes.slice(*audited_columns) else - changed_attributes.except(*non_audited_columns) + all_changes.except(*non_audited_columns) end collection.inject({}) do |changes, (attr, old_value)|
Use updated AR::Dirty API to find changed attributes
collectiveidea_audited
train
ad4519a52d0e493b889dab7b03aac5e417eb4361
diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContains.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContains.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContains.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorContains.java @@ -135,7 +135,13 @@ public class OQueryOperatorContains extends OQueryOperatorEqualityNotNulls { if (key == null) return null; - final Object indexResult = index.get(key); + final Object indexResult; + if (iOperationType == INDEX_OPERATION_TYPE.GET) + indexResult = index.get(key); + else { + return index.count(key); + } + if (indexResult instanceof Collection) result = (Collection<OIdentifiable>) indexResult; else if (indexResult == null) diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorEquals.java b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorEquals.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorEquals.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/operator/OQueryOperatorEquals.java @@ -147,7 +147,9 @@ public class OQueryOperatorEquals extends OQueryOperatorEqualityNotNulls { final Object keyTwo = compositeIndexDefinition.createSingleValue(keyParams); - if (fetchLimit > -1) + if (INDEX_OPERATION_TYPE.COUNT.equals(iOperationType)) { + result = (long) index.getValuesBetween(keyOne, true, keyTwo, true).size(); + } else if (fetchLimit > -1) result = index.getValuesBetween(keyOne, true, keyTwo, true, fetchLimit); else result = index.getValuesBetween(keyOne, true, keyTwo, true);
Fix of count optimization for contains operator.
orientechnologies_orientdb
train
a94c9d4b89cb816679314a13e832f9144c0a39d2
diff --git a/src/rituals/invoke_tasks.py b/src/rituals/invoke_tasks.py index <HASH>..<HASH> 100644 --- a/src/rituals/invoke_tasks.py +++ b/src/rituals/invoke_tasks.py @@ -55,19 +55,20 @@ def clean(docs=False, backups=False, bytecode=False, dist=False, all=False, venv=False, extra=''): # pylint: disable=redefined-builtin """Perform house-cleaning.""" cfg = config.load() - patterns = ['build', 'pip-selfcheck.json'] + # TODO: replace "…/**/*" when dir patterns are added + patterns = ['build/**/*', 'pip-selfcheck.json'] if docs or all: - patterns.append('docs/_build') + patterns.append('docs/_build/**/*') if dist or all: - patterns.append('dist') + patterns.append('dist/**/*') if backups or all: patterns.extend(['*~', '**/*~']) if bytecode or all: - patterns.extend(['*.py[co]', '**/*.py[co]', '**/__pycache__']) + patterns.extend(['*.py[co]', '**/*.py[co]', '**/__pycache__/**/*']) venv_dirs = ['bin', 'include', 'lib', 'share', 'local'] if venv: - patterns.extend(venv_dirs) + patterns.extend([i + '/**/*' for i in venv_dirs]) if extra: patterns.extend(shlex.split(extra))
:bug: fixed recursive dir patterns
jhermann_rituals
train
ea6020e992da99397e6a6be838dd1a5fb904b497
diff --git a/spec/rdkafka/consumer_spec.rb b/spec/rdkafka/consumer_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rdkafka/consumer_spec.rb +++ b/spec/rdkafka/consumer_spec.rb @@ -724,6 +724,8 @@ describe Rdkafka::Consumer do # # This is, in effect, an integration test and the subsequent specs are # unit tests. + create_topic_handle = rdkafka_config.admin.create_topic(topic_name, 1, 1) + create_topic_handle.wait(max_wait_timeout: 15.0) consumer.subscribe(topic_name) produce_n 42 all_yields = [] @@ -777,6 +779,8 @@ describe Rdkafka::Consumer do end it "should yield [] if nothing is received before the timeout" do + create_topic_handle = rdkafka_config.admin.create_topic(topic_name, 1, 1) + create_topic_handle.wait(max_wait_timeout: 15.0) consumer.subscribe(topic_name) consumer.each_batch do |batch| expect(batch).to eq([])
Update specs to create topics in setup phase
appsignal_rdkafka-ruby
train
533a7905734dbeb08d234c4c9776b04ace95d5b0
diff --git a/scan.go b/scan.go index <HASH>..<HASH> 100644 --- a/scan.go +++ b/scan.go @@ -193,7 +193,7 @@ func Columns(src interface{}, includePk bool) ([]string, error) { // `column1`,`column2`,... // using Quote as the quote character. func (d *Database) ColumnsQuoted(src interface{}, includePk bool) (string, error) { - unquoted, err := Columns(src, includePk) + unquoted, err := d.Columns(src, includePk) if err != nil { return "", err }
Fix Columns() reference in ColumnsQuoted() (#<I>).
russross_meddler
train
74da92f778522fafc667a09cd4dfa5bf7f57a815
diff --git a/HISTORY.rst b/HISTORY.rst index <HASH>..<HASH> 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -1,6 +1,11 @@ History ======== +2.1.4 (2019-06-02) +------------------ + +* Handle BadStatusLine errors + 2.1.3 (2019-06-01) ------------------ diff --git a/simplenote/__init__.py b/simplenote/__init__.py index <HASH>..<HASH> 100644 --- a/simplenote/__init__.py +++ b/simplenote/__init__.py @@ -3,5 +3,5 @@ from .simplenote import Simplenote, SimplenoteLoginFailed __author__ = "Daniel Schauenberg" -__version__ = "2.1.3" +__version__ = "2.1.4" __license__ = "MIT" diff --git a/simplenote/simplenote.py b/simplenote/simplenote.py index <HASH>..<HASH> 100644 --- a/simplenote/simplenote.py +++ b/simplenote/simplenote.py @@ -15,11 +15,13 @@ if sys.version_info > (3, 0): from urllib.error import HTTPError import urllib.parse as urllib import html + from http.client import BadStatusLine else: import urllib2 from urllib2 import HTTPError import urllib from HTMLParser import HTMLParser + from httplib import BadStatusLine import base64 import time @@ -81,7 +83,7 @@ class Simplenote(object): try: res = urllib2.urlopen(request).read() token = json.loads(res.decode('utf-8'))["access_token"] - except HTTPError: + except (HTTPError, BadStatusLine): raise SimplenoteLoginFailed('Login to Simplenote API failed!') except IOError: # no connection exception token = None @@ -133,7 +135,7 @@ class Simplenote(object): raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.') else: return e, -1 - except IOError as e: + except (IOError, BadStatusLine) as e: return e, -1 note = json.loads(response.read().decode('utf-8')) note = self.__add_simplenote_api_fields(note, noteid, int(response.info().get("X-Simperium-Version"))) @@ -191,7 +193,7 @@ class Simplenote(object): raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.') else: return e, -1 - except IOError as e: + except (IOError, BadStatusLine) as e: return e, -1 note_to_update = json.loads(response.read().decode('utf-8')) note_to_update = self.__add_simplenote_api_fields(note_to_update, noteid, int(response.info().get("X-Simperium-Version"))) @@ -284,7 +286,7 @@ class Simplenote(object): raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.') else: return e, -1 - except IOError as e: + except (IOError, BadStatusLine) as e: return e, -1 # get additional notes if bookmark was set in response @@ -311,7 +313,7 @@ class Simplenote(object): raise SimplenoteLoginFailed('Login to Simplenote API failed! Check Token.') else: return e, -1 - except IOError as e: + except (IOError, BadStatusLine) as e: return e, -1 note_list = notes["index"] self.current = response_notes["current"] @@ -371,7 +373,7 @@ class Simplenote(object): request.add_header(self.header, self.get_token()) try: response = urllib2.urlopen(request) - except IOError as e: + except (IOError, BadStatusLine) as e: return e, -1 except HTTPError as e: if e.code == 401:
Handle BadStatusLine errors As far as I can tell this is really an issue in urllib2 as that should really catch and handle this error as URLError or HTTPError. But it doesn't seem to. More details/info in the issue. Fixes: #<I>
mrtazz_simplenote.py
train
5db40467c03db191115a12402f0145e738cd147d
diff --git a/examples/library/library.py b/examples/library/library.py index <HASH>..<HASH> 100644 --- a/examples/library/library.py +++ b/examples/library/library.py @@ -11,14 +11,17 @@ app.config['DEBUG'] = True app.config['MONGOALCHEMY_DATABASE'] = 'library' db = MongoAlchemy(app) + class Author(db.Document): name = db.StringField() + class Book(db.Document): title = db.StringField() author = db.DocumentField(Author) year = db.IntField() + @app.route('/author/new') def new_author(): """Creates a new author by a giving name (via GET parameter) @@ -29,6 +32,7 @@ def new_author(): author.save() return 'Saved :)' + @app.route('/authors/') def list_authors(): """List all authors.
examples/library: fix flake8 issues
cobrateam_flask-mongoalchemy
train