hash
stringlengths
40
40
diff
stringlengths
131
26.7k
message
stringlengths
7
694
project
stringlengths
5
67
split
stringclasses
1 value
diff_languages
stringlengths
2
24
cf7eccf55962fc59d98336da0b5526f27c0cd217
diff --git a/lib/blockscore/connection.rb b/lib/blockscore/connection.rb index <HASH>..<HASH> 100644 --- a/lib/blockscore/connection.rb +++ b/lib/blockscore/connection.rb @@ -5,12 +5,6 @@ require 'httparty' require 'blockscore/error' require 'blockscore/errors/invalid_request_error' -HEADERS = { - 'Accept' => 'application/vnd.blockscore+json;version=4', - 'User-Agent' => 'blockscore-ruby/4.1.0 (https://github.com/BlockScore/blockscore-ruby)', - 'Content-Type' => 'application/json' -} - module BlockScore module Connection mattr_accessor :api_key @@ -37,6 +31,14 @@ module BlockScore private + def headers + @@headers ||= { + 'Accept' => 'application/vnd.blockscore+json;version=4', + 'User-Agent' => 'blockscore-ruby/4.1.0 (https://github.com/BlockScore/blockscore-ruby)', + 'Content-Type' => 'application/json' + } + end + def request(method, path, params) response = execute_request(method, path, params) @@ -58,7 +60,6 @@ module BlockScore def execute_request(method, path, params) auth = { :username => @@api_key, :password => '' } - headers = HEADERS options = { :basic_auth => auth, :headers => headers, :body => params.to_json }
make headers a memoized method
BlockScore_blockscore-ruby
train
rb
25f3d3afe0b768e6b2b44e01845fc083685035f2
diff --git a/mamba/formatters.py b/mamba/formatters.py index <HASH>..<HASH> 100644 --- a/mamba/formatters.py +++ b/mamba/formatters.py @@ -91,8 +91,6 @@ class DocumentationFormatter(object): with indent(3): puts(colored.red('Failure/Error: %s' % self.format_failing_expectation(failed))) puts() - puts(colored.red(str(failed.exception))) - puts() puts('Traceback:') puts(colored.red(self.format_traceback(failed))) puts() @@ -110,11 +108,10 @@ class DocumentationFormatter(object): return ' '.join(result) def format_failing_expectation(self, spec_): - error = traceback.format_tb(spec_.traceback)[1:2][0] - return error.split('\n')[-2].strip() + return str(spec_.exception) def format_traceback(self, spec_): - return ''.join(traceback.format_tb(spec_.traceback)[1:]) + return ''.join([message[2:] for message in traceback.format_tb(spec_.traceback)[1:]]) def format_seconds(self, seconds): return '%.4f seconds' % seconds
Avoid fails when formatting traceback and it does not exists
nestorsalceda_mamba
train
py
0deef5bad6cb61d00fcccd62ee047ebb0fea37f7
diff --git a/bottle_sqlalchemy.py b/bottle_sqlalchemy.py index <HASH>..<HASH> 100644 --- a/bottle_sqlalchemy.py +++ b/bottle_sqlalchemy.py @@ -47,7 +47,7 @@ Usage Example:: db.add(entity) -It is up to you create engine, and metadata, because SQLAlchemy has +It is up to you create engine and metadata, because SQLAlchemy has a lot of options to do it. The plugin just handles the SQLAlchemy session.
Removed a comma So very OCD...
iurisilvio_bottle-sqlalchemy
train
py
bec4c9bcaf6851037607c60ceea30d5c44758119
diff --git a/tests/integration/runners/test_jobs.py b/tests/integration/runners/test_jobs.py index <HASH>..<HASH> 100644 --- a/tests/integration/runners/test_jobs.py +++ b/tests/integration/runners/test_jobs.py @@ -9,6 +9,7 @@ from __future__ import absolute_import, print_function, unicode_literals from tests.support.case import ShellCase from tests.support.unit import skipIf + class ManageTest(ShellCase): ''' Test the manage runner @@ -35,7 +36,7 @@ class ManageTest(ShellCase): ''' ret = self.run_run_plus('jobs.lookup_jid') expected = 'Passed invalid arguments:' - self.self.assertIn(expected, ret['return']) + self.assertIn(expected, ret['return']) @skipIf(True, 'to be re-enabled when #23623 is merged') def test_list_jobs(self):
Fixing typo in test_jobs. Fixing lint.
saltstack_salt
train
py
4d53c7c5a8d55a25c732334e07fae984691b3d38
diff --git a/master/buildbot/reporters/bitbucket.py b/master/buildbot/reporters/bitbucket.py index <HASH>..<HASH> 100644 --- a/master/buildbot/reporters/bitbucket.py +++ b/master/buildbot/reporters/bitbucket.py @@ -115,6 +115,8 @@ class BitbucketStatusPush(http.HttpStatusPushBase): if path.endswith('.git'): path = path[:-4] + while path.endswith('/'): + path = path[:-1] parts = path.split('/')
remove trailing / in the repo url
buildbot_buildbot
train
py
c78b0b86393f025076ae09bb3069a17c1c3e66e1
diff --git a/spec/file_spec.rb b/spec/file_spec.rb index <HASH>..<HASH> 100644 --- a/spec/file_spec.rb +++ b/spec/file_spec.rb @@ -12,7 +12,7 @@ describe Cap2::File do context 'when the file does have the given capability' do before(:each) do - system %{sudo setcap "cap_dac_override+p" #{file.path}} + run_as_root('permit(:dac_override)') end it { should be_permitted(:dac_override) } @@ -26,7 +26,7 @@ describe Cap2::File do context 'when the file does have the given capability' do before(:each) do - system %{sudo setcap "cap_dac_override+pe" #{file.path}} + run_as_root('permit(:dac_override)', 'enable_on_exec(:dac_override)') end it { should be_effective(:dac_override) } @@ -40,7 +40,7 @@ describe Cap2::File do context 'when the file does have the given capability' do before(:each) do - system %{sudo setcap "cap_dac_override+i" #{file.path}} + run_as_root('allow_inherit(:dac_override)') end it { should be_inheritable(:dac_override) }
Use `run_as_root` rather than `system 'sudo...` in file_spec.rb
lmars_cap2
train
rb
519f0682c54958151df7c2cb7d51349de99cf5be
diff --git a/test/test_bulk.py b/test/test_bulk.py index <HASH>..<HASH> 100644 --- a/test/test_bulk.py +++ b/test/test_bulk.py @@ -1043,7 +1043,7 @@ class TestBulkWriteConcern(BulkTestBase): 'op': {'_id': '...', 'a': 1}}]}, result) - self.assertEqual(2, len(result['writeConcernErrors'])) + self.assertTrue(len(result['writeConcernErrors']) > 1) failed = result['writeErrors'][0] self.assertTrue("duplicate" in failed['errmsg'])
Fix a bulk operations test for MongoDB <I> behavior change
mongodb_mongo-python-driver
train
py
1e18fc3285097c4a83582016b86d2e2835539a9f
diff --git a/filter-widget/Filter.js b/filter-widget/Filter.js index <HASH>..<HASH> 100644 --- a/filter-widget/Filter.js +++ b/filter-widget/Filter.js @@ -57,8 +57,8 @@ export const Filter = DefineMap.extend('Filter', { }); export const FilterList = DefineList.extend('FilterList', { - '#': Filter -}); + DefineMap: Filter +}, {}); export const FilterOptions = [{ label: 'Does not contain',
workaround can-define issue with '#' and concat
roemhildtg_spectre-canjs
train
js
a7656e3ad29f09d76a8d51fdda053f2a98dd1620
diff --git a/lib/hako/schedulers/ecs.rb b/lib/hako/schedulers/ecs.rb index <HASH>..<HASH> 100644 --- a/lib/hako/schedulers/ecs.rb +++ b/lib/hako/schedulers/ecs.rb @@ -139,7 +139,10 @@ module Hako unless page.service_arns.empty? @ecs.describe_services(cluster: @cluster, services: page.service_arns).services.each do |s| if s.status != 'INACTIVE' - max_port = [max_port, find_front_port(s)].max + port = find_front_port(s) + if port + max_port = [max_port, port].max + end end end end @@ -158,7 +161,9 @@ module Hako task_definition.container_definitions.each do |c| container_definitions[c.name] = c end - container_definitions['front'].port_mappings[0].host_port + if container_definitions.size == 2 && container_definitions['front'] && container_definitions['app'] + container_definitions['front'].port_mappings[0].host_port + end end def task_definition_changed?(front, app)
Ignore non-hako services
eagletmt_hako
train
rb
0b0aa5722ca89ef12de4495d03c88b32b1b3c90b
diff --git a/pykube/objects.py b/pykube/objects.py index <HASH>..<HASH> 100644 --- a/pykube/objects.py +++ b/pykube/objects.py @@ -4,6 +4,7 @@ import time import jsonpatch +from urllib import urlencode from .exceptions import ObjectDoesNotExist from .query import ObjectManager @@ -175,6 +176,21 @@ class Pod(NamespacedAPIObject): condition = next((c for c in cs if c["type"] == "Ready"), None) return condition is not None and condition["status"] == "True" + def get_logs(self, container=None): + url = "logs" + params = {} + if container is not None: + params["container"] = container + query_string = urlencode(params) + url += "?{}".format(query_string) if query_string else "" + kwargs = {'url': url, + 'pods': self.name, + 'namespace': self.namespace, + 'version': self.version} + r = self.api.get(**kwargs) + r.raise_for_status() + return r.json() + class ReplicationController(NamespacedAPIObject, ReplicatedAPIObject):
Adds implementation to get logs from the Pod object itself
kelproject_pykube
train
py
458ab2acff786c243eab15c5cf55bf5c0abd036e
diff --git a/ehforwarderbot/__main__.py b/ehforwarderbot/__main__.py index <HASH>..<HASH> 100644 --- a/ehforwarderbot/__main__.py +++ b/ehforwarderbot/__main__.py @@ -1,5 +1,5 @@ # coding=utf-8 - +import signal import threading import logging import argparse @@ -265,6 +265,8 @@ def main(): setup_telemetry(conf['telemetry']) atexit.register(stop_gracefully) + signal.signal(signal.SIGTERM, stop_gracefully) + signal.signal(signal.SIGINT, stop_gracefully) init(conf) poll() diff --git a/ehforwarderbot/__version__.py b/ehforwarderbot/__version__.py index <HASH>..<HASH> 100644 --- a/ehforwarderbot/__version__.py +++ b/ehforwarderbot/__version__.py @@ -1,3 +1,3 @@ # coding=utf-8 -__version__ = "2.0.0b21.dev1" +__version__ = "2.0.0b21.dev2"
Attempt to address #<I>: catch SIGTERM and SIGINT for graceful exit.
blueset_ehForwarderBot
train
py,py
949db3ed579bdcc231ab20070ae2e3b2c0768a6f
diff --git a/src/Form/FieldTextarea.js b/src/Form/FieldTextarea.js index <HASH>..<HASH> 100644 --- a/src/Form/FieldTextarea.js +++ b/src/Form/FieldTextarea.js @@ -11,7 +11,9 @@ class FieldTextarea extends FieldInput { constructor() { super(...arguments); - this.state = {height: 0}; + this.state = {height: this.props.minHeight}; + + console.log(this.props); this.updateTextareaHeight = Util.throttle(this.updateTextareaHeight, 100); this.handleContentEditableBlur = this.handleContentEditableBlur.bind(this); @@ -21,10 +23,6 @@ class FieldTextarea extends FieldInput { this.handleContentEditableFocus.bind(this); } - componentWillMount() { - this.setState({height: this.props.minHeight}); - } - componentDidMount() { super.componentDidMount(...arguments);
Assign minHeight in the constructor
mesosphere_reactjs-components
train
js
2895803e85aa7d3f09ba25c9e2abfb3796211252
diff --git a/go/cmd/vtctld/vtctld.go b/go/cmd/vtctld/vtctld.go index <HASH>..<HASH> 100644 --- a/go/cmd/vtctld/vtctld.go +++ b/go/cmd/vtctld/vtctld.go @@ -269,6 +269,7 @@ func (ar *ActionRepository) Apply(actionName string, zkPath string, r *http.Requ output, err := action(ar.wrangler, zkPath, r) if err != nil { result.error(err.Error()) + return result } result.Output = output return result
vtctld now will show the error.
vitessio_vitess
train
go
b529d7f0c0c0952431b7de477bc1c4cf78f54655
diff --git a/devices.js b/devices.js index <HASH>..<HASH> 100644 --- a/devices.js +++ b/devices.js @@ -1676,6 +1676,13 @@ const devices = [ extend: hue.light_onoff_brightness_colortemp, }, { + zigbeeModel: ['LTC021'], + model: '3435011P7', + vendor: 'Philips', + description: 'Hue white ambiance bathroom ceiling light Adore', + extend: hue.light_onoff_brightness_colortemp, + }, + { zigbeeModel: ['LTD003'], model: '4503848C5', vendor: 'Philips',
Add support for LTC<I> Philips Adore bathroom light (#<I>)
Koenkk_zigbee-shepherd-converters
train
js
eac13cc80286f905c4f62107fc69dfc201c0a015
diff --git a/gen/strings_test.go b/gen/strings_test.go index <HASH>..<HASH> 100644 --- a/gen/strings_test.go +++ b/gen/strings_test.go @@ -82,7 +82,7 @@ func TestAlphaString(t *testing.T) { t.Errorf("Invalid string: %#v", v) } } - if result.Sieve == nil || result.Sieve("01") { + if result.Sieve != nil && result.Sieve("01") { t.Error("Invalid sieve") } } @@ -106,7 +106,7 @@ func TestNumString(t *testing.T) { t.Errorf("Invalid string: %#v", v) } } - if result.Sieve == nil || result.Sieve("abc") { + if result.Sieve != nil && result.Sieve("abc") { t.Error("Invalid sieve") } } @@ -136,7 +136,7 @@ func TestIdentifier(t *testing.T) { t.Errorf("Invalid string: %#v", v) } } - if result.Sieve == nil || result.Sieve("0ab") || result.Sieve("ab\n") { + if result.Sieve != nil && (result.Sieve("0ab") || result.Sieve("ab\n")) { t.Error("Invalid sieve") } }
Sometimes Sieve is legitimately nil.
leanovate_gopter
train
go
037b1fa267d8f8c85fd7b1344282606cf0579894
diff --git a/expynent/patterns.py b/expynent/patterns.py index <HASH>..<HASH> 100644 --- a/expynent/patterns.py +++ b/expynent/patterns.py @@ -288,3 +288,9 @@ PHONE_NUMBER = { # RegEx pattern to match Taiwan phone numbers 'TW': r'^(?:\+886|0)((?:9\d{8})|(?:[2-8]\d{7,8}))$' } + +# List of RegEx patterns for license plates +LICENSE_PLATE = { + # Regex pattern to match Taiwanese license plates + 'TW': r'(^[A-Z0-9]{2,3}-\d{2,4}$)|(^\d{2,3}-[A-Z0-9]{2,3}$)|(^\d{4}-[A-Z0-9]{2}$)|' + } \ No newline at end of file
added Taiwanese license plate regex
lk-geimfari_expynent
train
py
6f73675b94e3ea392c7e9259b83c1cf38a619b91
diff --git a/lib/discordrb/bot.rb b/lib/discordrb/bot.rb index <HASH>..<HASH> 100644 --- a/lib/discordrb/bot.rb +++ b/lib/discordrb/bot.rb @@ -660,22 +660,6 @@ module Discordrb token_cache.store_token(email, password, token) token - rescue Exception => e - response_code = login_response.nil? ? 0 : login_response.code ######## mackmm145 - if login_attempts < 100 && (e.inspect.include?('No such host is known.') || response_code == 523) - debug("Login failed! Reattempting in 5 seconds. #{100 - login_attempts} attempts remaining.") - debug("Error was: #{e.inspect}") - sleep 5 - login_attempts += 1 - retry - else - debug("Login failed permanently after #{login_attempts + 1} attempts") - - # Apparently we get a 400 if the password or username is incorrect. In that case, tell the user - debug("Are you sure you're using the correct username and password?") if e.class == RestClient::BadRequest - log_exception(e) - raise $ERROR_INFO - end end def retrieve_token(email, password, token_cache)
Completely redo the user_login error handling
meew0_discordrb
train
rb
1acf9dd8b3fafbfa2195082310cec2a443e973c1
diff --git a/browser/environment/helpers.js b/browser/environment/helpers.js index <HASH>..<HASH> 100644 --- a/browser/environment/helpers.js +++ b/browser/environment/helpers.js @@ -121,6 +121,16 @@ window.flush = function flush(callback) { }; /** + * Advances a single animation frame. + * @param {function()} callback + */ +window.animationFrameFlush = function animationFrameFlush(callback) { + requestAnimationFrame(function() { + flush(callback); + }); +} + +/** * DEPRECATED: Use `flush`. * @param {function} callback */
Add animationFrameFlush.
Polymer_web-component-tester
train
js
57acef15d229ab2350f51845a02447e49c2f7f6c
diff --git a/pushy/src/test/java/com/relayrides/pushy/apns/ApnsClientTest.java b/pushy/src/test/java/com/relayrides/pushy/apns/ApnsClientTest.java index <HASH>..<HASH> 100644 --- a/pushy/src/test/java/com/relayrides/pushy/apns/ApnsClientTest.java +++ b/pushy/src/test/java/com/relayrides/pushy/apns/ApnsClientTest.java @@ -240,6 +240,7 @@ public class ApnsClientTest { this.tokenAuthenticationClient = new ApnsClientBuilder() .setTrustedServerCertificateChain(CA_CERTIFICATE) .setEventLoopGroup(EVENT_LOOP_GROUP) + .setSslProvider(this.preferredSslProvider) .build(); this.tlsAuthenticationClient.connect(HOST, PORT).await();
Fixed a goof where the token-auth client wasn't paying attention to the preferred SSL provider.
relayrides_pushy
train
java
583f00ce317dfb4c2c6c4df4bd4694c6f0b0bf18
diff --git a/aiogram/types/base.py b/aiogram/types/base.py index <HASH>..<HASH> 100644 --- a/aiogram/types/base.py +++ b/aiogram/types/base.py @@ -211,6 +211,15 @@ class TelegramObject(ContextInstanceMixin, metaclass=MetaTelegramObject): """ return self.as_json() + def __repr__(self) -> str: + """ + Return object readable representation. + + Example: <ObjectName {"id": 123456}> + :return: object class name and object data as a string + """ + return f"<{type(self).__name__} {self}>" + def __getitem__(self, item: typing.Union[str, int]) -> typing.Any: """ Item getter (by key)
feat: TelegramObject readable representation (#<I>)
aiogram_aiogram
train
py
ca8fd588052a92397f6d643a6c519957433a5cbf
diff --git a/unit/manager.go b/unit/manager.go index <HASH>..<HASH> 100644 --- a/unit/manager.go +++ b/unit/manager.go @@ -161,6 +161,10 @@ func (m *SystemdManager) removeUnit(name string) { log.Printf("Unlinking systemd unit %s from target %s", name, m.Target.Name()) link := m.getLocalPath(path.Join(m.Target.Name()+".wants", name)) syscall.Unlink(link) + + file := m.getLocalPath(name) + log.Printf("Removing systemd unit file %s", file) + syscall.Unlink(file) } func (m *SystemdManager) readUnit(name string) (string, error) {
fix(agent): Unlink unit files when jobs are stopped
coreos_fleet
train
go
17c9c8a7e4834c42cdd474d9b1f3c65ef609ebce
diff --git a/lib/launchy/applications/browser.rb b/lib/launchy/applications/browser.rb index <HASH>..<HASH> 100644 --- a/lib/launchy/applications/browser.rb +++ b/lib/launchy/applications/browser.rb @@ -20,7 +20,7 @@ class Launchy::Application end def nix_app_list - nix_de = Launchy::Detect::NixDekstopEnvironment.browser + nix_de = Launchy::Detect::NixDesktopEnvironment.detect app_list = %w[ xdg-open ] app_list << nix_de.browser app_list << nix_de.fallback_browsers diff --git a/lib/launchy/detect/runner.rb b/lib/launchy/detect/runner.rb index <HASH>..<HASH> 100644 --- a/lib/launchy/detect/runner.rb +++ b/lib/launchy/detect/runner.rb @@ -29,7 +29,7 @@ module Launchy::Detect def shell_commands( cmd, args ) cmdline = [ cmd.shellsplit ] cmdline << args.collect{ |a| a.to_s.shellescape } - return commanddline_normalize( cmdline ) + return commandline_normalize( cmdline ) end def commandline_normalize( cmdline )
Fix browser opening in *nix; fixes gh-<I>, gh-<I>
copiousfreetime_launchy
train
rb,rb
fc9919f9a342694b817965f5c149fafbe4e1d9d2
diff --git a/spring-jdbc-oracle/src/main/java/com/github/ferstl/spring/jdbc/oracle/SqlOracleArrayValue.java b/spring-jdbc-oracle/src/main/java/com/github/ferstl/spring/jdbc/oracle/SqlOracleArrayValue.java index <HASH>..<HASH> 100644 --- a/spring-jdbc-oracle/src/main/java/com/github/ferstl/spring/jdbc/oracle/SqlOracleArrayValue.java +++ b/spring-jdbc-oracle/src/main/java/com/github/ferstl/spring/jdbc/oracle/SqlOracleArrayValue.java @@ -19,6 +19,8 @@ import java.sql.Array; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; +import java.util.Arrays; + import org.springframework.dao.CleanupFailureDataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.jdbc.core.JdbcTemplate; @@ -111,4 +113,12 @@ public final class SqlOracleArrayValue implements NamedSqlValue { } } + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return Arrays.toString(this.values); + } + }
Implement SqlOracleArrayValue#toString Implement SqlOracleArrayValue#toString for debug purposes. It is extremely helpful to have a good #toString while debugging in the IDE.
ferstl_spring-jdbc-oracle
train
java
6db1eb697502b4070f2d4d1471cd9b314af9a570
diff --git a/lib/Sabre/HTTP/Request.php b/lib/Sabre/HTTP/Request.php index <HASH>..<HASH> 100644 --- a/lib/Sabre/HTTP/Request.php +++ b/lib/Sabre/HTTP/Request.php @@ -35,9 +35,8 @@ class Sabre_HTTP_Request { if (is_null($this->body)) { $this->body = file_get_contents('php://input'); - } else { - return $this->body; - } + } + return $this->body; }
Path by Andreas Gohr, Thanks!
sabre-io_dav
train
php
a3fdcd1b8d88f97e55fc771321e7dd0a4e21de16
diff --git a/src/BoomCMS/Chunk/Linkset.php b/src/BoomCMS/Chunk/Linkset.php index <HASH>..<HASH> 100644 --- a/src/BoomCMS/Chunk/Linkset.php +++ b/src/BoomCMS/Chunk/Linkset.php @@ -25,10 +25,7 @@ class Linkset extends BaseChunk 'limit' => 0, ]; - /** - * @return array - */ - public function attributes() + public function attributes(): array { foreach ($this->options as $key => $value) { $attrs[$this->attributePrefix.$key] = (int) $value; @@ -77,17 +74,15 @@ class Linkset extends BaseChunk /** * Returns true if the linkset contains any links. - * - * @return bool */ - public function hasContent() + public function hasContent(): bool { return count($this->getLinks()) > 0; } - public function getTitle() + public function getTitle(): string { - return isset($this->attrs['title']) ? $this->attrs['title'] : ''; + return $this->attrs['title'] ?? ''; } /**
Chunk linkset: Added PHP7 features to Linkset class
boomcms_boom-core
train
php
0357093f6f99b297835522f84f4b48e0ab44cb23
diff --git a/packages/core/src/index.js b/packages/core/src/index.js index <HASH>..<HASH> 100644 --- a/packages/core/src/index.js +++ b/packages/core/src/index.js @@ -9,7 +9,7 @@ import { import Component from './component' import Render, { Router } from './render' -import { State, Effect, Hook, Actions, StateDefaults } from 'jumpstate' +import { State, Effect, Hook, Actions, StateDefaults, getState, dispatch } from 'jumpstate' import Goto from './routing' import { Middleware } from './reducer' @@ -34,6 +34,8 @@ module.exports = { /* Redux */ Middleware, + getState, + dispatch, /* Other */ StateDefaults
Expose getState and dispatch from jumpstate
jsonmaur_jumpsuit
train
js
3f87ad8555ff9ba5c3e66466e213a5ef513bbb92
diff --git a/lib/odata/query/criteria.rb b/lib/odata/query/criteria.rb index <HASH>..<HASH> 100644 --- a/lib/odata/query/criteria.rb +++ b/lib/odata/query/criteria.rb @@ -1,21 +1,32 @@ module OData class Query + # Represents a discreet detail about an OData query. It also validates + # the criteria based on what the gem knows how to support. class Criteria + # Defines the options required to create a new OData::Query::Criteria. REQUIRED_OPTIONS = [:operation, :argument] + + # Defines the operations the OData gem knows how to support. SUPPORTED_OPERATIONS = [ :filter, :order_by, :skip, :top, :select, :expand, :inlinecount ] + # Creates a new OData::Query::Criteria with the supplied options. + # @param options [Hash] def initialize(options = {}) @options = process_options(options) validate_required_options validate_supported_operation end + # The query operation of a particular criteria. + # @return [Symbol] def operation options[:operation] end + # The query argument of a particular criteria. + # @return [String] def argument options[:argument] end
Updated YARD documentation. [ci skip]
ruby-odata_odata
train
rb
d333b1beff08ae8a25fead947995f8fd839effe5
diff --git a/src/Cascader/Dropdown.js b/src/Cascader/Dropdown.js index <HASH>..<HASH> 100644 --- a/src/Cascader/Dropdown.js +++ b/src/Cascader/Dropdown.js @@ -296,16 +296,17 @@ class Dropdown extends React.Component<Props, State> { handleSearchRowSelect = (item: Object, event: DefaultEvent) => { const { valueKey, onChange, onSelect } = this.props; const value = item[valueKey]; + const nextState = getDerivedStateForCascade(this.props, this.state, value); this.closeDropdown(); this.setState({ - ...getDerivedStateForCascade(this.props, this.state, value), + ...nextState, selectNode: item, searchKeyword: '', value }); - onSelect && onSelect(item, null, null, event); + onSelect && onSelect(item, nextState.activePaths, null, event); onChange && onChange(value, event); };
Fixed an issue with Cascader select search result. (#<I>)
rsuite_rsuite
train
js
b5cca4d1605ff95fb2bcfa61cc5158f71dc2dddc
diff --git a/pymatgen/io/vasp/sets.py b/pymatgen/io/vasp/sets.py index <HASH>..<HASH> 100644 --- a/pymatgen/io/vasp/sets.py +++ b/pymatgen/io/vasp/sets.py @@ -370,7 +370,7 @@ class DictSet(VaspInputSet): for mag in incar['MAGMOM']]) incar['NUPDOWN'] = nupdown - if self.use_structure_charge and self.structure.charge: + if self.use_structure_charge: incar["NELECT"] = self.nelect return incar @@ -392,7 +392,11 @@ class DictSet(VaspInputSet): if ps.element in site_symbols: site_symbols.remove(ps.element) nelect += self.structure.composition.element_composition[ps.element] * ps.ZVAL - return int(round(nelect)) - self.structure.charge + + if self.use_structure_charge: + return int(round(nelect)) - self.structure.charge + else: + return int(round(nelect)) @property def kpoints(self):
Fix setting NELECT only when told to
materialsproject_pymatgen
train
py
b77efec36c073d0fab88d6bdc99aedd3d40feef4
diff --git a/uncompyle6/parsers/reducecheck/or_check.py b/uncompyle6/parsers/reducecheck/or_check.py index <HASH>..<HASH> 100644 --- a/uncompyle6/parsers/reducecheck/or_check.py +++ b/uncompyle6/parsers/reducecheck/or_check.py @@ -38,6 +38,7 @@ def or_check(self, lhs, n, rule, ast, tokens, first, last): last_token = tokens[last] last_token_offset = last_token.off2int() + # FIXME: use instructions for all of this if jmp_true_target < first_offset: return False elif jmp_true_target < last_token_offset: @@ -49,8 +50,10 @@ def or_check(self, lhs, n, rule, ast, tokens, first, last): # For a backwards loop, well compare to the instruction *after* # then POP_JUMP... last_token = tokens[last + 1] + # HACK alert 3 is the Python < 3.6ish thing. + # Convert to using instructions return not ( - (last_token_offset <= jmp_true_target <= last_token_offset + 2) + (last_token_offset <= jmp_true_target <= last_token_offset + 3) or jmp_true_target < tokens[first].off2int() ) elif last_token == "JUMP_FORWARD" and expr_jt.kind != "expr_jitop":
git commit -m'Adjust "or" offset check ... for Python < <I> hopefully it doesn't break Python <I>+
rocky_python-uncompyle6
train
py
e56fe8a2e8eb8d4fadee0fbaa226c1b275da4246
diff --git a/libs/render.js b/libs/render.js index <HASH>..<HASH> 100644 --- a/libs/render.js +++ b/libs/render.js @@ -7,6 +7,10 @@ var isEngine = function(engine) { return typeof(engine) === 'function'; } +var isRemote = function(dir) { + return dir && (dir.indexOf('http') === 0 || dir.indexOf('https') === 0); +} + // 根据给定的主题名称或者文件名称渲染邮件 // 不指定引擎渲染的话会自动寻找支持的模板引擎 // e.g: exports.render('mails-flat/message', {...}, callback); @@ -22,7 +26,10 @@ module.exports = function(template, data, callback, e) { var engine = {}; var dest = file.exist ? file.dir : file.availables[0]; engine.name = theme['view engine']; + // 主题相关信息 data.Theme = theme; + // 渲染页面时要进行 #{static} 变量的替换,这里就是替换成相应主题在 public 下的目录 + data.static = isRemote(theme.static) ? theme.static : '/' + theme.name; try { engine._engine = isEngine(e) ? e : require(theme['view engine']); } catch (err) {
<I>: move static locals in
guo-yu_pkghub-render
train
js
325e4b6e2760caac39a704dab81fc3a8e830b017
diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index <HASH>..<HASH> 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -20,6 +20,7 @@ from pandas.core.dtypes.missing import isna import pandas as pd import pandas._testing as tm +from pandas.api.types import pandas_dtype from pandas.arrays import SparseArray @@ -400,6 +401,23 @@ def test_is_int64_dtype(dtype): assert com.is_int64_dtype(dtype) +def test_type_comparison_with_numeric_ea_dtype(any_numeric_ea_dtype): + # GH#43038 + assert pandas_dtype(any_numeric_ea_dtype) == any_numeric_ea_dtype + + +def test_type_comparison_with_real_numpy_dtype(any_real_numpy_dtype): + # GH#43038 + assert pandas_dtype(any_real_numpy_dtype) == any_real_numpy_dtype + + +def test_type_comparison_with_signed_int_ea_dtype_and_signed_int_numpy_dtype( + any_signed_int_ea_dtype, any_signed_int_numpy_dtype +): + # GH#43038 + assert not pandas_dtype(any_signed_int_ea_dtype) == any_signed_int_numpy_dtype + + @pytest.mark.parametrize( "dtype", [
tests added for dtype comparison with fixture (#<I>)
pandas-dev_pandas
train
py
3af33b35d588f6fc9712c81ab7c546a0ad3b4673
diff --git a/git_ready.py b/git_ready.py index <HASH>..<HASH> 100644 --- a/git_ready.py +++ b/git_ready.py @@ -48,7 +48,8 @@ def main(branch): # Ensure that we're in a git repository. This command is silent unless # you're not actually in a git repository, in which case, you receive a # "Not a git repository" error message. - sys.stdout.write(subprocess.check_output(['git', 'rev-parse'])) + output = subprocess.check_output(['git', 'rev-parse']).decode('utf-8') + sys.stdout.write(output) except subprocess.CalledProcessError: # Bail if we're not in a git repository. return
Decode bytes from stdout
dolph_git-ready
train
py
2c26122ec17d612ccd3049c346e5e6c75e7c9220
diff --git a/app/models/chouette/route.rb b/app/models/chouette/route.rb index <HASH>..<HASH> 100644 --- a/app/models/chouette/route.rb +++ b/app/models/chouette/route.rb @@ -16,7 +16,7 @@ class Chouette::Route < Chouette::TridentActiveRecord def find_by_stop_area(stop_area) stop_area_ids = Integer === stop_area ? [stop_area] : (stop_area.children_in_depth + [stop_area]).map(&:id) where( :stop_area_id => stop_area_ids).first or - raise ActiveRecord::RecordNotFound.new("Can't find a StopArea #{stop_area.inspect} in Route #{owner.id.inspect}'s StopPoints") + raise ActiveRecord::RecordNotFound.new("Can't find a StopArea #{stop_area.inspect} in Route #{proxy_owner.id.inspect}'s StopPoints") end def between(departure, arrival) @@ -40,7 +40,7 @@ class Chouette::Route < Chouette::TridentActiveRecord departure, arrival = [departure, arrival].collect do |endpoint| String === endpoint ? Chouette::StopArea.find_by_objectid(endpoint) : endpoint end - proxy_owner.stop_points.between(departure, arrival).includes(:stop_areas).collect(&:stop_area) + proxy_owner.stop_points.between(departure, arrival).includes(:stop_area).collect(&:stop_area) end end
Use stop_area relation in place of stop_areas for stop_points
afimb_ninoxe
train
rb
c69d8347e60b756cb6f81c906a47744d3b4276d7
diff --git a/djcelery/management/commands/celeryctl.py b/djcelery/management/commands/celeryctl.py index <HASH>..<HASH> 100644 --- a/djcelery/management/commands/celeryctl.py +++ b/djcelery/management/commands/celeryctl.py @@ -22,4 +22,7 @@ class Command(CeleryCommand): def run_from_argv(self, argv): util = celeryctl(app=app) - util.execute_from_commandline(argv[1:]) + + util.execute_from_commandline(self.handle_default_options(argv)[1:]) + +
Fixing #<I> (--settings not supported with celeryctl). Code was already there. One just has to call it
celery_django-celery
train
py
e883617808844fcf20b5d5512f033ac437dfba7d
diff --git a/src/ossos/core/ossos/wcs.py b/src/ossos/core/ossos/wcs.py index <HASH>..<HASH> 100644 --- a/src/ossos/core/ossos/wcs.py +++ b/src/ossos/core/ossos/wcs.py @@ -106,6 +106,10 @@ class WCS(astropy_wcs.WCS): return pos[0] * units.degree, pos[1] * units.degree def sky2xy(self, ra, dec, usepv=True): + if isinstance(ra, Quantity): + ra = ra.to(units.degree).value + if isinstance(dec, Quantity): + dec = dec.to(units.degree).value try: if usepv: return sky2xypv(ra=ra, @@ -120,10 +124,7 @@ class WCS(astropy_wcs.WCS): except Exception as ex: logger.warning("sky2xy raised exception: {0}".format(ex)) logger.warning("Reverted to CD-Matrix WCS to convert: {0} {1} ".format(ra, dec)) - if isinstance(ra, Quantity): - ra = ra.to(units.degree).value - if isinstance(dec, Quantity): - dec = dec.to(units.degree).value + print ex pos = self.wcs_world2pix([[ra, dec], ], 1) return pos[0][0], pos[0][1]
the sky2xy function expects to be using values not quanities.. so set them to values here.
OSSOS_MOP
train
py
7548d8347b99a75b5bb8d458b62a80eecf3a87fc
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -17,7 +17,6 @@ require 'alchemy/seeder' require 'alchemy/test_support/auth_helpers' require 'alchemy/test_support/controller_requests' require 'alchemy/test_support/integration_helpers' -require 'alchemy/test_support/essence_shared_examples' require 'alchemy/test_support/factories' require 'capybara/poltergeist' require 'capybara/rails' @@ -29,6 +28,8 @@ require 'rspec/rails' require_relative "support/hint_examples.rb" require_relative "support/transformation_examples.rb" +require 'alchemy/test_support/essence_shared_examples' + ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true ActionMailer::Base.default_url_options[:host] = "test.com"
Move require `essence_shared_examples` after rspec in spec_helper. .. as `shared_examples_for` is an rspec method, which needs to be defined beforehand.
AlchemyCMS_alchemy_cms
train
rb
186c1ce03274c1dbab09f585ae3da3c3759960c0
diff --git a/lib/neo4j/active_node/labels/reloading.rb b/lib/neo4j/active_node/labels/reloading.rb index <HASH>..<HASH> 100644 --- a/lib/neo4j/active_node/labels/reloading.rb +++ b/lib/neo4j/active_node/labels/reloading.rb @@ -14,6 +14,7 @@ module Neo4j::ActiveNode::Labels associations.each_value(&:queue_model_refresh!) MODELS_FOR_LABELS_CACHE.clear WRAPPED_CLASSES.each { |c| MODELS_TO_RELOAD << c.name } + WRAPPED_CLASSES.clear end end end
Put this back, because of course it broke things
neo4jrb_neo4j
train
rb
d294c5741895bbc1c4ddadbfa82fab190af0e01b
diff --git a/abodepy/devices/light.py b/abodepy/devices/light.py index <HASH>..<HASH> 100644 --- a/abodepy/devices/light.py +++ b/abodepy/devices/light.py @@ -1,6 +1,7 @@ """Abode light device.""" import json import logging +import math from abodepy.exceptions import AbodeException @@ -74,8 +75,11 @@ class AbodeLight(AbodeSwitch): if response_object['idForPanel'] != self.device_id: raise AbodeException((ERROR.SET_STATUS_DEV_ID)) - if (response_object['hue'] != int(hue) or - response_object['saturation'] != int(saturation)): + # Abode will sometimes return hue value off by 1 (rounding error) + hue_comparison = math.isclose(response_object["hue"], + int(hue), abs_tol=1) + if not hue_comparison or (response_object["saturation"] + != int(saturation)): _LOGGER.warning( ("Set color mismatch for device %s. " "Request val: %s, Response val: %s "),
Fix for hue logging issue (#<I>) * Fix for hue logging issue * Fix for saturation comparison * Yet another fix for comparison confusion
MisterWil_abodepy
train
py
531fcade9053706cd0e9e4a49ddc29fd98a623dd
diff --git a/termdown.py b/termdown.py index <HASH>..<HASH> 100755 --- a/termdown.py +++ b/termdown.py @@ -9,7 +9,9 @@ import click from dateutil.parser import parse from pyfiglet import Figlet -TIMEDELTA_REGEX = re.compile(r'((?P<hours>\d+)h ?)?' +TIMEDELTA_REGEX = re.compile(r'((?P<years>\d+)y ?)?' + r'((?P<days>\d+)d ?)?' + r'((?P<hours>\d+)h ?)?' r'((?P<minutes>\d+)m ?)?' r'((?P<seconds>\d+)s ?)?') @@ -65,6 +67,11 @@ def parse_timedelta(deltastr): for name, value in matches.groupdict().items(): if value: components[name] = int(value) + for period, hours in (('days', 24), ('years', 8766)): + if period in components: + components['hours'] = components.get('hours', 0) + \ + components[period] * hours + del components[period] return int(timedelta(**components).total_seconds())
allow days and years in timedelta STARTs
trehn_termdown
train
py
64547763863ec3736216967b2970866077785208
diff --git a/synapse/cores/ram.py b/synapse/cores/ram.py index <HASH>..<HASH> 100644 --- a/synapse/cores/ram.py +++ b/synapse/cores/ram.py @@ -19,11 +19,11 @@ class Cortex(common.Cortex): def _sizeByRange(self, prop, valu, limit=None): # HACK: for speed - data = dict(size=0) + data = [0] def inc(): - data['size'] += 1 + data[0] += 1 [ inc() for r in self.rowsbyprop.get(prop,()) if r[2] >= valu[0] and r[2] < valu[1] ] - return data['size'] + return data[0] def _rowsByRange(self, prop, valu, limit=None): # HACK: for speed
optimized sizeByRange for ram cortex
vertexproject_synapse
train
py
393f0c961220893ab75e4627f1487608014502a7
diff --git a/session.go b/session.go index <HASH>..<HASH> 100644 --- a/session.go +++ b/session.go @@ -227,18 +227,26 @@ func (s *Session) init() error { } hosts = hosts[:0] + + var wg sync.WaitGroup for _, host := range hostMap { - host = s.ring.addOrUpdate(host) + host := s.ring.addOrUpdate(host) if s.cfg.filterHost(host) { continue } host.setState(NodeUp) - s.pool.addHost(host) - hosts = append(hosts, host) + + wg.Add(1) + go func() { + defer wg.Done() + s.pool.addHost(host) + }() } + wg.Wait() + type bulkAddHosts interface { AddHosts([]*HostInfo) }
Init host pools in parallel. (#<I>) Creating a session can take a long time if your cluster is big and there's latency between you and the cluster. We are seeing it take ~<I>s to create a session to a <I> node cluster with ~<I>ms of latency. This is somewhat related to #<I> and #<I>, but this change tries to do the simplest thing to speed up initial connection without changing any behavior.
gocql_gocql
train
go
972d98f05d91431b93c13c97ff1da268780f24cb
diff --git a/Application.php b/Application.php index <HASH>..<HASH> 100644 --- a/Application.php +++ b/Application.php @@ -169,6 +169,11 @@ class Application extends HttpKernel */ private function throwUncaughtInfrastructureException(Exception $exception) { + (new ApplicationLogService())->getLogger()->critical( + 'Error: ' . $exception->getMessage(), + $exception->getTrace() + ); + if (getenv('ENV') == self::ENV_PROD) { throw new HttpException(Response::HTTP_INTERNAL_SERVER_ERROR, 'Internal server error'); }
[update] add the logging for uncaught infrastructure exceptions
Antonyan_ddd-mappers-infrastructure
train
php
e90926a4932b86e6e2d4a5c43524692e25bc4d96
diff --git a/app/controllers/marty/diagnostic/controller.rb b/app/controllers/marty/diagnostic/controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/marty/diagnostic/controller.rb +++ b/app/controllers/marty/diagnostic/controller.rb @@ -5,7 +5,7 @@ module Marty def self.inherited(klass) namespace = klass.name.deconstantize.split('::')[0] rescue '' - Marty::Diagnostic::Reporter.namespaces.unshift(namespace) + Reporter.namespaces.unshift(namespace) super end
revert changes to diag controller
arman000_marty
train
rb
67e2d81af716ef974cf17589eb8416ff663e3ce4
diff --git a/lib/Controller/Data.php b/lib/Controller/Data.php index <HASH>..<HASH> 100644 --- a/lib/Controller/Data.php +++ b/lib/Controller/Data.php @@ -87,10 +87,10 @@ abstract class Controller_Data extends AbstractController { // abstract function loadByConditions($model); // abstract function deleteAll($model); - /** Create a new cursor and load model with the first entry */ + /** Create a new cursor and load model with the first entry. Returns cursor */ abstract function prefetchAll($model); - /** Provided that rewind was called before, load next data entry */ - abstract function loadCurrent($model); + /** Load next data row from cursor */ + abstract function loadCurrent($model,&$cursor); } diff --git a/lib/Model.php b/lib/Model.php index <HASH>..<HASH> 100644 --- a/lib/Model.php +++ b/lib/Model.php @@ -766,14 +766,15 @@ class Model extends AbstractModel implements ArrayAccess,Iterator,Countable { // }}} // {{{ Iterator support + public $_cursor=null; function rewind() { $this->unload(); - $this->controller->prefetchAll($this); + $this->_cursor = $this->controller->prefetchAll($this); $this->next(); } function next() { $this->hook('beforeLoad', array('iterating')); - $this->controller->loadCurrent($this); + $this->controller->loadCurrent($this,$this->_cursor); if($this->loaded()) { $this->hook('afterLoad'); }
Store "cursor" inside model instead of controller, when iterating through adta.
atk4_atk4
train
php,php
7dc6549e666becb30ab5d0756155c55c697aef8d
diff --git a/support/cas-server-support-aws-cognito-authentication/src/main/java/org/apereo/cas/authentication/AmazonCognitoAuthenticationAuthenticationHandler.java b/support/cas-server-support-aws-cognito-authentication/src/main/java/org/apereo/cas/authentication/AmazonCognitoAuthenticationAuthenticationHandler.java index <HASH>..<HASH> 100644 --- a/support/cas-server-support-aws-cognito-authentication/src/main/java/org/apereo/cas/authentication/AmazonCognitoAuthenticationAuthenticationHandler.java +++ b/support/cas-server-support-aws-cognito-authentication/src/main/java/org/apereo/cas/authentication/AmazonCognitoAuthenticationAuthenticationHandler.java @@ -82,8 +82,8 @@ public class AmazonCognitoAuthenticationAuthenticationHandler extends AbstractUs } val userResult = cognitoIdentityProvider.adminGetUser(AdminGetUserRequest.builder() - .userPoolId(credential.getUsername()) - .userPoolId(properties.getUserPoolId()).build()); + .userPoolId(properties.getUserPoolId()) + .username(credential.getUsername()).build()); val attributes = new LinkedHashMap<String, List<Object>>(); attributes.put("userStatus", CollectionUtils.wrap(userResult.userStatusAsString()));
Amazon Cognito Authentication: fix adminGetUser (#<I>) (cherry picked from commit <I>f<I>aaaff<I>f<I>a2f<I>f<I>bd<I>fc0b)
apereo_cas
train
java
180296ac9bb43fb0436458a2b8769aaa58bf8b33
diff --git a/src/processors/DropProcessor.php b/src/processors/DropProcessor.php index <HASH>..<HASH> 100644 --- a/src/processors/DropProcessor.php +++ b/src/processors/DropProcessor.php @@ -113,13 +113,13 @@ class DropProcessor extends AbstractProcessor { $object['expr_type'] = $objectType; if ($objectType === ExpressionType::TABLE || $objectType === ExpressionType::TEMPORARY_TABLE) { $object['table'] = $trim; + $object['no_quotes'] = false; $object['alias'] = false; - } else { - $object['base_expr'] = $trim; } - $object['no_quote'] = $this->revokeQuotation($trim); + $object['base_expr'] = $trim; + $object['no_quotes'] = $this->revokeQuotation($trim); $object['delim'] = false; - + $objectList[] = $object; continue 2; }
CHG: the property no_quote has been renamed into no_quotes. CHG: the property order within the table part has been changed. git-svn-id: <URL>
greenlion_PHP-SQL-Parser
train
php
a3100066d8c827396e94fa67314ef7fd540332ed
diff --git a/webwhatsapi/__init__.py b/webwhatsapi/__init__.py index <HASH>..<HASH> 100644 --- a/webwhatsapi/__init__.py +++ b/webwhatsapi/__init__.py @@ -23,7 +23,7 @@ class WhatsAPIDriver(object): _SELECTORS = { 'firstrun': "#wrapper", - 'qrCode': ".qrcode > img:nth-child(4)", + 'qrCode': "img[alt=\"Scan me !\"]", 'mainPage': ".app.two", 'chatList': ".infinite-list-viewport", 'messageList': "#main > div > div:nth-child(1) > div > div.message-list",
Fix qrCode css selector QRCode css selector changed to search for its alt text rather than searching almost randomly.
mukulhase_WebWhatsapp-Wrapper
train
py
ca00fbc4c51e20c3f702d20091e1fcda8a9ef913
diff --git a/test/test.py b/test/test.py index <HASH>..<HASH> 100755 --- a/test/test.py +++ b/test/test.py @@ -36,10 +36,9 @@ from pandocxnos import insert_secnos_factory from pandocxnos import repair_refs, process_refs_factory, replace_refs_factory PANDOCVERSION = '2.8.1' -PANDOC = 'pandoc-2.9.2.1' +PANDOC = 'pandoc-2.10.1' PANDOC1p15 = 'pandoc-1.15.2' # pylint: disable=invalid-name - -PANDOC_API_VERSION = '1,20' +PANDOC_API_VERSION = '1,21' #-----------------------------------------------------------------------------
Updated for pandoc-<I>.
tomduck_pandoc-xnos
train
py
ea4599f1d0daf6c8697c6bcecd429998a013b986
diff --git a/GPy/kern/constructors.py b/GPy/kern/constructors.py index <HASH>..<HASH> 100644 --- a/GPy/kern/constructors.py +++ b/GPy/kern/constructors.py @@ -5,6 +5,23 @@ import numpy as np from kern import kern import parts + +def rbf_inv(input_dim,variance=1., inv_lengthscale=None,ARD=False): + """ + Construct an RBF kernel + + :param input_dim: dimensionality of the kernel, obligatory + :type input_dim: int + :param variance: the variance of the kernel + :type variance: float + :param lengthscale: the lengthscale of the kernel + :type lengthscale: float + :param ARD: Auto Relevance Determination (one lengthscale per dimension) + :type ARD: Boolean + """ + part = parts.rbf_inv.RBFInv(input_dim,variance,inv_lengthscale,ARD) + return kern(input_dim, [part]) + def rbf(input_dim,variance=1., lengthscale=None,ARD=False): """ Construct an RBF kernel diff --git a/GPy/kern/parts/__init__.py b/GPy/kern/parts/__init__.py index <HASH>..<HASH> 100644 --- a/GPy/kern/parts/__init__.py +++ b/GPy/kern/parts/__init__.py @@ -20,3 +20,4 @@ import spline import symmetric import white import hierarchical +import rbf_inv
Added rbf_inv.py kernel which is parametrised with the variances
SheffieldML_GPy
train
py,py
86b650a9a8dbe0bf2759181cb43019c0e2b92f3b
diff --git a/color.js b/color.js index <HASH>..<HASH> 100644 --- a/color.js +++ b/color.js @@ -301,9 +301,11 @@ if (!net.brehaut) { net.brehaut = {}; } }, function ( css ) { - if (css in css_colors) { - css = css_colors[css.toLowerCase()]; + var lower = css.toLowerCase(); + if (lower in css_colors) { + css = css_colors[lower]; } + css = css.replace(/^#/,''); if (css.length === 0 ||
CSS color names are not case-sensitive any more
brehaut_color-js
train
js
f19760a63b66746b50157768fca57a66845dbf37
diff --git a/src/Textfield.js b/src/Textfield.js index <HASH>..<HASH> 100644 --- a/src/Textfield.js +++ b/src/Textfield.js @@ -64,7 +64,7 @@ class Textfield extends React.Component { const { className, inputClassName, id, error, expandable, expandableIcon, floatingLabel, label, maxRows, - rows, style, ...otherProps } = this.props; + rows, style, children, ...otherProps } = this.props; const hasRows = !!rows; const customId = id || `textfield-${label.replace(/[^a-z0-9]/gi, '')}`; @@ -97,12 +97,14 @@ class Textfield extends React.Component { {labelContainer} {errorContainer} </div> + {children} </div> ) : ( <div className={containerClasses} style={style}> {input} {labelContainer} {errorContainer} + {children} </div> ); }
feat(Textfield): Render `children` as last element to ease customization of the Textfield by client code. (#<I>) SEE Make Textfield render children #<I>
tleunen_react-mdl
train
js
ce0341e984a98bc4b15a309f631d3f513c7b773a
diff --git a/alot/account.py b/alot/account.py index <HASH>..<HASH> 100644 --- a/alot/account.py +++ b/alot/account.py @@ -161,7 +161,8 @@ class Account(object): :param mail: the mail to send :type mail: :class:`email.message.Message` or string - :raises: :class:`alot.account.SendingMailFailed` if an error occured + :returns: a `Deferred` that errs back with a class:`SendingMailFailed`, + containing a reason string if an error occured. """ return 'not implemented'
adjust docstring for Account.send_mail mention the returned Deferred
pazz_alot
train
py
2fc53d8f9c811fffcc8e5e16f45b45bafb8c005b
diff --git a/src/Concerns/MakesHttpRequests.php b/src/Concerns/MakesHttpRequests.php index <HASH>..<HASH> 100644 --- a/src/Concerns/MakesHttpRequests.php +++ b/src/Concerns/MakesHttpRequests.php @@ -376,7 +376,7 @@ trait MakesHttpRequests } if (! Str::startsWith($uri, 'http')) { - $uri = config('app.url').'/'.$uri; + $uri = $this->baseUrl.'/'.$uri; } return trim($uri, '/');
use configured baseUrl instead of app url
albertcht_lumen-testing
train
php
6d466b4445ec7201e3c9216fafff0853779c3095
diff --git a/lib/crash_log/configuration.rb b/lib/crash_log/configuration.rb index <HASH>..<HASH> 100644 --- a/lib/crash_log/configuration.rb +++ b/lib/crash_log/configuration.rb @@ -1,5 +1,6 @@ require 'hashr' require 'multi_json' +require 'logger' module CrashLog class Configuration < Hashr
Ensure we've loaded Logger in config
crashlog_crashlog
train
rb
72ea22088056fd50dd9cd1f55c17716fbbca9cb7
diff --git a/rapidoid-integration-tests/src/test/java/org/rapidoid/http/HttpLoginTest.java b/rapidoid-integration-tests/src/test/java/org/rapidoid/http/HttpLoginTest.java index <HASH>..<HASH> 100644 --- a/rapidoid-integration-tests/src/test/java/org/rapidoid/http/HttpLoginTest.java +++ b/rapidoid-integration-tests/src/test/java/org/rapidoid/http/HttpLoginTest.java @@ -26,6 +26,8 @@ import org.rapidoid.annotation.Since; import org.rapidoid.commons.Err; import org.rapidoid.commons.Rnd; import org.rapidoid.ctx.Contextual; +import org.rapidoid.log.Log; +import org.rapidoid.log.LogLevel; import org.rapidoid.security.Role; import org.rapidoid.setup.On; import org.rapidoid.u.U; @@ -37,10 +39,12 @@ import java.util.List; @Since("5.1.0") public class HttpLoginTest extends IsolatedIntegrationTest { - volatile boolean ready = false; + private volatile boolean ready = false; @Test public void testLogin() { + Log.setLogLevel(LogLevel.ERROR); + On.get("/user").json(() -> U.list(Contextual.username(), Contextual.roles())); On.get("/profile").roles(Role.LOGGED_IN).json(Contextual::username);
Hide the warnings for the failed HTTP logins in HttpLoginTest.
rapidoid_rapidoid
train
java
7ad2ce628af039016b99e3d9a43f92df59e441af
diff --git a/src/measurement/position_measurement.js b/src/measurement/position_measurement.js index <HASH>..<HASH> 100644 --- a/src/measurement/position_measurement.js +++ b/src/measurement/position_measurement.js @@ -427,7 +427,7 @@ export function coordsChar(cm, x, y) { function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { let measure = ch => intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, ch), "line") let end = lineObj.text.length - let begin = findFirst(ch => measure(ch).bottom <= y, end - 1, 0) + 1 + let begin = findFirst(ch => measure(ch - 1).bottom <= y, end, 0) end = findFirst(ch => measure(ch).top > y, begin, end) return {begin, end} } @@ -450,7 +450,7 @@ function coordsCharInner(cm, lineObj, lineNo, x, y) { prevDiff = diff let prevPos = pos pos = moveVisually(cm, lineObj, pos, dir) - if (pos == null || pos.ch < begin || end <= pos.ch) { + if (pos == null || pos.ch < begin || end <= (pos.sticky == "before" ? pos.ch - 1 : pos.ch)) { pos = prevPos break }
Fix coordsChar at end and beginning of wrapped bidi lines
codemirror_CodeMirror
train
js
9fad1d9fd8022fca1e945cad02a4e258be644d5e
diff --git a/visidata/vdtui/__init__.py b/visidata/vdtui/__init__.py index <HASH>..<HASH> 100755 --- a/visidata/vdtui/__init__.py +++ b/visidata/vdtui/__init__.py @@ -435,7 +435,7 @@ class Extensible: def global_api(cls, func): setattr(cls, func.__name__, func) def _vdfunc(*args, **kwargs): - return func(vd, *args, **kwargs) + return getattr(vd, func.__name__)(*args, **kwargs) # getattr in case of replacement return _vdfunc @classmethod
[api] global_api global func calls VisiData peer by name, to allow for patching
saulpw_visidata
train
py
25addb7f7447aea08407dbe484b2b02c0a0a6135
diff --git a/ui/src/dashboards/constants/index.js b/ui/src/dashboards/constants/index.js index <HASH>..<HASH> 100644 --- a/ui/src/dashboards/constants/index.js +++ b/ui/src/dashboards/constants/index.js @@ -26,23 +26,23 @@ export const NEW_DEFAULT_DASHBOARD_CELL = { } const getMostCommonValue = values => { - const distribution = {} - let max = 0 - let result = 0 - - values.forEach(value => { - distribution[value] = (distribution[value] || 0) + 1 - if (distribution[value] > max) { - max = distribution[value] - result = [value] - return - } - if (distribution[value] === max) { - result.push(value) - } - }) + const results = values.reduce( + (acc, value) => { + const {distribution, mostCommonCount} = acc + distribution[value] = (distribution[value] || 0) + 1 + if (distribution[value] > mostCommonCount) { + return { + distribution, + mostCommonCount: distribution[value], + mostCommonValue: value, + } + } + return acc + }, + {distribution: {}, mostCommonCount: 0} + ) - return result[0] + return results.mostCommonValue } export const generateNewDashboardCell = dashboard => {
Use Iris' improved approach for determine most common cell sizes
influxdata_influxdb
train
js
4a2a06270cfd5b956dd5bf70e0c80fa230917615
diff --git a/py3status/modules/do_not_disturb.py b/py3status/modules/do_not_disturb.py index <HASH>..<HASH> 100644 --- a/py3status/modules/do_not_disturb.py +++ b/py3status/modules/do_not_disturb.py @@ -87,7 +87,7 @@ class Py3status: self.is_on = not self.is_on if self._is_dunst(): new_flag = "--signal {}".format(self.dunst_signal_on - if self.is_on else self.dunst_signal_off) + if self.is_on else self.dunst_signal_off) system("killall {} dunst".format(new_flag)) else: if self.is_on:
Revise indentation to make flake8 happy
ultrabug_py3status
train
py
ada08f876633417a4f1087928f16649364b5a276
diff --git a/satpy/tests/reader_tests/test_nucaps.py b/satpy/tests/reader_tests/test_nucaps.py index <HASH>..<HASH> 100644 --- a/satpy/tests/reader_tests/test_nucaps.py +++ b/satpy/tests/reader_tests/test_nucaps.py @@ -60,7 +60,7 @@ class FakeNetCDF4FileHandler2(FakeNetCDF4FileHandler): """Mimic reader input file content.""" file_content = { '/attr/time_coverage_start': filename_info['start_time'].strftime('%Y-%m-%dT%H:%M:%S.%fZ'), - '/attr/time_coverage_end': filename_info['end_time'].strftime('%Y-%m-%dT%H:%M:%S.%fZ'), + '/attr/time_coverage_end': filename_info['end_time'].strftime('%Y-%m-%dT%H:%M:%SZ'), '/attr/start_orbit_number': 1, '/attr/end_orbit_number': 2, '/attr/platform_name': 'NPP',
Add a test for alternate form of date found in <I> files, using end_time to perform that test while keeping original format for start_time test.
pytroll_satpy
train
py
31b8d423b4bde96f0590553071185a99cf412ec8
diff --git a/i3pystatus/openstack_vms.py b/i3pystatus/openstack_vms.py index <HASH>..<HASH> 100644 --- a/i3pystatus/openstack_vms.py +++ b/i3pystatus/openstack_vms.py @@ -17,12 +17,10 @@ class Openstack_vms(IntervalModule): ("username", "Username for OpenStack authentication (OS_USERNAME)"), ("password", "Password for Openstack authentication (OS_PASSWORD)"), ("tenant_name", "Tenant/Project name to view (OS_TENANT_NAME)"), - ("color", "Display color when non-active VMs are =< `threshold` " - "(default: #00FF00"), - ("crit_color", "Display color when non-active VMs are => `threshold` " - "(default: #FF0000"), + ("color", "Display color when non-active VMs are =< `threshold`"), + ("crit_color", "Display color when non-active VMs are => `threshold`"). ("threshold", "Set critical indicators when non-active VM pass this " - "number (default: 0)"), + "number"), ("horizon_url", "When clicked, open this URL in a browser") ) required = ("auth_url", "password", "tenant_name", "username")
Remove defaults documentation, as they are auto-gen
enkore_i3pystatus
train
py
f017d286e47bfa529cec41a0fbc96c51efa116b6
diff --git a/src/post.js b/src/post.js index <HASH>..<HASH> 100644 --- a/src/post.js +++ b/src/post.js @@ -106,7 +106,7 @@ return function () if (line == "quit") { process.exit(); } - stockfish.postMessage(line); + stockfish.postMessage(line, true); } });
Don't delay for command line either.
nmrugg_stockfish.js
train
js
ca006a677bc8ba58b0624e85b35c074c23798ca6
diff --git a/app/components/ninetails/section.rb b/app/components/ninetails/section.rb index <HASH>..<HASH> 100644 --- a/app/components/ninetails/section.rb +++ b/app/components/ninetails/section.rb @@ -5,7 +5,10 @@ module Ninetails attr_accessor :elements_instances def self.new_from_filename(filename) - name = File.basename(filename, ".rb") + new_from_name File.basename(filename, ".rb") + end + + def self.new_from_name(name) "Section::#{name.camelize}".safe_constantize.new end diff --git a/app/controllers/ninetails/sections_controller.rb b/app/controllers/ninetails/sections_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/ninetails/sections_controller.rb +++ b/app/controllers/ninetails/sections_controller.rb @@ -10,7 +10,7 @@ module Ninetails end def show - render json: empty_section_from_name(params[:id]) + render json: Section.new_from_name(params[:id]).serialize end def validate
Split new_from_filename into two methods One that handles converting a lowercase name to an instance of the class. Another that converts a full filename and then uses the formentioned method.
iZettle_ninetails
train
rb,rb
e423f7d4ba3af0b8382dc6b45fbcac5f5bb996b8
diff --git a/maildump/static/js/maildump.js b/maildump/static/js/maildump.js index <HASH>..<HASH> 100644 --- a/maildump/static/js/maildump.js +++ b/maildump/static/js/maildump.js @@ -4,6 +4,9 @@ $(document).ready(function() { // Misc stuff and initialization $('.resizer').on('mousedown', function(e) { + if(e.button != 0) { + return; + } var $this = $(this); var target = $this.data('sibling') == 'prev' ? $this.prev() : $this.next(); e.preventDefault();
Only allow resizing with the left mouse button
ThiefMaster_maildump
train
js
3282fece4a7f343bb383be6cbb3e81c62ab26808
diff --git a/meshio/h5m_io.py b/meshio/h5m_io.py index <HASH>..<HASH> 100644 --- a/meshio/h5m_io.py +++ b/meshio/h5m_io.py @@ -44,16 +44,17 @@ def read(filename): 'Tet4': 'tetra' } cells = {} + cell_data = {} for h5m_type, data in dset['elements'].iteritems(): meshio_type = h5m_to_meshio_type[h5m_type] conn = data['connectivity'] # Note that the indices are off by 1 in h5m. cells[meshio_type] = conn[()] - 1 - cell_data = {} - if 'tags' in data: - for name, dataset in data['tags'].items(): - cell_data[name] = dataset[()] + # TODO bring cell data back + # if 'tags' in data: + # for name, dataset in data['tags'].items(): + # cell_data[name] = dataset[()] # The `sets` in H5M are special in that they represent a segration of data # in the current file, particularly by a load balancer (Metis, Zoltan,
h5m: don't read cell data for now
nschloe_meshio
train
py
cfdcca113298578a3c20d69c98739e38578a47da
diff --git a/promptly/inputs.py b/promptly/inputs.py index <HASH>..<HASH> 100644 --- a/promptly/inputs.py +++ b/promptly/inputs.py @@ -120,11 +120,11 @@ class ChoiceInput(BaseInput): return prompt def process_data(self, data): - try: - self.value = int(data) - except ValueError: - self.value = None - raise + + if not [x for x in choices if str(x[0]) == data]: + raise ValueError + + self.value = data diff --git a/tests/test_promptly.py b/tests/test_promptly.py index <HASH>..<HASH> 100644 --- a/tests/test_promptly.py +++ b/tests/test_promptly.py @@ -28,6 +28,7 @@ class TestPromptly(unittest.TestCase): form.prompt() values = form.values() + for v in values: print(v)
fixed issue with BooleanInput
aventurella_promptly
train
py,py
b9e4caa37275654cbafc59e22aeac0e2c98b017c
diff --git a/xhtml2pdf/document.py b/xhtml2pdf/document.py index <HASH>..<HASH> 100644 --- a/xhtml2pdf/document.py +++ b/xhtml2pdf/document.py @@ -74,16 +74,22 @@ def pisaStory(src, path=None, link_callback=None, debug=0, default_css=None, def pisaDocument(src, dest=None, path=None, link_callback=None, debug=0, default_css=None, xhtml=False, encoding=None, xml_output=None, - raise_exception=True, capacity=100 * 1024, **kw): - log.debug("pisaDocument options:\n src = %r\n dest = %r\n path = %r\n link_callback = %r\n xhtml = %r", + raise_exception=True, capacity=100 * 1024, context_meta=None, + **kw): + log.debug("pisaDocument options:\n src = %r\n dest = %r\n path = %r\n link_callback = %r\n xhtml = %r\n context_meta = %r", src, dest, path, link_callback, - xhtml) + xhtml, + context_meta) # Prepare simple context context = pisaContext(path, debug=debug, capacity=capacity) + + if context_meta is not None: + context.meta.update(context_meta) + context.pathCallback = link_callback # Build story
Add optional pisaDocument argument to set metadata Without this the functionality of pisaDocument would need to be recreated in order to set metadata such as the document author.
xhtml2pdf_xhtml2pdf
train
py
cd0a96381c501638b2ffecce12fd511a562b1a32
diff --git a/test/helper/Appium_test.js b/test/helper/Appium_test.js index <HASH>..<HASH> 100644 --- a/test/helper/Appium_test.js +++ b/test/helper/Appium_test.js @@ -14,6 +14,7 @@ describe('Appium', function () { this.timeout(0); before(() => { + global.codecept_dir = path.join(__dirname, '/../data'); app = new Appium({ app: apk_path, desiredCapabilities: { @@ -584,15 +585,15 @@ describe('Appium', function () { }); }); - describe('#saveScreenshot', () => { + describe('#saveScreenshot @quick', () => { beforeEach(() => { global.output_dir = path.join(global.codecept_dir, 'output'); }); it('should create a screenshot file in output dir', async () => { const sec = (new Date()).getUTCMilliseconds(); - await app.saveScreenshot(`screenshot_${sec}`); - assert.ok(fileExists(path.join(output_dir, `screenshot_${sec}`)), null, 'file does not exists'); + await app.saveScreenshot(`screenshot_${sec}.png`); + assert.ok(fileExists(path.join(global.output_dir, `screenshot_${sec}.png`)), null, 'file does not exists'); }); });
re-enabled saveScreenshot for Appium tests
Codeception_CodeceptJS
train
js
fbd1a82d47fff935dcb0b5cc5e8b33fa77b5d9a7
diff --git a/lib/containers.js b/lib/containers.js index <HASH>..<HASH> 100644 --- a/lib/containers.js +++ b/lib/containers.js @@ -27,9 +27,10 @@ var defaultDefinitions = [{ }, { 'require': 'process-container', 'type': 'process' -}, { - 'require': 'process-monitor-container', - 'type': 'processmonitor' +// TODO re-enable +//}, { +// 'require': 'process-monitor-container', +// 'type': 'processmonitor' }, { 'require': 'aws-elb-container', 'type': 'aws-elb'
Commented process-monitor-container require in containers.
nearform_nscale-kernel
train
js
dc8cdd260cb59cf00b1588e1b7b68d691d075649
diff --git a/command/apply_destroy_test.go b/command/apply_destroy_test.go index <HASH>..<HASH> 100644 --- a/command/apply_destroy_test.go +++ b/command/apply_destroy_test.go @@ -195,7 +195,7 @@ func TestApply_destroyTargeted(t *testing.T) { Mode: addrs.ManagedResourceMode, Type: "test_instance", Name: "foo", - }.Instance(addrs.NoKey).Absolute(addrs.RootModuleInstance), + }.Instance(addrs.IntKey(0)).Absolute(addrs.RootModuleInstance), &states.ResourceInstanceObjectSrc{ AttrsJSON: []byte(`{"id":"i-ab123"}`), Status: states.ObjectReady, @@ -212,8 +212,9 @@ func TestApply_destroyTargeted(t *testing.T) { Name: "foo", }.Instance(addrs.NoKey).Absolute(addrs.RootModuleInstance), &states.ResourceInstanceObjectSrc{ - AttrsJSON: []byte(`{"id":"i-abc123"}`), - Status: states.ObjectReady, + AttrsJSON: []byte(`{"id":"i-abc123"}`), + Dependencies: []addrs.AbsResource{mustResourceAddr("test_instance.foo")}, + Status: states.ObjectReady, }, addrs.AbsProviderConfig{ Provider: addrs.NewLegacyProvider("test"),
add missing deps to targeted destroy test
hashicorp_terraform
train
go
448e1196513825e30c350edc011993dc2e73b16a
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,10 +1,10 @@ +S3 = require('AWS').S3; + Upload = (awsBucketName, options) { - this.aws = null; // initial aws connection - - this.awsBucketName = awsBucketName; - - // Set default options - this.path = options.path || '/images'; + this.s3 = new S3({ params: { Bucket: awsBucketName } }); + + // Set options + this.path = options.path || '/'; this.url = options.url || null; this.sizes = options.sizes || [780, 320]; this.keepOriginal = options.keepOriginal || true; // @TODO this won't work
Init S3 bucket on new class instance
Turistforeningen_node-s3-uploader
train
js
e6cc2649b21f23f149073102800d786c97cb1399
diff --git a/src/utils/source.js b/src/utils/source.js index <HASH>..<HASH> 100644 --- a/src/utils/source.js +++ b/src/utils/source.js @@ -280,6 +280,23 @@ function getMode(source: Source, sourceMetaData: SourceMetaDataType) { return "jsx"; } + const languageMimeMap = [ + { ext: ".c", mode: "text/x-csrc" }, + { ext: ".kt", mode: "text/x-kotlin" }, + { ext: ".cpp", mode: "text/x-c++src" }, + { ext: ".m", mode: "text/x-objectivec" }, + { ext: ".rs", mode: "text/x-rustsrc" } + ]; + + // check for C and other non JS languages + if (url) { + const result = languageMimeMap.find(({ ext }) => url.endsWith(ext)); + + if (result !== undefined) { + return result.mode; + } + } + // if the url ends with .marko we set the name to Javascript so // syntax highlighting works for marko too if (url && url.match(/\.marko$/i)) {
Add non-js languages (#<I>)
firefox-devtools_debugger
train
js
129b561a1b12be3d8c77edbe1cd2bec58539ac05
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -40,6 +40,7 @@ module.exports = function(app, dcPath) { '-f', dcFile, 'run', + '--service-ports', app, cmd ].join(' ');
[#1] add service ports option to the command
markbirbeck_docker-compose-run
train
js
20d58f78a70a1a45bb2be03bdbc2b841d2b00656
diff --git a/loadCSS.js b/loadCSS.js index <HASH>..<HASH> 100644 --- a/loadCSS.js +++ b/loadCSS.js @@ -31,21 +31,17 @@ function loadCSS( href, before, media, callback ){ // This function sets the link's media back to `all` so that the stylesheet applies once it loads // It is designed to poll until document.styleSheets includes the new sheet. ss.onloadcssdefined = function( cb ){ - var defined; var i = sheets.length; while( i-- ){ if( sheets[ i ].href && sheets[ i ].href === ss.href ){ - defined = true; - break; + cb(); + return; } } - if( defined ){ - cb(); - } else { - setTimeout(function() { - ss.onloadcssdefined( cb ); - }); - } + // Try again later + setTimeout(function() { + ss.onloadcssdefined( cb ); + }); }; ss.onloadcssdefined(function() { ss.media = media || "all";
optimise: Simplify by returning early from the loop
filamentgroup_loadCSS
train
js
a293f37ca5a230e09f2ef3a88a99ee10ad9d04b6
diff --git a/app/templates/_keystone.js b/app/templates/_keystone.js index <HASH>..<HASH> 100644 --- a/app/templates/_keystone.js +++ b/app/templates/_keystone.js @@ -14,7 +14,6 @@ var Twig = require('twig');<% } %> // and documentation. <% } %> keystone.init({ - 'name': '<%= projectName %>', 'brand': '<%= projectName %>', <% if (preprocessor === 'sass') { %> @@ -39,8 +38,8 @@ keystone.init({ extname: '.hbs', }).engine, <% } else if (viewEngine == 'twig') { %> - 'twig options':{ method: 'fs' }, - 'custom engine':Twig.render, + 'twig options': { method: 'fs' }, + 'custom engine': Twig.render, <% } %><% if (includeEmail) { %> 'emails': 'templates/emails', <% } %> @@ -48,7 +47,6 @@ keystone.init({ 'session': true, 'auth': true, 'user model': '<%= userModel %>', - }); <% if (includeGuideComments) { %> // Load your project's Models
Fixing lint errors in generated code
keystonejs_generator-keystone
train
js
c0567986c13df54ac838ff78483d18fedddbb4fc
diff --git a/src/Extend/Item.php b/src/Extend/Item.php index <HASH>..<HASH> 100644 --- a/src/Extend/Item.php +++ b/src/Extend/Item.php @@ -35,7 +35,7 @@ class Item extends CommonItem implements ItemInterface */ public function getProductRecord() { - return $this->getParameter('product_code'); + return $this->getParameter('productCode'); } /** @@ -43,6 +43,6 @@ class Item extends CommonItem implements ItemInterface */ public function setProductCode($value) { - return $this->setParameter('product_code', $value); + return $this->setParameter('productCode', $value); } }
Issue #<I> - refactored to camel case for product code
thephpleague_omnipay-sagepay
train
php
68b81078c7718bbf0a083e77b6da658c900b15d4
diff --git a/tests/unit/framework/db/ActiveRecordTest.php b/tests/unit/framework/db/ActiveRecordTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/framework/db/ActiveRecordTest.php +++ b/tests/unit/framework/db/ActiveRecordTest.php @@ -426,7 +426,16 @@ class ActiveRecordTest extends DatabaseTestCase $this->assertEquals(1, $customers[1]->id); $this->assertTrue($customers[0]->isRelationPopulated('orders')); $this->assertTrue($customers[1]->isRelationPopulated('orders')); + } + /** + * This query will do the same join twice, ensure duplicated JOIN gets removed + * https://github.com/yiisoft/yii2/pull/2650 + */ + public function testJoinWithVia() + { + Order::getDb()->getQueryBuilder()->separator = "\n"; + Order::find()->joinWith('itemsInOrder1')->joinWith('items')->all(); } public function testInverseOf()
removed duplicated joins when using joinWith and via relations fixes #<I>
yiisoft_yii-core
train
php
f7d248505a73b9e8405f80dd7eb03d4e2ff8ec0b
diff --git a/eZ/Publish/Core/REST/Server/Controller/Content.php b/eZ/Publish/Core/REST/Server/Controller/Content.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/Core/REST/Server/Controller/Content.php +++ b/eZ/Publish/Core/REST/Server/Controller/Content.php @@ -67,7 +67,13 @@ class Content extends RestController public function loadContent( $contentId ) { $contentInfo = $this->repository->getContentService()->loadContentInfo( $contentId ); - $mainLocation = $this->repository->getLocationService()->loadLocation( $contentInfo->mainLocationId ); + + $mainLocation = null; + if ( !empty( $contentInfo->mainLocationId ) ) + { + $mainLocation = $this->repository->getLocationService()->loadLocation( $contentInfo->mainLocationId ); + } + $contentType = $this->repository->getContentTypeService()->loadContentType( $contentInfo->contentTypeId ); $contentVersion = null;
Fix for EZP-<I>: REST API: GET Content request fails when the content has not been published.
ezsystems_ezpublish-kernel
train
php
419d499005414304e88019106443dfe4b0a8806a
diff --git a/mtools/mlaunch/mlaunch.py b/mtools/mlaunch/mlaunch.py index <HASH>..<HASH> 100755 --- a/mtools/mlaunch/mlaunch.py +++ b/mtools/mlaunch/mlaunch.py @@ -994,7 +994,7 @@ class MLaunchTool(BaseCmdLineTool): self.wait_for(ports) - def _initiate_replset(self, port, name): + def _initiate_replset(self, port, name, maxwait=30): # initiate replica set if not self.args['replicaset']: return @@ -1003,7 +1003,15 @@ class MLaunchTool(BaseCmdLineTool): try: rs_status = con['admin'].command({'replSetGetStatus': 1}) except OperationFailure, e: - con['admin'].command({'replSetInitiate':self.config_docs[name]}) + # not initiated yet + for i in range(maxwait): + try: + con['admin'].command({'replSetInitiate':self.config_docs[name]}) + break + except OperationFailure, e: + print e.message, " - will retry" + time.sleep(1) + if self.args['verbose']: print "initializing replica set '%s' with configuration: %s" % (name, self.config_docs[name]) print "replica set '%s' initialized." % name
introduced <I>sec delay in last commit. now correctly breaks if replset is configured.
rueckstiess_mtools
train
py
9eb52cbc7e1155277f1c5025f2ffdb1bd65674a9
diff --git a/pkg/policy/api/fqdn.go b/pkg/policy/api/fqdn.go index <HASH>..<HASH> 100644 --- a/pkg/policy/api/fqdn.go +++ b/pkg/policy/api/fqdn.go @@ -54,6 +54,10 @@ type FQDNSelector struct { MatchPattern string `json:"matchPattern,omitempty"` } +func (s *FQDNSelector) String() string { + return fmt.Sprintf("MatchName: %s, MatchPattern %s", s.MatchName, s.MatchPattern) +} + // sanitize for FQDNSelector is a little wonky. While we do more processing // when using MatchName the basic requirement is that is a valid regexp. We // test that it can compile here.
policy API: add String() function for FQDNSelector Similar to the EndpointSelector, this allows for storing the string representation of an FQDNSelector as a map key in the SelectorCache.
cilium_cilium
train
go
9e28841e2de1386704fdec1c4a098238610d8ff5
diff --git a/mime.js b/mime.js index <HASH>..<HASH> 100644 --- a/mime.js +++ b/mime.js @@ -118,12 +118,14 @@ MIME.prototype = { * @return {String} */ encodeBase64: function( input, charset ) { - if( Buffer.isBuffer( input ) ) { - return input.toString( 'base64' ) - } else { + if( charset ) { return new MIME.Iconv( charset, 'UTF8//TRANSLIT//IGNORE' ) .convert( input ) .toString( 'base64' ) + } else { + return Buffer.isBuffer( input ) + ? input.toString( 'base64' ) + : new Buffer( input ).toString( 'base64' ) } }, @@ -136,7 +138,7 @@ MIME.prototype = { */ decodeBase64: function( input, charset ) { if( charset ) { - return new Iconv( 'UTF8', charset + '//TRANSLIT//IGNORE' ) + return new MIME.Iconv( 'UTF8', charset + '//TRANSLIT//IGNORE' ) .convert( new Buffer( input, 'base64' ) ) } else { return new Buffer( input, 'base64' )
Updated mime.js: Added iconv to base<I> en/decoding
jhermsmeier_node-mime-lib
train
js
76a88f2211890d4ddce27981f5139fc0950ce28a
diff --git a/src/Symfony/Component/Security/Http/LoginLink/ExpiredLoginLinkStorage.php b/src/Symfony/Component/Security/Http/LoginLink/ExpiredLoginLinkStorage.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Security/Http/LoginLink/ExpiredLoginLinkStorage.php +++ b/src/Symfony/Component/Security/Http/LoginLink/ExpiredLoginLinkStorage.php @@ -14,6 +14,8 @@ namespace Symfony\Component\Security\Http\LoginLink; use Psr\Cache\CacheItemPoolInterface; /** + * @experimental in 5.2 + * * @final */ class ExpiredLoginLinkStorage
[Security] Mark ExpiredLoginLinkStorage as experimental
symfony_symfony
train
php
5815383ddb4921e4f29008a4e687dfc3856c81ff
diff --git a/tests/test_vincent.py b/tests/test_vincent.py index <HASH>..<HASH> 100644 --- a/tests/test_vincent.py +++ b/tests/test_vincent.py @@ -206,12 +206,13 @@ class TestVincent(object): for cls in test_classes: vis1 = cls() vis2 = cls() - vis3 = cls() assert_vega_equal(vis1, vis2) - assert_vega_equal(vis2, vis3) vis1 += ([0, 1], 'scales', 0, 'range') vis3 = vis2 + ([0, 1], 'scales', 0, 'range') assert_vega_equal(vis1, vis3) + vis1 -= ('domain', 'scales', 0) + vis4 = vis3 - ('domain', 'scales', 0) + assert_vega_equal(vis1, vis4) def test_datetimeandserial(self): '''Test pandas serialization and datetime parsing''' diff --git a/vincent/vincent.py b/vincent/vincent.py index <HASH>..<HASH> 100644 --- a/vincent/vincent.py +++ b/vincent/vincent.py @@ -87,7 +87,7 @@ class Vega(object): def __sub__(self, tuple): '''Allow for updating of Vega with sub operator''' vis = deepcopy(self) - vis.update_component('add', *tuple) + vis.update_component('remove', *tuple) return vis def __isub__(self, tuple):
BUG: __sub__ added instead of removed - fixes <I>
wrobstory_vincent
train
py,py
53c8510c02e72a4eaa0a7e41a4853da8af039c5b
diff --git a/chef/spec/unit/provider/user/pw_spec.rb b/chef/spec/unit/provider/user/pw_spec.rb index <HASH>..<HASH> 100644 --- a/chef/spec/unit/provider/user/pw_spec.rb +++ b/chef/spec/unit/provider/user/pw_spec.rb @@ -217,6 +217,9 @@ describe Chef::Provider::User::Pw do end describe "when loading the current state" do + before do + @provider.new_resource = Chef::Resource::User.new("adam") + end it "should raise an error if the required binary /usr/sbin/pw doesn't exist" do File.should_receive(:exists?).with("/usr/sbin/pw").and_return(false)
avoid libshadow check in User::Pw tests This fixes the case where there's a user named "adam" with "x" for the password field on the box running the tests
chef_chef
train
rb
1762952e17db56143adabc8091c6d1b6983b2fb8
diff --git a/framework/filter.js b/framework/filter.js index <HASH>..<HASH> 100644 --- a/framework/filter.js +++ b/framework/filter.js @@ -210,12 +210,16 @@ module.exports = Base.extend({ this.partitions.forEach(function (partition) { if ((partition.selected.length === 2) && (partition.isDatetime || partition.isContinuous)) { + if (partition.groupFixedS || partition.groupFixedSC) { + // scale down binsize + var newSize = partition.selected[1] - partition.selected[0]; + var oldSize = partition.maxval - partition.minval; + partition.groupingParam = partition.groupingParam * newSize / oldSize; + } // zoom to selected range, if possible partition.set({ minval: partition.selected[0], - maxval: partition.selected[1], - groupingParam: 20, - groupingContinuous: 'fixedn' + maxval: partition.selected[1] }, { silent: true }); partition.setGroups(); } else if (partition.selected.length > 0 && (partition.isCategorial)) {
Keep binning settings as consistent as possible on zooming in closes #<I>
NLeSC_spot
train
js
4de21bf5d560e7ac0e7c64689fc4c888f8239f08
diff --git a/src/Session.php b/src/Session.php index <HASH>..<HASH> 100644 --- a/src/Session.php +++ b/src/Session.php @@ -57,7 +57,7 @@ class Session extends Token { Toolkit::trace("SessionId from cookie: $sessionId"); } - $session = parent::getInstance($args, $conf, $confHash); + $session = parent::getInstance([$sessionId], $conf, $confHash); if (!$sessionId) { $action->setCookie( static::$_conf['cookie']['name'],
Session should pass sessionId not args to parent
x2ts_x2ts-session
train
php
0a1700b64a2e496217dd0531ebe8326410fd6cdc
diff --git a/salt/utils/yamldumper.py b/salt/utils/yamldumper.py index <HASH>..<HASH> 100644 --- a/salt/utils/yamldumper.py +++ b/salt/utils/yamldumper.py @@ -9,7 +9,7 @@ from __future__ import absolute_import try: from yaml import CDumper as Dumper except ImportError: - from yaml import CDumper as Dumper + from yaml import Dumper from salt.utils.odict import OrderedDict
Update yamldumper.py fixed wrong import
saltstack_salt
train
py
ae997a2315a6b676f2cba9b2a48d1360503512f8
diff --git a/pysc2/env/sc2_env.py b/pysc2/env/sc2_env.py index <HASH>..<HASH> 100644 --- a/pysc2/env/sc2_env.py +++ b/pysc2/env/sc2_env.py @@ -537,8 +537,10 @@ class SC2Env(environment.Base): return replay_path def close(self): - self._metrics.close() logging.info("Environment Close") + if hasattr(self, "_metrics") and self._metrics: + self._metrics.close() + self._metrics = None if hasattr(self, "_renderer_human") and self._renderer_human: self._renderer_human.close() self._renderer_human = None
Shut down cleanly even if the environment didn't finish the constructor. PiperOrigin-RevId: <I>
deepmind_pysc2
train
py
76e9dd18c1b3db15106b6ff4739b2d23bdb6399b
diff --git a/bigtext.js b/bigtext.js index <HASH>..<HASH> 100644 --- a/bigtext.js +++ b/bigtext.js @@ -51,6 +51,8 @@ if($.fn.smartresize) { // https://github.com/lrbabe/jquery-smartresize/ eventName = 'smartresize.' + eventName; + } else if(_.debounce) { + resizeFunction = _.debounce(resizeFunction, 200) } $(window).unbind(eventName).bind(eventName, resizeFunction); }
Add underscore resize debouncer
zachleat_BigText
train
js
15fff43b2cbe96dd10af2535ff9c7de9d3b05675
diff --git a/Config/Database.cfg.php b/Config/Database.cfg.php index <HASH>..<HASH> 100644 --- a/Config/Database.cfg.php +++ b/Config/Database.cfg.php @@ -14,7 +14,7 @@ class Database_Config_Framework { : "Gt_" . APPNAME; $this->_user = isset($this->_user) ? $this->_user - : "Gt_" . APPNAME . "_User"; + : "Gt_" . APPNAME; $this->_pass = isset($this->_pass) ? $this->_pass : "Gt_" . APPNAME . "_Pass";
Changed database username convention to drop the _User. Increased APPNAME to <I> char limit.
PhpGt_WebEngine
train
php
4916c8aef22b0d9641d4390882f12f18f751886c
diff --git a/lib/valid_email2/address.rb b/lib/valid_email2/address.rb index <HASH>..<HASH> 100644 --- a/lib/valid_email2/address.rb +++ b/lib/valid_email2/address.rb @@ -21,10 +21,8 @@ module ValidEmail2 return false if @parse_error if address.domain && address.address == @raw_address - tree = address.send(:tree) - # Valid address needs to have a dot in the domain - tree.domain.dot_atom_text.elements.size > 1 + !!address.domain.match(/\./) else false end
Count the dots in the domain without using the tree method Instead of using the private method #tree on the address to count the dots in the domain we simply match if there are any at all. This allows us to be compatible with the latest mail gem version which has deprecated the #tree.
micke_valid_email2
train
rb
3fb80b053de9eaf56902befaa9a69bf8683c5c05
diff --git a/agent/utils/mongo_fix/mongo_fix.go b/agent/utils/mongo_fix/mongo_fix.go index <HASH>..<HASH> 100644 --- a/agent/utils/mongo_fix/mongo_fix.go +++ b/agent/utils/mongo_fix/mongo_fix.go @@ -18,7 +18,6 @@ package mongo_fix import ( "net/url" - "github.com/pkg/errors" "go.mongodb.org/mongo-driver/mongo/options" ) @@ -30,7 +29,8 @@ func ClientOptionsForDSN(dsn string) (*options.ClientOptions, error) { // if username or password is set, need to replace it with correctly parsed credentials. parsedDsn, err := url.Parse(dsn) if err != nil { - return nil, errors.Wrap(err, "cannot parse DSN") + // for non-URI, do nothing (PMM-10265) + return clientOptions, nil } username := parsedDsn.User.Username() password, _ := parsedDsn.User.Password()
fallback to original DSN if it is non-URI (#<I>)
percona_pmm
train
go
4c4ba1953abac0a0b7e9c0f8c64aba7fa1f94234
diff --git a/lib/agent.js b/lib/agent.js index <HASH>..<HASH> 100644 --- a/lib/agent.js +++ b/lib/agent.js @@ -61,6 +61,8 @@ module.exports = { request: dispatchFromAgent('request'), stream: dispatchFromAgent('stream'), pipeline: dispatchFromAgent('pipeline'), + connect: dispatchFromAgent('connect'), + upgrade: dispatchFromAgent('upgrade'), setGlobalAgent, Agent }
feat: add connect and upgrade to global methods
mcollina_undici
train
js
4926341d909355013cec0c3d46e0de2be315a9e3
diff --git a/Services/Twilio/Rest/IncomingPhoneNumber.php b/Services/Twilio/Rest/IncomingPhoneNumber.php index <HASH>..<HASH> 100644 --- a/Services/Twilio/Rest/IncomingPhoneNumber.php +++ b/Services/Twilio/Rest/IncomingPhoneNumber.php @@ -81,6 +81,10 @@ * * The HTTP method Twilio will use when requesting the above URL. Either GET or POST. * + * .. php:attr:: beta + * + * Whether this number is new to Twilio's inventory. + * * .. php:attr:: uri * * The URI for this resource, relative to https://api.twilio.com.
Add beta property to IPN docs
twilio_twilio-php
train
php
038f593b2abaa83bc345912d710d043fc0bd54bd
diff --git a/code/model/EventRegistration.php b/code/model/EventRegistration.php index <HASH>..<HASH> 100644 --- a/code/model/EventRegistration.php +++ b/code/model/EventRegistration.php @@ -245,7 +245,7 @@ class EventRegistration extends DataObject { } public function isSubmitted() { - return ($this->Status != "Unsubmitted"); + return $this->Status && ($this->Status != "Unsubmitted"); } public function canPay() {
FIX: isSubmitted check on EventRegistration should also check if the Status value is set
registripe_registripe-core
train
php
556a77e3158bf7705c28f98ad9918d77b1b4a673
diff --git a/filesystems/common.py b/filesystems/common.py index <HASH>..<HASH> 100644 --- a/filesystems/common.py +++ b/filesystems/common.py @@ -54,7 +54,7 @@ def create( _state=attr.ib(default=attr.Factory(state), repr=False), create=create_file, - open=lambda fs, path, mode="rb": open_file( + open=lambda fs, path, mode="r": open_file( fs=fs, path=path, mode=mode, ), remove_file=remove_file,
Default open to mode "r" not "rb"
Julian_Filesystems
train
py
7f762cbcd657b0a8020113daa6357e63d3136912
diff --git a/lib/options.js b/lib/options.js index <HASH>..<HASH> 100644 --- a/lib/options.js +++ b/lib/options.js @@ -33,21 +33,14 @@ module.exports.parse = function (argv) { // Deprecated in 0.0.10 'flow-parser' ], - string: ['print-width', 'tab-width', 'parser', 'trailing-comma'], + string: ['parser', 'trailing-comma'], default: { semi: true, color: true, 'bracket-spacing': true, parser: 'babylon' }, - alias: { help: 'h', version: 'v', 'list-different': 'l' }, - unknown: function (param) { - if (param.startsWith('-')) { - console.warn('Ignored unknown option: ' + param + '\n'); - return false; - } - return true; - } + alias: { help: 'h', version: 'v', 'list-different': 'l' } }); return camelcaseKeys(parsed); };
Relax option parsing a bit Prettier does some extra validation and conversion, but let's just be lazy, skip the validation, and let minimist do the conversion.
josephfrazier_prettier_d
train
js
d8231024c39a16e9c5d68c841f4d68e60a216c87
diff --git a/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php b/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php index <HASH>..<HASH> 100644 --- a/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php +++ b/ModelDescriber/Annotations/SymfonyConstraintAnnotationReader.php @@ -88,6 +88,11 @@ class SymfonyConstraintAnnotationReader $property->maximum = (int) $annotation->value; } elseif ($annotation instanceof Assert\LessThanOrEqual) { $property->maximum = (int) $annotation->value; + } elseif ($annotation instanceof Assert\GreaterThan) { + $property->exclusiveMinimum = true; + $property->minimum = (int) $annotation->value; + } elseif ($annotation instanceof Assert\GreaterThanOrEqual) { + $property->minimum = (int) $annotation->value; } } }
feature: Add new validation from constraints. - Add minimum for GreaterThanOrEqual - add minimum and exclusiveMinimum LessThanOrEqual annotation
nelmio_NelmioApiDocBundle
train
php
04ca9d51ba483fd285020b07941845df7fa49e82
diff --git a/pkg/cmd/server/kubernetes/node_config.go b/pkg/cmd/server/kubernetes/node_config.go index <HASH>..<HASH> 100644 --- a/pkg/cmd/server/kubernetes/node_config.go +++ b/pkg/cmd/server/kubernetes/node_config.go @@ -176,12 +176,17 @@ func BuildKubernetesNodeConfig(options configapi.NodeConfig) (*NodeConfig, error // docker-in-docker (dind) deployments are used for testing // networking plugins. Running openshift under dind won't work // with the real oom adjuster due to the state of the cgroups path - // in a dind container that uses systemd for init. + // in a dind container that uses systemd for init. Similarly, + // cgroup manipulation of the nested docker daemon doesn't work + // properly under centos/rhel and should be disabled by setting + // the name of the container to an empty string. // - // TODO(marun) Make dind cgroups compatible with openshift + // This workaround should become unnecessary once user namespaces if value := cmdutil.Env("OPENSHIFT_DIND", ""); value == "true" { glog.Warningf("Using FakeOOMAdjuster for docker-in-docker compatibility") cfg.OOMAdjuster = oom.NewFakeOOMAdjuster() + glog.Warningf("Disabling cgroup manipulation of nested docker daemon for docker-in-docker compatibility") + cfg.DockerDaemonContainer = "" } // Setup auth
Fix dind compatibility with centos/rhel Kubelet's cgroup manipulation of the dind daemon is not compatible with centos/rhel. This change disables the offending cgroup manipulation when the kubelet is running with dind.
openshift_origin
train
go