hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
5af49852d19d7ce194f45d75cafaece08c3d1e7c
diff --git a/leaflet-search.js b/leaflet-search.js index <HASH>..<HASH> 100644 --- a/leaflet-search.js +++ b/leaflet-search.js @@ -18,6 +18,7 @@ L.Control.Search = L.Control.extend({ propFilter: 'title', //property of elements filtered initial: true, autoPan: false, //auto panTo when click on tooltip + animPan: false, //animation after panTo zoom: false //zoom after pan to location found, default: map.getZoom() }, @@ -27,7 +28,7 @@ L.Control.Search = L.Control.extend({ this.timersTime = 1200;//delay for autoclosing }, - onAdd: function (map) { + onAdd: function (e) { this._map = map; this._container = L.DomUtil.create('div', 'leaflet-control-search'); this._input = this._createInput(this.options.text, 'search-input'); @@ -160,8 +161,29 @@ L.Control.Search = L.Control.extend({ return alert; }, - _findLocation: function() { //pan to location if founded + _animLocation: function(latlng) { + var circle = new L.CircleMarker(latlng, {radius: 40, color: '#e03', fill:false}); + circle.addTo(map); + var tt = 100, + ss = 20, + mr = circle._radius/ss + f = 0; + + var ii = setInterval(function() { //animation + mr += f++; + if(circle._radius-mr > 5) + circle.setRadius(circle._radius-mr); + else + { + map.removeLayer(circle); + clearInterval(ii); + } + },tt); + }, + + _findLocation: function() { //pan to location if founded + if(this._input.style.display == 'none') { this.maximize(); @@ -177,7 +199,9 @@ L.Control.Search = L.Control.extend({ { //this._map.panTo(latlng); var z = this.options.zoom || this._map.getZoom(); - this._map.setView(latlng, z); + if(this.options.animPan) + this._animLocation(latlng); + this._map.setView(latlng, z); this.minimize(); } else
added animation after panning, added animPan option
stefanocudini_leaflet-search
train
1aaab00e071af129000da6cdfaa582bfc227225a
diff --git a/lib/reek/smells/duplicate_method_call.rb b/lib/reek/smells/duplicate_method_call.rb index <HASH>..<HASH> 100644 --- a/lib/reek/smells/duplicate_method_call.rb +++ b/lib/reek/smells/duplicate_method_call.rb @@ -78,7 +78,7 @@ module Reek method_ctx.local_nodes(:attrasgn) do |asgn_node| result[asgn_node].push(asgn_node) unless asgn_node.args.nil? end - result + result.to_a.sort_by {|call_exp, _| call_exp.format_ruby} end def allow_calls?(method) diff --git a/lib/reek/smells/uncommunicative_variable_name.rb b/lib/reek/smells/uncommunicative_variable_name.rb index <HASH>..<HASH> 100644 --- a/lib/reek/smells/uncommunicative_variable_name.rb +++ b/lib/reek/smells/uncommunicative_variable_name.rb @@ -74,7 +74,7 @@ module Reek result = Hash.new {|hash, key| hash[key] = []} find_assignment_variable_names(exp, result) find_block_argument_variable_names(exp, result) - result + result.to_a.sort_by {|name, _| name.to_s} end def find_assignment_variable_names(exp, accumulator) diff --git a/spec/matchers/smell_of_matcher.rb b/spec/matchers/smell_of_matcher.rb index <HASH>..<HASH> 100644 --- a/spec/matchers/smell_of_matcher.rb +++ b/spec/matchers/smell_of_matcher.rb @@ -16,28 +16,42 @@ module SmellOfMatcher def matches?(src) @source = src.to_reek_source + ctx = MethodContext.new(nil, @source.syntax_tree) detector = @klass.new(@source.desc, @klass.default_config.merge(@config)) detector.examine(ctx) actual_smells = detector.smells_found.to_a + if actual_smells.empty? @reason = 'no smells found by detector' return false end - return false if actual_smells.any? do |expected_smell| - @reason = "Found #{expected_smell.smell_class}/#{expected_smell.subclass}" && - expected_smell.smell_class != @klass::SMELL_CLASS && - expected_smell.subclass != @klass::SMELL_SUBCLASS + + actual_smells.each do |smell| + if smell.smell_class != @klass::SMELL_CLASS || + smell.subclass != @klass::SMELL_SUBCLASS + @reason = "Found #{smell.smell_class}/#{smell.subclass}" + return false + end + end + + expected_number_of_smells = @expected_smells.empty? ? 1 : @expected_smells.length + + if expected_number_of_smells != actual_smells.length + @reason = "expected #{expected_number_of_smells} smell(s), found #{actual_smells.length}" + return false end - return actual_smells.length == 1 if @expected_smells.empty? - return false unless @expected_smells.length == actual_smells.length - @expected_smells.each_with_index do |expected_smell,index| - expected_smell.each do |(key,value)| - if actual_smells[index].smell[key] != value - @reason = "#{key} != #{value}" + + @expected_smells.zip(actual_smells).each do |expected_smell, actual_smell| + expected_smell.each do |key, value| + actual_value = actual_smell.smell[key] + if actual_value != value + @reason = "expected #{key} to be #{value}, was #{actual_value}" + return false end end end + true end
Improve SmellOfMatcher This change improves SmellOfMatcher in the following ways: - Correctly report no match if smell properties do not match - Improve message when smell properties do not match - Clean up code to clearly show different ways matching may fail On Ruby <I>, this improved SmellOfMatcher revealed an implicit dependency on the hash key ordering being guaranteed: - Explicitely sort smells detected within a single context by DuplicateMethodCall and UncommunicativeModuleName
troessner_reek
train
56505fb62394c5723b02d48701f3bed251344a7d
diff --git a/decidim-proposals/app/events/decidim/proposals/admin/proposal_note_created_event.rb b/decidim-proposals/app/events/decidim/proposals/admin/proposal_note_created_event.rb index <HASH>..<HASH> 100644 --- a/decidim-proposals/app/events/decidim/proposals/admin/proposal_note_created_event.rb +++ b/decidim-proposals/app/events/decidim/proposals/admin/proposal_note_created_event.rb @@ -13,7 +13,7 @@ module Decidim end def admin_proposal_info_url - decidim_admin_participatory_process_proposals.proposal_url(resource, resource.component.mounted_params) + send(resource.component.mounted_admin_engine).proposal_url(resource, resource.component.mounted_params) end private diff --git a/decidim-proposals/spec/events/decidim/proposals/admin/proposal_note_created_event_spec.rb b/decidim-proposals/spec/events/decidim/proposals/admin/proposal_note_created_event_spec.rb index <HASH>..<HASH> 100644 --- a/decidim-proposals/spec/events/decidim/proposals/admin/proposal_note_created_event_spec.rb +++ b/decidim-proposals/spec/events/decidim/proposals/admin/proposal_note_created_event_spec.rb @@ -39,4 +39,26 @@ describe Decidim::Proposals::Admin::ProposalNoteCreatedEvent do .to include(%(Someone has left a note on the proposal <a href="#{resource_path}">#{resource_title}</a>. Check it out at <a href="#{admin_proposal_info_path}">the admin panel</a>)) end end + + context "when proposals component added to assemblies participatory space" do + let(:assembly) { create(:assembly) } + let(:proposal_component) { create :proposal_component, participatory_space: assembly } + let(:resource) { create :proposal, component: proposal_component, title: ::Faker::Lorem.characters(number: 25) } + let(:admin_proposal_info_path) { "/admin/assemblies/#{participatory_space.slug}/components/#{component.id}/manage/proposals/#{resource.id}" } + let(:admin_proposal_info_url) { "http://#{organization.host}/admin/assemblies/#{participatory_space.slug}/components/#{component.id}/manage/proposals/#{resource.id}" } + + describe "email_intro" do + it "is generated correctly" do + expect(subject.email_intro) + .to eq(%(Someone has left a note on the proposal "#{resource_title}". Check it out at <a href="#{admin_proposal_info_url}">the admin panel</a>)) + end + end + + describe "notification_title" do + it "is generated correctly" do + expect(subject.notification_title) + .to include(%(Someone has left a note on the proposal <a href="#{resource_path}">#{resource_title}</a>. Check it out at <a href="#{admin_proposal_info_path}">the admin panel</a>)) + end + end + end end
Fix notifications when there is a note proposal in other spaces than processes (#<I>)
decidim_decidim
train
eaebb55ec4d453eca9eb8f7c566c215e7656a66d
diff --git a/spec/platform/overlay_cache_spec.rb b/spec/platform/overlay_cache_spec.rb index <HASH>..<HASH> 100644 --- a/spec/platform/overlay_cache_spec.rb +++ b/spec/platform/overlay_cache_spec.rb @@ -53,7 +53,7 @@ describe Platform::OverlayCache do end it "should have extensions" do - @cache.extensions.should == ['test', 'hello', 'random'] + @cache.extensions.should == ['hello', 'random', 'test'] end it "should provide the paths to specific extensions" do
Make sure the extension names are sorted.
ronin-ruby_ronin
train
0dfa63bad944126a56b2bdef1b8f57c621d3d3dd
diff --git a/packages/react-dnd/src/DragDropContextProvider.js b/packages/react-dnd/src/DragDropContextProvider.js index <HASH>..<HASH> 100644 --- a/packages/react-dnd/src/DragDropContextProvider.js +++ b/packages/react-dnd/src/DragDropContextProvider.js @@ -29,32 +29,40 @@ export default class DragDropContextProvider extends Component { window: PropTypes.object, } - constructor(props, context) { - super(props, context) - this.backend = unpackBackendForEs5Users(props.backend) - } + constructor(props, context) { + super(props, context) - getChildContext() { - /** + /** * This property determines which window global to use for creating the DragDropManager. * If a window has been injected explicitly via props, that is used first. If it is available * as a context value, then use that, otherwise use the browser global. */ - const getWindow = () => { - if (this.props && this.props.window) { - return this.props.window - } else if (this.context && this.context.window) { - return this.context.window - } else if (typeof window !== 'undefined') { - return window - } - return undefined - } - - return createChildContext(this.backend, { window: getWindow() }) - } + const getWindow = () => { + if (props && props.window) { + return props.window + } else if (context && context.window) { + return context.window + } else if (typeof window !== 'undefined') { + return window + } + return undefined + }; - render() { - return Children.only(this.props.children) - } + this.backend = unpackBackendForEs5Users(props.backend) + this.childContext = createChildContext(this.backend, { window: getWindow() }) + } + + componentWillReceiveProps(nextProps) { + if (nextProps.backend !== this.props.backend || nextProps.window !== this.props.window) { + throw new Error('DragDropContextProvider backend and window props must not change.') + } + } + + getChildContext() { + return this.childContext + } + + render() { + return Children.only(this.props.children) + } }
DragDropContextProvider don't recreate child context (#<I>) * DragDropContextProvider don't recreate child context * .
react-dnd_react-dnd
train
bd95afbafd30cb6911c582f6fcea7a97af5974ae
diff --git a/tests/test_core.py b/tests/test_core.py index <HASH>..<HASH> 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -303,14 +303,6 @@ class TestPath: assert '/pets' in paths assert '/v1/pets' not in paths - def test_add_path_strips_path_base_path(self, spec): - spec.options['basePath'] = '/v1' - path = '/v1/pets' - spec.add_path(path) - paths = get_paths(spec) - assert '/pets' in paths - assert '/v1/pets' not in paths - def test_add_parameters(self, spec): route_spec = self.paths['/pet/{petId}']['get']
Remove duplicate test This is a remain from Path removal.
marshmallow-code_apispec
train
898f04d9cf888c36275c65f31a27df126d56aba4
diff --git a/mod/quiz/format/multianswer/format.php b/mod/quiz/format/multianswer/format.php index <HASH>..<HASH> 100644 --- a/mod/quiz/format/multianswer/format.php +++ b/mod/quiz/format/multianswer/format.php @@ -147,7 +147,7 @@ class quiz_file_format extends quiz_default_format { /// multianswer import $questions= array(); - $thequestion= extractMultiAnswerQuestion(implode('',$lines)); + $thequestion= extractMultiAnswerQuestion(addslashes(implode('',$lines))); if (!empty($thequestion)) { $thequestion->name = $lines[0];
Allow cloze questions to contain quotes
moodle_moodle
train
39556cc20f663412b8ae653196a306414955ac7f
diff --git a/oauthlib/parameters.py b/oauthlib/parameters.py index <HASH>..<HASH> 100644 --- a/oauthlib/parameters.py +++ b/oauthlib/parameters.py @@ -9,3 +9,97 @@ This module contains methods related to `section 3.5`_ of the OAuth 1.0a spec. .. _`section 3.5`: http://tools.ietf.org/html/rfc5849#section-3.5 """ +from urlparse import urlparse, urlunparse, parse_qsl +from utils import filter_params, urlencode + + +def order_params(target): + """Decorator which reorders params contents to start with oauth_* params + + Assumes the decorated method takes a params dict or list of tuples as its + first argument. + """ + def wrapper(params, *args, **kwargs): + params = order_oauth_parameters(params) + return target(params, *args, **kwargs) + + wrapper.__doc__ = target.__doc__ + return wrapper + + +def order_oauth_parameters(params): + """Order a parameters dict or list of tuples with OAuth ones first + + Per `section 3.5`_ of the spec. + + .. _`section 3.5`: http://tools.ietf.org/html/rfc5849#section-3.5 + """ + # Convert dictionaries to list of tuples + if isinstance(params, dict): + params = params.items() + + ordered = [] + for k, v in params: + if k.startswith("oauth_"): + ordered.insert(0, (k, v)) + else: + ordered.append((k, v)) + + return ordered + + +@filter_params +def prepare_authorization_header(params, realm=None): + """Prepare the Authorization header. + + Per `section 3.5.1`_ of the spec. + + .. _`section 3.5.1`: http://tools.ietf.org/html/rfc5849#section-3.5.1 + + """ + # TODO: Realm should always be the first parameter, right? + # Doesn't seem to be specified. + if realm: + params.insert(0, ("realm", realm)) + + # Only oauth_ and realm parameters should remain by this point. + return 'OAuth {params}'.format(params=', '.join( + ['{0}="{1}"'.format(k, v) for k, v in params])) + + +@order_params +def prepare_form_encoded_body(params): + """Prepare the Form-Encoded Body. + + Per `section 3.5.2`_ of the spec. + + params: OAuth parameters and data (i.e. POST data). + + .. _`section 3.5.2`: http://tools.ietf.org/html/rfc5849#section-3.5.2 + + """ + return '&'.join(['{0}={1}'.format(k, v) for k, v in params]) + + +@order_params +def prepare_request_uri_query(params, url): + """Prepare the Request URI Query. + + Per `section 3.5.3`_ of the spec. + + params: OAuth parameters and data (i.e. POST data). + url: The request url. Query components will be removed. + + .. _`section 3.5.3`: http://tools.ietf.org/html/rfc5849#section-3.5.3 + + """ + # convert dict to list of tuples + if isinstance(params, dict): + params = params.items() + + # append OAuth params to the existing set of query components + sch, net, path, par, query, fra = urlparse(url) + queryparams = parse_qsl(query, True) + queryparams.extend(params) + query = urlencode(params) + return urlunparse((sch, net, path, par, query, fra))
First stab at parameters.py Implements section <I> of the spec
oauthlib_oauthlib
train
3572bb5c0e67223b6252a2ae254852fe6769c0bb
diff --git a/doc/source/reference/potential.rst b/doc/source/reference/potential.rst index <HASH>..<HASH> 100644 --- a/doc/source/reference/potential.rst +++ b/doc/source/reference/potential.rst @@ -342,7 +342,6 @@ As an example, we integrate the Sun's orbit for 10 Gyr in which gives .. image:: ../images/orbit-sun-mwpotentials.png - :scale: 40 % Much of the difference between these orbits is due to the different present Galactocentric radius of the Sun, if we simply plot the @@ -354,7 +353,6 @@ agree better >>> o_irrI.plot(d1='R-{}'.format(get_physical(Irrgang13I)['ro']),d2='z',overplot=True,lw=0.6) .. image:: ../images/orbit-sun-mwpotentials-vsRsun.png - :scale: 40 % We can also compare the rotation curves of these different models @@ -365,8 +363,6 @@ We can also compare the rotation curves of these different models >>> legend() .. image:: ../images/mwpotentials-vcirc.png - :scale: 40 % - diff --git a/galpy/orbit/integrateFullOrbit.py b/galpy/orbit/integrateFullOrbit.py index <HASH>..<HASH> 100644 --- a/galpy/orbit/integrateFullOrbit.py +++ b/galpy/orbit/integrateFullOrbit.py @@ -172,8 +172,7 @@ def _parse_pot(pot,potforactions=False,potfortorus=False): npot+= 1 pot_type.append(26) stype= Sigma.get('type','exp') - if stype == 'exp' \ - or (stype == 'exp' and 'Rhole' in Sigma): + if stype == 'exp' and not 'Rhole' in Sigma: pot_args.extend([3,0, 4.*numpy.pi*Sigma.get('amp',1.)*p._amp, Sigma.get('h',1./3.)]) diff --git a/tests/test_orbit.py b/tests/test_orbit.py index <HASH>..<HASH> 100644 --- a/tests/test_orbit.py +++ b/tests/test_orbit.py @@ -50,6 +50,7 @@ from test_potential import testplanarMWPotential, testMWPotential, \ fullyRotatedTriaxialNFWPotential, \ sech2DiskSCFPotential, \ expwholeDiskSCFPotential, \ + altExpwholeDiskSCFPotential, \ mockFlatSpiralArmsPotential, \ mockRotatingFlatSpiralArmsPotential, \ mockSpecialRotatingFlatSpiralArmsPotential, \ @@ -126,6 +127,7 @@ def test_energy_jacobi_conservation(): pots.append('mockSCFDensityPotential') pots.append('sech2DiskSCFPotential') pots.append('expwholeDiskSCFPotential') + pots.append('altExpwholeDiskSCFPotential') pots.append('mockFlatSpiralArmsPotential') pots.append('mockRotatingFlatSpiralArmsPotential') pots.append('mockSpecialRotatingFlatSpiralArmsPotential') @@ -498,6 +500,7 @@ def test_energy_conservation_linear(): pots.append('mockSCFAxiDensity2Potential') pots.append('sech2DiskSCFPotential') pots.append('expwholeDiskSCFPotential') + pots.append('altExpwholeDiskSCFPotential') pots.append('triaxialLogarithmicHaloPotential') pots.append('nestedListPotential') rmpots= ['Potential','MWPotential','MWPotential2014', diff --git a/tests/test_potential.py b/tests/test_potential.py index <HASH>..<HASH> 100644 --- a/tests/test_potential.py +++ b/tests/test_potential.py @@ -3805,6 +3805,24 @@ class expwholeDiskSCFPotential(DiskSCFPotential): hz={'type':'exp','h':1./27.}, a=1.,N=5,L=5) return None +# Same as above, but specify type as 'exp' and give Rhole, to make sure that +# case is handled correctly +class altExpwholeDiskSCFPotential(DiskSCFPotential): + def __init__(self): + # Add a Hernquist potential because otherwise the density near the + # center is zero + from galpy.potential import HernquistPotential + hp= HernquistPotential(normalize=0.5) + DiskSCFPotential.__init__(self,\ + dens=lambda R,z: 13.5*numpy.exp(-0.5/(R+10.**-10.) + -3.*R-numpy.fabs(z)*27.) + +hp.dens(R,z), + Sigma={'h': 1./3., + 'type': 'exp','amp': 1.0, + 'Rhole':0.5}, + hz={'type':'exp','h':1./27.}, + a=1.,N=5,L=5) + return None class nonaxiDiskSCFPotential(DiskSCFPotential): def __init__(self): thp= triaxialHernquistPotential()
Fix parsing of DiskSCFPotential to C in the case where type == 'exp' but Rhole is in the list of parameters (so type should be expwhole)
jobovy_galpy
train
6582ef1a499391bf1d76da92065751dd7afcd36a
diff --git a/lib/xcode/parsers/plutil_project_parser.rb b/lib/xcode/parsers/plutil_project_parser.rb index <HASH>..<HASH> 100644 --- a/lib/xcode/parsers/plutil_project_parser.rb +++ b/lib/xcode/parsers/plutil_project_parser.rb @@ -1,4 +1,5 @@ require 'json' +require 'plist' module Xcode @@ -7,10 +8,11 @@ module Xcode # # Using the sytem tool plutil, the specified project file is parsed and - # converted to JSON, which is then converted to a hash object. + # converted to XML, and then converted into a ruby hash object. # def parse path - JSON.parse(`plutil -convert json -o - "#{path}"`) + xml = `plutil -convert xml1 -o - "#{path}"` + Plist::parse_xml(xml) end end diff --git a/lib/xcode/version.rb b/lib/xcode/version.rb index <HASH>..<HASH> 100644 --- a/lib/xcode/version.rb +++ b/lib/xcode/version.rb @@ -1,3 +1,3 @@ module Xcode - VERSION = "0.0.21" + VERSION = "0.1.0" end
Use plutil -convert xml1 as json doesnt exist on snow leopard
rayh_xcoder
train
995a35c16ec9b4e2f7138ce13d6916aa722dfd5e
diff --git a/tests/test_request_construction.py b/tests/test_request_construction.py index <HASH>..<HASH> 100644 --- a/tests/test_request_construction.py +++ b/tests/test_request_construction.py @@ -178,36 +178,70 @@ def test_element_references_to_different_namespaces(): </SOAP-ENV:Envelope>""") -def test_extra_parameters(): - """Extra input parameters should be rejected.""" - service = _service_from_wsdl(tests.wsdl_input("""\ - <xsd:element name="Wrapper"> - <xsd:complexType> - <xsd:sequence> - <xsd:element name="aString" type="xsd:string" /> - <xsd:element name="anInteger" type="xsd:integer" /> - </xsd:sequence> - </xsd:complexType> - </xsd:element>""", "Wrapper")) - - def test(expected, *args, **kwargs): - try: - service.f(*args, **kwargs) - except TypeError, e: - assert str(e) == expected +class TestExtraParameters: + """ + Extra input parameters should be rejected correctly. - expected = "f() takes 2 positional arguments but 3 were given" - test(expected, "one", 2, 3) - test(expected, "one", 2, "boom") + Parameters should be treated as regular Python function arguments. - expected = "f() got an unexpected keyword argument 'x'" - test(expected, "one", 2, x=3) - test(expected, aString="one", anInteger=2, x=3) - test(expected, aString="one", x=3, anInteger=2) - test(expected, x=3, aString="one", anInteger=2) + """ - expected = "f() got multiple values for argument 'aString'" - test(expected, 3, aString="one", anInteger=3) + def expect_error(self, expected_error_text, *args, **kwargs): + try: + self.service.f(*args, **kwargs) + except TypeError, e: + assert str(e) == expected_error_text + + def init_function_params(self, params): + """ + Initialize a test in this group with the given parameter definition. + + Constructs a complete WSDL schema based on the given function parameter + definition (used to define a single function named 'f'), and creates a + suds Client object to be used for testing suds's web service operation + invocation. + + May only be invoked once per test. + + """ + # Using an empty 'xsd:element' XML element here when passed an empty + # params string seems to cause suds not to recognize the web service + # operation described in the given WSDL schema as using 'wrapped' input + # parameters. Whether or not this is the correct behaviour is not up to + # the tests in this test group to decide so we make sure we at least + # add a single space as the element's data. + if not params: + params = " " + input = '<xsd:element name="Wrapper">%s</xsd:element>' % (params,) + assert not hasattr(self, "service") + self.service = _service_from_wsdl(tests.wsdl_input(input, "Wrapper")) + + def test_function_with_multiple_parameters(self): + """ + Test how extra parameters are handled in an operation taking more than + one input parameter. + + """ + self.init_function_params("""\ + <xsd:complexType> + <xsd:sequence> + <xsd:element name="aString" type="xsd:string" /> + <xsd:element name="anInteger" type="xsd:integer" /> + </xsd:sequence> + </xsd:complexType>""") + + expected = "f() takes 2 positional arguments but 3 were given" + self.expect_error(expected, "one", 2, 3) + self.expect_error(expected, "one", 2, "boom") + + expected = "f() got an unexpected keyword argument 'x'" + self.expect_error(expected, "one", 2, x=3) + self.expect_error(expected, aString="one", anInteger=2, x=3) + self.expect_error(expected, aString="one", x=3, anInteger=2) + self.expect_error(expected, x=3, aString="one", anInteger=2) + + expected = "f() got multiple values for argument 'aString'" + self.expect_error(expected, 3, aString="one", anInteger=3) def test_invalid_input_parameter_type_handling():
refactor the extra parameter reporting test This is a preparation step for extending the test suite with similar tests done using functions taking no parameters or a single parameter, which need to use a bit different wording in their exception strings.
suds-community_suds
train
b75d6131f89fcc86f4198bcbde2ded2cdfe1a39f
diff --git a/lib/greeklish/greeklish_converter.rb b/lib/greeklish/greeklish_converter.rb index <HASH>..<HASH> 100644 --- a/lib/greeklish/greeklish_converter.rb +++ b/lib/greeklish/greeklish_converter.rb @@ -44,6 +44,10 @@ module Greeklish # @param token_length the length of the input token # @return A list of the generated strings def convert(input_token) + if (input_token[-1, 1] == "ς") + input_token[-1, 1] = "σ" + end + # Is this a Greek word? if (!identify_greek_word(input_token)) return nil diff --git a/spec/greeklish_converter_spec.rb b/spec/greeklish_converter_spec.rb index <HASH>..<HASH> 100644 --- a/spec/greeklish_converter_spec.rb +++ b/spec/greeklish_converter_spec.rb @@ -7,7 +7,7 @@ describe 'GreeklishConverter' do # a sample of greek words to generate their greeklish # counterparts. - greek_words = ["αυτοκινητο", "ομπρελα", "ξεσκεπαστοσ"] + greek_words = ["αυτοκινητο", "ομπρελα", "ξεσκεπαστοσ", "ομορφος"] # the greeklish counterparts that should be generated from the greek words. generated_greeklish_words = [ @@ -15,11 +15,16 @@ describe 'GreeklishConverter' do "autokinito", "aftokinito", "avtokinito", "aytokinito", "autokinhtwn", "aftokinhta", "avtokinhta", "aytokinhtwn"], ["omprela", "obrela", "ompreles", "obrelwn", "obreles", "omprelas"], - ["kseskepastos", "xeskepastos", "kseskepastou", "xeskepastwn", "kseskepastoi"] + ["kseskepastos", "xeskepastos", "kseskepastou", "xeskepastwn", "kseskepastoi"], + ["omorfos", "omorphos", "omorfh", "omorphh", "omorfi", "omorphi", "omorfous", + "omorphous", "omorfoys", "omorphoys", "omorfus", "omorphus", "omorfou", + "omorphou", "omorfoy", "omorphoy", "omorfu", "omorphu", "omorfoi", "omorphoi", + "omorfi", "omorphi", "omorfwn", "omorphwn", "omorfon", "omorphon", "omorfvn", + "omorphvn"] ] # these words should not be processed by the converter. - invalid_words = ["mobile", "αυριο64", "καλάθι", "ΣΠιτι", "ομορφος" ] + invalid_words = ["mobile", "αυριο64", "καλάθι", "ΣΠιτι"] before(:each) do @greeklish_words = []
Transform "ς" to "σ"
skroutz_greeklish
train
f3cdf351b76a5a6b3f6f35c5d265392e76a0882b
diff --git a/src/utils/Sorter.js b/src/utils/Sorter.js index <HASH>..<HASH> 100644 --- a/src/utils/Sorter.js +++ b/src/utils/Sorter.js @@ -168,8 +168,8 @@ module.exports = Backbone.View.extend({ // TODO: Cache ?!? var frameRect = frame.getBoundingClientRect(); var ownerDocBodyRect = frame.ownerDocument.body.getBoundingClientRect(); - addTop = frameRect.top - ownerDocBodyRect.top; - addLeft = frameRect.left - ownerDocBodyRect.left; + addTop = frameRect.top - ownerDocBodyRect.top - doc.body.scrollTop; + addLeft = frameRect.left - ownerDocBodyRect.left - doc.body.scrollLeft; } dragHelperStyle.top = (e.pageY + addTop) + 'px'; dragHelperStyle.left = (e.pageX + addLeft) + 'px';
Block component drag helper position - account for scroll in the editor canvas
artf_grapesjs
train
2a462f9ae668740d52d4dea46c690ecd6dd3456e
diff --git a/src/Main.js b/src/Main.js index <HASH>..<HASH> 100644 --- a/src/Main.js +++ b/src/Main.js @@ -165,7 +165,7 @@ Main.prototype.printHelp = function(parser) { var buf = parser.help(); - console.log(buf); + this.getOutput().log(buf); }; /** @@ -176,9 +176,7 @@ Main.prototype.printVersion = function() { var Package = require("../package.json"); - - // TODO use Output? - console.log(Package.version); + this.getOutput().log(Package.version); }; /**
Main: Use output for printing help and version
crosswalk-project_crosswalk-app-tools
train
86ec22ad524b6f1f929b400085c8cbb925588959
diff --git a/docs/app/js/codepen.js b/docs/app/js/codepen.js index <HASH>..<HASH> 100644 --- a/docs/app/js/codepen.js +++ b/docs/app/js/codepen.js @@ -158,8 +158,13 @@ // module needs to match so that the $templateCache is populated with the necessary // assets. function replaceDemoModuleWithCodepenModule(file) { - var matchAngularModule = /\.module\(('[^']*'|"[^"]*")\s*,(?:\s*\[([^\]]*)\])?/g; - return file.replace(matchAngularModule, ".module('MyApp'"); + var matchAngularModule = /\.module\(('[^']*'|"[^"]*")\s*,(\s*\[([^\]]*)\]\s*\))/ig; + + // Include 'ngMessages' since the 'assets-cache.js' has the same dependencies + // angular.module('MyApp', ['ngMaterial', 'ngMessages']) + // See scripts.js for list of external Angular libraries used for the demos + + return file.replace(matchAngularModule, ".module('MyApp',['ngMaterial', 'ngMessages'])"); } } })();
fix(demos): CodePen launches fixed Fixes #<I>.
angular_material
train
7d6ed530ca01c23159eae86f4c4c5e0db594ea1f
diff --git a/lib/Cldr.js b/lib/Cldr.js index <HASH>..<HASH> 100644 --- a/lib/Cldr.js +++ b/lib/Cldr.js @@ -6,6 +6,7 @@ var Path = require('path'), libxmljs = require('libxmljs'), seq = require('seq'), normalizeLocaleId = require('./normalizeLocaleId'), + convertObjectsWithIntegerKeysToArrays = require('./convertObjectsWithIntegerKeysToArrays'), cldrPluralRuleToJavaScriptAst = require('./cldrPluralRuleToJavaScriptAst'), CldrRbnfRuleSet = require('./CldrRbnfRuleSet'), uglifyJs = require('uglify-js'); @@ -308,7 +309,7 @@ Cldr.prototype = { eraNames[typeInOutput][type] = eraNames[typeInOutput][type] || eraNode.text(); }); }); - return eraNames; + return convertObjectsWithIntegerKeysToArrays(eraNames); }, extractQuarterNames: function (localeId, calendarId) { @@ -329,7 +330,7 @@ Cldr.prototype = { }); }); }); - return quarterNames; + return convertObjectsWithIntegerKeysToArrays(quarterNames); }, extractDayPeriods: function (localeId, calendarId) { @@ -370,7 +371,7 @@ Cldr.prototype = { }); }); }); - return cyclicNames; + return convertObjectsWithIntegerKeysToArrays(cyclicNames); }, extractMonthNames: function (localeId, calendarId) { @@ -391,7 +392,7 @@ Cldr.prototype = { }); }); }); - return monthNames; + return convertObjectsWithIntegerKeysToArrays(monthNames); }, extractMonthPatterns: function (localeId, calendarId) { @@ -433,7 +434,7 @@ Cldr.prototype = { }); }); }); - return dayNames; + return convertObjectsWithIntegerKeysToArrays(dayNames); }, extractFields: function (localeId, calendarId) {
Cldr.extract{Era,Quarter,Cyclic,Day,Month}Names: Output arrays instead of objects with all integer keys.
papandreou_node-cldr
train
d203a74a770964d01f8fcb918b6b9d5aa0198d86
diff --git a/benchexec/tools/hiptnt.py b/benchexec/tools/hiptnt.py index <HASH>..<HASH> 100644 --- a/benchexec/tools/hiptnt.py +++ b/benchexec/tools/hiptnt.py @@ -21,6 +21,18 @@ import benchexec.util as util import benchexec.tools.template import benchexec.result as result +REQUIRED_PATHS = [ + "fixcalc", + "hip", + "hiptnt", + "hiptnt.sh", + "oc", + "prelude.ss", + "run_hiptnt", + "stdlib.h", + "z3-4.3.2", + ] + class Tool(benchexec.tools.template.BaseTool): def executable(self):
Add required files for HIPTNT
sosy-lab_benchexec
train
ccac442d0d65e0cd7e9867c449e100fc0e5456bf
diff --git a/test/unit/esl/connection.test.js b/test/unit/esl/connection.test.js index <HASH>..<HASH> 100644 --- a/test/unit/esl/connection.test.js +++ b/test/unit/esl/connection.test.js @@ -95,6 +95,34 @@ describe('esl.Connection', function() { ); }); }); + + describe('.execute()', function() { + var uuid = 'f6a2ae66-2a0d-4ede-87ae-1da2ef25ada5', + uuid2 = 'a5eac28e-b623-463d-87ad-b9de90afaf33'; + + it('should invoke the callback', function(done) { + testChannelExecute(conn, 'playback', 'foo', uuid, function(evt) { + expect(evt.getHeader('Application')).to.equal('playback'); + done(); + }); + }); + + it('should invoke only one callback on the same session', function(done) { + testChannelExecute(conn, 'hangup', '', uuid, function(evt) { + expect(evt.getHeader('Application')).to.equal('hangup'); + done(); + }); + }); + + it('should invoke a callback for a different session', function(done) { + testChannelExecute(conn, 'hangup', '', uuid2, function(evt) { + expect(evt.getHeader('Application')).to.equal('hangup'); + done(); + }); + }); + + }); + /*, '.sendRecv()': { topic: function() { return null; }, @@ -191,3 +219,39 @@ function testConnectionSend(done, conn, args, expected) { conn.send.apply(conn, args); } + +function sendChannelExecuteResponse(conn, appUuid, appName, appArg, uuid) { + // condensed output from FreeSWITCH to test relevant parts. + var resp = [ + 'Event-Name: CHANNEL_EXECUTE_COMPLETE', + 'Unique-ID: ' + uuid, + 'Application: ' + appName, + 'Application-Response: _none_', + 'Application-UUID: ' + appUuid, + '', + '', + ].join('\n'); + conn.socket.write('Content-Type: text/event-plain\n'); + conn.socket.write('Content-Length: ' + resp.length + '\n\n'); + conn.socket.write(resp); +} + +function testChannelExecute(conn, appName, appArg, uuid, cb) { + conn.socket.once('data', function(data) { + data = data.toString('utf8'); + var lines = data.split('\n'); + + expect(lines).to.contain('call-command: execute'); + expect(lines).to.contain('execute-app-name: ' + appName); + expect(lines).to.contain('execute-app-arg: ' + appArg); + + // first send an unrelated message that should not be picked up. + var otherUuid = 'fee64ea1-c11d-4a1b-9715-b755fed7a557'; + sendChannelExecuteResponse(conn, otherUuid, 'sleep', '1', uuid); + + var appUuid = /\nEvent-UUID: ([0-9a-f-]+)\n/.exec(data)[1]; + sendChannelExecuteResponse(conn, appUuid, appName, appArg, uuid); + }); + + conn.execute(appName, appArg, uuid, cb); +}
test: add regression test for Connection.execute Ensures that the modifications to the execute callback handling does not accidentally trigger other events. Sends a different event before the actual response to ensure that <URL>
englercj_node-esl
train
f5a20108be15ca995b32e98162ea76f7fdaff757
diff --git a/search/mongo_search.go b/search/mongo_search.go index <HASH>..<HASH> 100644 --- a/search/mongo_search.go +++ b/search/mongo_search.go @@ -125,7 +125,7 @@ func dateSelector(date *Date, prefix Prefix) bson.M { } case GT: timeCriteria = bson.M{ - "$gte": date.RangeHighExcl(), + "$gt": date.RangeLowIncl(), } case LT: timeCriteria = bson.M{ @@ -168,7 +168,7 @@ func periodSelector(date *Date, prefix Prefix) bson.M { "$or": []bson.M{ bson.M{ "end.time": bson.M{ - "$gte": date.RangeHighExcl(), + "$gt": date.RangeLowIncl(), }, }, // Also support instances where period exists, but end is null (ongoing) @@ -203,7 +203,7 @@ func periodSelector(date *Date, prefix Prefix) bson.M { }, bson.M{ "end.time": bson.M{ - "$gte": date.RangeHighExcl(), + "$gt": date.RangeLowIncl(), }, }, // Also support instances where period exists, but end is null (ongoing) diff --git a/search/mongo_search_test.go b/search/mongo_search_test.go index <HASH>..<HASH> 100644 --- a/search/mongo_search_test.go +++ b/search/mongo_search_test.go @@ -340,12 +340,12 @@ func (m *MongoSearchSuite) TestConditionOnsetGTQueryObject(c *C) { "$or": []bson.M{ bson.M{ "onsetDateTime.time": bson.M{ - "$gte": time.Date(2012, time.March, 1, 7, 1, 0, 0, m.Local), + "$gt": time.Date(2012, time.March, 1, 7, 0, 0, 0, m.Local), }, }, bson.M{ "onsetPeriod.end.time": bson.M{ - "$gte": time.Date(2012, time.March, 1, 7, 1, 0, 0, m.Local), + "$gt": time.Date(2012, time.March, 1, 7, 0, 0, 0, m.Local), }, }, bson.M{ @@ -414,7 +414,7 @@ func (m *MongoSearchSuite) TestConditionOnsetGEQueryObject(c *C) { }, bson.M{ "onsetPeriod.end.time": bson.M{ - "$gte": time.Date(2012, time.March, 1, 7, 1, 0, 0, m.Local), + "$gt": time.Date(2012, time.March, 1, 7, 0, 0, 0, m.Local), }, }, bson.M{ @@ -514,7 +514,7 @@ func (m *MongoSearchSuite) TestEncounterPeriodGTQueryObject(c *C) { "$or": []bson.M{ bson.M{ "period.end.time": bson.M{ - "$gte": time.Date(2012, time.November, 1, 8, 31, 0, 0, m.Local), + "$gt": time.Date(2012, time.November, 1, 8, 30, 0, 0, m.Local), }, }, bson.M{ @@ -530,7 +530,7 @@ func (m *MongoSearchSuite) TestEncounterPeriodGTQuery(c *C) { mq := m.MongoSearcher.CreateQuery(q) num, err := mq.Count() util.CheckErr(err) - c.Assert(num, Equals, 1) + c.Assert(num, Equals, 2) } func (m *MongoSearchSuite) TestEncounterPeriodLTQueryObject(c *C) { @@ -575,7 +575,7 @@ func (m *MongoSearchSuite) TestEncounterPeriodGEQueryObject(c *C) { }, bson.M{ "period.end.time": bson.M{ - "$gte": time.Date(2012, time.November, 1, 8, 31, 0, 0, m.Local), + "$gt": time.Date(2012, time.November, 1, 8, 30, 0, 0, m.Local), }, }, bson.M{
Fix implementation of gt searches, based on clarificaton provided at <URL>
intervention-engine_fhir
train
632adeb6c771606e0506701db4b64f4596dec377
diff --git a/modules/core/src/main/java/org/torquebox/core/analysis/DefaultNodeVisitor.java b/modules/core/src/main/java/org/torquebox/core/analysis/DefaultNodeVisitor.java index <HASH>..<HASH> 100644 --- a/modules/core/src/main/java/org/torquebox/core/analysis/DefaultNodeVisitor.java +++ b/modules/core/src/main/java/org/torquebox/core/analysis/DefaultNodeVisitor.java @@ -66,7 +66,7 @@ public class DefaultNodeVisitor implements NodeVisitor { results.add( childResult ); } } catch(UnsupportedOperationException ex) { - log.warn( "JRuby doesn't support visiting node " + child + " - skipping it, but looking at its children." ); + log.trace( "JRuby doesn't support visiting node " + child + " - skipping it, but looking at its children." ); for (Node grandChild : child.childNodes()) { defaultVisitNode( grandChild ); }
Quiet down injection analyzer (TORQUE-<I>)
torquebox_torquebox
train
b1039368725bb49402ef8660103ff359b86f2c88
diff --git a/src/main/java/com/bazaarvoice/jolt/Shiftr.java b/src/main/java/com/bazaarvoice/jolt/Shiftr.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/bazaarvoice/jolt/Shiftr.java +++ b/src/main/java/com/bazaarvoice/jolt/Shiftr.java @@ -156,6 +156,16 @@ import java.util.Map; * aka "tag-Pro" and "tag-Con"). * '$' has the same syntax as the '&' wildcard, and can be read as, dereference to get a value, and then use that value as the data to be output. * + * '|' Wildcard + * Valid only on the LHS of the spec. + * This 'or' wildcard allows you to match multiple input keys. Useful if you don't always know exactly what your input data will be. + * Example Spec : + * <pre> + * { + * "rating|Rating" : "rating-primary" // match "rating" or "Rating" copy the data to "rating-primary" + * } + * </pre> + * * '@' Wildcard * Valid only on the LHS of the spec. * For the Shiftr spec to be valid Json, it can not have two keys with the exact same value. diff --git a/src/main/java/com/bazaarvoice/jolt/shiftr/Key.java b/src/main/java/com/bazaarvoice/jolt/shiftr/Key.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/bazaarvoice/jolt/shiftr/Key.java +++ b/src/main/java/com/bazaarvoice/jolt/shiftr/Key.java @@ -93,7 +93,7 @@ public class Key { literalChildren.put( child.pathElement.getRawKey(), child ); } else if ( child.pathElement instanceof AtPathElement || ( // special if it is an "@" - child.pathElement instanceof DollarReferencePathElement ) ) { // special if it is a "&" and it has no children + child.pathElement instanceof DollarReferencePathElement ) ) { // special if it is a "$" specialChildren.add( child ); } else { // star || (& with children)
Doc-ed the '|' wildcard.
bazaarvoice_jolt
train
6ee2259b3c60c5af5c6adfd5be9e99fb0f32588c
diff --git a/iotilebuild/RELEASE.md b/iotilebuild/RELEASE.md index <HASH>..<HASH> 100644 --- a/iotilebuild/RELEASE.md +++ b/iotilebuild/RELEASE.md @@ -2,6 +2,11 @@ All major changes in each released version of IOTileBuild are listed here. +## 2.6.9 + +- Add architecture overrides for qemu unit tests so that they target the + cortex-m0plus + ## 2.6.8 - Add list_local to DependencyManager so that we can implement a recursive build diff --git a/iotilebuild/iotile/build/config/site_scons/unit_test_qemu.py b/iotilebuild/iotile/build/config/site_scons/unit_test_qemu.py index <HASH>..<HASH> 100644 --- a/iotilebuild/iotile/build/config/site_scons/unit_test_qemu.py +++ b/iotilebuild/iotile/build/config/site_scons/unit_test_qemu.py @@ -92,6 +92,12 @@ class QEMUSemihostedUnitTest(unit_test.UnitTest): build_dirs = self.build_dirs(target) + # Retarget for unit tests, since qemu only supports the cortex-m0 + target = target.retarget() + target.settings['cpu'] = 'cortex-m0plus' + target.settings['cflags'] = ["-mthumb", "-Wall", "-pedantic", "-Wextra", "-Wshadow", "-Os", "-g", "-fno-builtin", "-ffunction-sections", "-fdata-sections"] + target.settings['asflags'] = ["-Wall"] + target.settings['ldflags'] = ["-mthumb", "-Xlinker", "--gc-sections", "--specs=nano.specs", "-lc", "-lnosys", "-nostartfiles"] prog_env = arm.setup_environment(target) # Convert main.c.tpl into main.c diff --git a/iotilebuild/version.py b/iotilebuild/version.py index <HASH>..<HASH> 100644 --- a/iotilebuild/version.py +++ b/iotilebuild/version.py @@ -1 +1 @@ -version = "2.6.8" +version = "2.6.9"
Hardcode cortex-m0 architecture for qemu unit tests (#<I>)
iotile_coretools
train
d3fa817e3f5ad437f12463b0aee19f0e00549050
diff --git a/network.js b/network.js index <HASH>..<HASH> 100644 --- a/network.js +++ b/network.js @@ -988,8 +988,8 @@ function handleJoint(ws, objJoint, bSaved, callbacks){ unlock(); console.log("############################## transient error "+error); joint_storage.removeUnhandledJointAndDependencies(unit, function(){ - if (objJoint.ball) - db.query("DELETE FROM hash_tree_balls WHERE ball=? AND unit=?", [objJoint.ball, objJoint.unit.unit]); + // if (objJoint.ball) + // db.query("DELETE FROM hash_tree_balls WHERE ball=? AND unit=?", [objJoint.ball, objJoint.unit.unit]); delete assocUnitsInWork[unit]; }); },
don't delete from hash_tree_balls after getting a transient error
byteball_ocore
train
adea6c4cf251a11a61b6d58ab589320eb0f74f98
diff --git a/lib/ViewModels/ToolsPanelViewModel.js b/lib/ViewModels/ToolsPanelViewModel.js index <HASH>..<HASH> 100644 --- a/lib/ViewModels/ToolsPanelViewModel.js +++ b/lib/ViewModels/ToolsPanelViewModel.js @@ -386,7 +386,10 @@ function requestTiles(toolsPanel, requests, minLevel, maxLevel) { popup.message += '<div style="' + (slowDatasets > 0 ? 'color:red' : '') + '">Slow datasets: ' + slowDatasets + ' <i>(>' + maxAverage + 'ms average, or >' + maxMaximum + 'ms maximum)</i></div>'; - popup.message += '<pre>' + JSON.stringify(blacklist) + '</pre>'; + var blacklistString = JSON.stringify(blacklist); + if (blacklistString.length > 2) { + popup.message += 'Suggested blacklist: <pre>' + JSON.stringify(blacklist) + '</pre>'; + } } }
Only show the suggesteed blacklist if there is one.
TerriaJS_terriajs
train
424e676cd44a5c0fef0e38a69cf77ef5f866a8e5
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -101,11 +101,12 @@ define( 'WP_REDIS_SERVERS', [ ### Replication (Redis Sentinel) ```php +define( 'WP_REDIS_CLIENT', 'predis' ); define( 'WP_REDIS_SENTINEL', 'mymaster' ); -define( 'WP_REDIS_SERVERS', [ - 'tcp://127.0.0.1:5380', - 'tcp://127.0.0.2:5381', - 'tcp://127.0.0.3:5382', +define( 'WP_REDIS_SENTINELS', [ + 'tcp://127.0.0.1:26379', + 'tcp://127.0.0.2:26380', + 'tcp://127.0.0.3:26381', ] ); ``` diff --git a/includes/diagnostics.php b/includes/diagnostics.php index <HASH>..<HASH> 100644 --- a/includes/diagnostics.php +++ b/includes/diagnostics.php @@ -51,6 +51,8 @@ $constants = array( 'WP_REDIS_GLOBAL_GROUPS', 'WP_REDIS_IGNORED_GROUPS', 'WP_CACHE_KEY_SALT', + 'WP_REDIS_SENTINEL', + 'WP_REDIS_SENTINELS', ); foreach ( $constants as $constant ) { diff --git a/includes/object-cache.php b/includes/object-cache.php index <HASH>..<HASH> 100644 --- a/includes/object-cache.php +++ b/includes/object-cache.php @@ -462,8 +462,11 @@ class WP_Object_Cache { $parameters = WP_REDIS_CLUSTER; $options[ 'cluster' ] = 'redis'; } elseif ( defined( 'WP_REDIS_SENTINEL' ) ) { - $parameters = WP_REDIS_SERVERS; - $options[ 'replication' ] = true; + if ( !defined( 'WP_REDIS_SENTINELS' ) ) { + throw new Exception; + } + $parameters = WP_REDIS_SENTINELS; + $options[ 'replication' ] = 'sentinel'; $options[ 'service' ] = WP_REDIS_SENTINEL; } diff --git a/includes/servers-list.php b/includes/servers-list.php index <HASH>..<HASH> 100644 --- a/includes/servers-list.php +++ b/includes/servers-list.php @@ -110,6 +110,10 @@ class Servers_List extends WP_List_Table { $servers = WP_REDIS_SERVERS; } + if ( defined( 'WP_REDIS_SENTINEL' ) && defined( 'WP_REDIS_SENTINELS' ) ) { + $servers = WP_REDIS_SENTINELS; + } + if ( ! isset( $servers ) ) { $servers = array( $server ); } diff --git a/readme.txt b/readme.txt index <HASH>..<HASH> 100644 --- a/readme.txt +++ b/readme.txt @@ -113,11 +113,12 @@ __Replication (Master-Slave):__ __Replication (Redis Sentinel):__ + define( 'WP_REDIS_CLIENT', 'predis' ); define( 'WP_REDIS_SENTINEL', 'mymaster' ); - define( 'WP_REDIS_SERVERS', [ - 'tcp://127.0.0.1:5380', - 'tcp://127.0.0.2:5381', - 'tcp://127.0.0.3:5382', + define( 'WP_REDIS_SENTINELS', [ + 'tcp://127.0.0.1:26379', + 'tcp://127.0.0.2:26380', + 'tcp://127.0.0.3:26381', ] ); __Sharding:__ diff --git a/redis-cache.php b/redis-cache.php index <HASH>..<HASH> 100644 --- a/redis-cache.php +++ b/redis-cache.php @@ -3,7 +3,7 @@ Plugin Name: Redis Object Cache Plugin URI: https://wordpress.org/plugins/redis-cache/ Description: A persistent object cache backend powered by Redis. Supports Predis, PhpRedis, HHVM, replication, clustering and WP-CLI. -Version: 1.3.5 +Version: 1.3.6 Text Domain: redis-cache Domain Path: /languages Author: Till Krüss
Extend and debug sentinel support (#<I>) * extend sentinel support * update sentinel documentation * update version number * fix typo
tillkruss_redis-cache
train
3595c7d2ae9b1324fa51999c60b91d45511e034f
diff --git a/src/nwmatcher-base.js b/src/nwmatcher-base.js index <HASH>..<HASH> 100644 --- a/src/nwmatcher-base.js +++ b/src/nwmatcher-base.js @@ -110,7 +110,7 @@ extendedValidator = standardValidator.replace(pseudoclass, '.*'), - reValidator = global.RegExp(standardValidator, 'g'), + reValidator = global.RegExp(standardValidator), reTrimSpaces = global.RegExp('^' + whitespace + '|' + whitespace + '$', 'g'), @@ -217,7 +217,7 @@ } } reValidator = global.RegExp(Config.SIMPLENOT ? - standardValidator : extendedValidator, 'g'); + standardValidator : extendedValidator); return true; }, diff --git a/src/nwmatcher-noqsa.js b/src/nwmatcher-noqsa.js index <HASH>..<HASH> 100644 --- a/src/nwmatcher-noqsa.js +++ b/src/nwmatcher-noqsa.js @@ -105,7 +105,7 @@ extendedValidator = standardValidator.replace(pseudoclass, '.*'), - reValidator = global.RegExp(standardValidator, 'g'), + reValidator = global.RegExp(standardValidator), reTrimSpaces = /^\s*|\s*$/g, @@ -388,7 +388,7 @@ } } reValidator = global.RegExp(Config.SIMPLENOT ? - standardValidator : extendedValidator, 'g'); + standardValidator : extendedValidator); return true; }, diff --git a/src/nwmatcher.js b/src/nwmatcher.js index <HASH>..<HASH> 100644 --- a/src/nwmatcher.js +++ b/src/nwmatcher.js @@ -167,7 +167,7 @@ extendedValidator = standardValidator.replace(pseudoclass, '.*'), // validator for standard selectors as default - reValidator = new global.RegExp(standardValidator, 'g'), + reValidator = new global.RegExp(standardValidator), // whitespace is any combination of these 5 character [\x20\t\n\r\f] // http://www.w3.org/TR/css3-selectors/#selector-syntax @@ -902,7 +902,7 @@ } } reValidator = new global.RegExp(Config.SIMPLENOT ? - standardValidator : extendedValidator, 'g'); + standardValidator : extendedValidator); return true; }, diff --git a/test/ender/ender.js b/test/ender/ender.js index <HASH>..<HASH> 100644 --- a/test/ender/ender.js +++ b/test/ender/ender.js @@ -263,7 +263,7 @@ extendedValidator = standardValidator.replace(pseudoclass, '.*'), // validator for standard selectors as default - reValidator = new global.RegExp(standardValidator, 'g'), + reValidator = new global.RegExp(standardValidator), // whitespace is any combination of these 5 character [\x20\t\n\r\f] // http://www.w3.org/TR/css3-selectors/#selector-syntax @@ -998,7 +998,7 @@ } } reValidator = new global.RegExp(Config.SIMPLENOT ? - standardValidator : extendedValidator, 'g'); + standardValidator : extendedValidator); return true; },
fix for invalid selector can cause match() to hang #<I> (@domenic)
dperini_nwmatcher
train
6f5c70418de4e6e56f4fe9698e60d65640c030a4
diff --git a/src/Encryptor/MCryptEncryptor.php b/src/Encryptor/MCryptEncryptor.php index <HASH>..<HASH> 100644 --- a/src/Encryptor/MCryptEncryptor.php +++ b/src/Encryptor/MCryptEncryptor.php @@ -54,9 +54,11 @@ class MCryptEncryptor implements EncryptorInterface */ public function encrypt($data) { - $this->init(); - $data = trim($this->middlewareEncryptor->encrypt(mcrypt_generic($this->module, $data))); - $this->close(); + if (!$this->isEncrypted($data)) { + $this->init(); + $data = trim($this->middlewareEncryptor->encrypt(mcrypt_generic($this->module, $data))); + $this->close(); + } return $data; } @@ -66,9 +68,11 @@ class MCryptEncryptor implements EncryptorInterface */ public function decrypt($data) { - $this->init(); - $data = trim(mdecrypt_generic($this->module, $this->middlewareEncryptor->decrypt($data))); - $this->close(); + if ($this->isEncrypted($data)) { + $this->init(); + $data = trim(mdecrypt_generic($this->module, $this->middlewareEncryptor->decrypt($data))); + $this->close(); + } return $data; } @@ -82,14 +86,6 @@ class MCryptEncryptor implements EncryptorInterface } /** - * @inheritdoc - */ - public function getName() - { - return $this->algorithm; - } - - /** * init encryption module */ private function init()
fix: avoid double encryption/decryption
rafrsr_crypto
train
d6e4c36ce36ea0c52b24f8b968dbd8b51056ee3b
diff --git a/libkbfs/folder_branch_ops.go b/libkbfs/folder_branch_ops.go index <HASH>..<HASH> 100644 --- a/libkbfs/folder_branch_ops.go +++ b/libkbfs/folder_branch_ops.go @@ -5511,6 +5511,11 @@ func (fbo *folderBranchOps) maybeFastForward(ctx context.Context, fbo.mdWriterLock.Lock(lState) defer fbo.mdWriterLock.Unlock(lState) + // Don't update while the in-memory state is dirty. + if fbo.blocks.GetState(lState) != cleanState { + return false, nil + } + // If the journal has anything in it, don't fast-forward since we // haven't finished flushing yet. If there was really a remote // update on the server, we'll end up in CR eventually.
folder_branch_ops: don't fast forward while dirty Fast-forward while dirty can cause the device to unlink unflushed nodes that have been made while disconnected, but it won't actually delete the dir entries from the dirty blocks. So when the flush finally happens, the journal will reference non-existent blocks, and all hell will break loose during CR. Issue: keybase/client#<I>
keybase_client
train
f6a930bfc23be8cc02f8901b415ebfcf142a94e7
diff --git a/sonnet/python/modules/basic.py b/sonnet/python/modules/basic.py index <HASH>..<HASH> 100644 --- a/sonnet/python/modules/basic.py +++ b/sonnet/python/modules/basic.py @@ -1241,18 +1241,20 @@ class MergeDims(base.AbstractModule): middle = [np.prod(middle)] static_shape = initial + middle + final - if static_shape.count(None) <= 1: - # At most one undefined dimension, so tf.reshape can handle this case. + if static_shape.count(None) + static_shape.count(0) <= 1: + # At most one undefined (or zero) dimension, so tf.reshape can handle this + # case. static_shape = [-1 if i is None else i for i in static_shape] return tf.reshape(tensor, static_shape) else: # Need to compute output shape dynamically. dynamic_input_shape = tf.shape(tensor) + dynamic_initial = dynamic_input_shape[:start] + dynamic_middle = tf.reduce_prod( + dynamic_input_shape[start:start + self._size], keep_dims=True) + dynamic_final = dynamic_input_shape[start + self._size:] dynamic_shape = tf.concat( - [dynamic_input_shape[:start], - [-1], - dynamic_input_shape[start + self._size:]], - axis=0) + [dynamic_initial, dynamic_middle, dynamic_final], axis=0) tensor = tf.reshape(tensor, dynamic_shape) tensor.set_shape(static_shape) # give it some static shape information diff --git a/sonnet/python/modules/basic_test.py b/sonnet/python/modules/basic_test.py index <HASH>..<HASH> 100644 --- a/sonnet/python/modules/basic_test.py +++ b/sonnet/python/modules/basic_test.py @@ -1676,6 +1676,18 @@ class MergeDimsTest(tf.test.TestCase, parameterized.TestCase): output = output.eval(feed_dict={inputs: np.zeros([2, 3, 4, 5, 6])}) self.assertEqual(list(output.shape), [2, 3, 4 * 5, 6]) + def testWithUndefinedAndZeroDim(self): + in_shape = [0, None, 2, 3] + start = 1 + size = 2 + inputs = tf.placeholder(tf.float32, shape=in_shape) + mod = snt.MergeDims(start=start, size=size) + output = mod(inputs) + self.assertEqual(output.get_shape().as_list(), [0, None, 3]) + with self.test_session() as session: + output = session.run(output, feed_dict={inputs: np.zeros([0, 5, 2, 3])}) + self.assertEqual(list(output.shape), [0, 10, 3]) + def testComputation(self): # Here we compare the output with the tf.reshape equivalent. in_shape = [2, 3, 4, 5, 6]
MergeDims: also handle dimensions of size zero. PiperOrigin-RevId: <I>
deepmind_sonnet
train
55525696c9354ccb15409d685ec63c5ffaf174ea
diff --git a/pkg/chart/chart.go b/pkg/chart/chart.go index <HASH>..<HASH> 100644 --- a/pkg/chart/chart.go +++ b/pkg/chart/chart.go @@ -356,26 +356,26 @@ func loadTar(r *tar.Reader) (*tarChart, error) { return c, nil } -// ChartMember is a file in a chart. -type ChartMember struct { +// Member is a file in a chart. +type Member struct { Path string `json:"path"` // Path from the root of the chart. Content []byte `json:"content"` // Base64 encoded content. } // LoadTemplates loads the members of TemplatesDir(). -func (c *Chart) LoadTemplates() ([]*ChartMember, error) { +func (c *Chart) LoadTemplates() ([]*Member, error) { dir := c.TemplatesDir() return c.loadDirectory(dir) } // loadDirectory loads the members of a directory. -func (c *Chart) loadDirectory(dir string) ([]*ChartMember, error) { +func (c *Chart) loadDirectory(dir string) ([]*Member, error) { files, err := ioutil.ReadDir(dir) if err != nil { return nil, err } - members := []*ChartMember{} + members := []*Member{} for _, file := range files { filename := filepath.Join(dir, file.Name()) if !file.IsDir() { @@ -399,13 +399,13 @@ func (c *Chart) loadDirectory(dir string) ([]*ChartMember, error) { } // LoadMember loads a chart member from a given path where path is the root of the chart. -func (c *Chart) LoadMember(path string) (*ChartMember, error) { +func (c *Chart) LoadMember(path string) (*Member, error) { filename := filepath.Join(c.loader.dir(), path) return c.loadMember(filename) } // loadMember loads and base 64 encodes a file. -func (c *Chart) loadMember(filename string) (*ChartMember, error) { +func (c *Chart) loadMember(filename string) (*Member, error) { dir := c.Dir() if !strings.HasPrefix(filename, dir) { err := fmt.Errorf("File %s is outside chart directory %s", filename, dir) @@ -419,7 +419,7 @@ func (c *Chart) loadMember(filename string) (*ChartMember, error) { path := strings.TrimPrefix(filename, dir) content := base64.StdEncoding.EncodeToString(b) - result := &ChartMember{ + result := &Member{ Path: path, Content: []byte(content), } @@ -428,8 +428,8 @@ func (c *Chart) loadMember(filename string) (*ChartMember, error) { } type ChartContent struct { - Chartfile *Chartfile `json:"chartfile"` - Members []*ChartMember `json:"members"` + Chartfile *Chartfile `json:"chartfile"` + Members []*Member `json:"members"` } func (c *Chart) LoadContent() (*ChartContent, error) { diff --git a/pkg/chart/chart_test.go b/pkg/chart/chart_test.go index <HASH>..<HASH> 100644 --- a/pkg/chart/chart_test.go +++ b/pkg/chart/chart_test.go @@ -198,7 +198,7 @@ func TestLoadTemplates(t *testing.T) { } } -func findMember(root, path string, members []*ChartMember) error { +func findMember(root, path string, members []*Member) error { for _, member := range members { if member.Path == path { filename := filepath.Join(root, path)
ref(chart): refactor ChartMember -> Member * Fixes some style errors in #<I>
helm_helm
train
356c487b1cafcafb9cdd62a88ce062895a0d62e7
diff --git a/tests/unit/date/test_daterange.py b/tests/unit/date/test_daterange.py index <HASH>..<HASH> 100644 --- a/tests/unit/date/test_daterange.py +++ b/tests/unit/date/test_daterange.py @@ -234,3 +234,19 @@ def test_intersection_preserves_boundaries(): assert DateRange('20110101', '20110102', OPEN_OPEN) == DateRange('20110101', '20110102', CLOSED_OPEN).intersection(DateRange('20110101', '20110102', OPEN_OPEN)) assert DateRange('20110101', '20110102', OPEN_OPEN) == DateRange('20110101', '20110102', OPEN_OPEN).intersection(DateRange('20110101', '20110102', OPEN_CLOSED)) + +def test_intersection_contains(): + # assert ((d in dr1) & (d in dr2)) == (d in (dr1 & dr2)) for any interval combination + start, end = dt(2018,1,1), dt(2018,1,2) + date_ranges = [DateRange(start, end, interval) for interval in CLOSED_CLOSED.__class__] + + def equal_contains(date,dr1,dr2): + return ((date in dr1) and (date in dr2)) == (date in dr1.intersection(dr2)) + + assert all(equal_contains(start,dr1,dr2) for dr1 in date_ranges for dr2 in date_ranges) + assert all(equal_contains(end,dr1,dr2) for dr1 in date_ranges for dr2 in date_ranges) + + + + +
added test_intersection_contains
manahl_arctic
train
0f2aaced43d20a342e477800a014a7be68fdc373
diff --git a/lib/gds.js b/lib/gds.js index <HASH>..<HASH> 100644 --- a/lib/gds.js +++ b/lib/gds.js @@ -40,7 +40,7 @@ module.exports = exports = gds = function init(config) { user: config.username, pass: config.password } -console.log(opts) + return request(opts, function(error, response, body) { return console.log({ error: error, @@ -103,9 +103,46 @@ console.log(opts) var gremlin = gremlinQuery; + /* + Input/Output + */ + + // Bulk Upload - GraphML + function uploadGraphMl() { + + } + + // Buld Upload - graphson + function uploadGraphSON() { + + } + + // Extract + function extractBulk(format) { + if (!format) var format = 'json'; + + var opts = { + url: '/extract', + headers: { + 'Content-Type': 'application/' + format + } + } + + return apiCall(opts); + } + + var io = { + bulkload: { + graphml: uploadGraphMl, + graphson: uploadGraphSON + }, + extract: extractBulk + } + // Return object return { vertices: vertices, - gremlin: gremlin + gremlin: gremlin, + io: io } }
I/O extract: defaults to JSON
ibm-watson-data-lab_--deprecated--nodejs-graph
train
e6e3c4ad0c543f739d78b6cb0015330701f7d3eb
diff --git a/cmd/crio/main.go b/cmd/crio/main.go index <HASH>..<HASH> 100644 --- a/cmd/crio/main.go +++ b/cmd/crio/main.go @@ -6,6 +6,7 @@ import ( "fmt" "io/ioutil" "net/http" + _ "net/http/pprof" "os" "os/signal" "path/filepath"
Bring back pprof Commit <I>f<I> (Oct <I> <I>, "Update golangci lint and apply fixes") inadvertently removed the pprof import, as a result, pprof can't be used even when enabled during runtime (via --profile flag), giving <I> on every URL. Bring it back.
cri-o_cri-o
train
574cfd24d835a5efd34d0f3833292f6e3935a660
diff --git a/lib/assets/javascripts/magic_grid.js b/lib/assets/javascripts/magic_grid.js index <HASH>..<HASH> 100644 --- a/lib/assets/javascripts/magic_grid.js +++ b/lib/assets/javascripts/magic_grid.js @@ -20,7 +20,7 @@ $(function () { is_manual = (e.type == 'search' || e.type == 'change'), relevant = is_manual || length >= minLength || length == 0, base_url = $grid.data("current"), - params = {}, + params = {'magic_grid_id' : grid_id}, //40 wpm typists == 280ms //90 wpm typists == 120ms delay = is_manual ? 0 : 250;
Send grid id in ajax requests, in theory to allow partials to be used for response
rmg_magic_grid
train
4c72ae91edc2bebbe13ca1f8eee32547826a8f15
diff --git a/RAPIDpy/goodnessOfFit.py b/RAPIDpy/goodnessOfFit.py index <HASH>..<HASH> 100644 --- a/RAPIDpy/goodnessOfFit.py +++ b/RAPIDpy/goodnessOfFit.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- ## ## goodnessOfFit.py ## RAPIDpy diff --git a/RAPIDpy/helper_functions.py b/RAPIDpy/helper_functions.py index <HASH>..<HASH> 100644 --- a/RAPIDpy/helper_functions.py +++ b/RAPIDpy/helper_functions.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- ## ## helper_functions.py ## RAPIDpy diff --git a/RAPIDpy/make_CF_RAPID_output.py b/RAPIDpy/make_CF_RAPID_output.py index <HASH>..<HASH> 100755 --- a/RAPIDpy/make_CF_RAPID_output.py +++ b/RAPIDpy/make_CF_RAPID_output.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +# -*- coding: utf-8 -*- ## ## make_CF_output.py ## RAPIDpy diff --git a/RAPIDpy/rapid.py b/RAPIDpy/rapid.py index <HASH>..<HASH> 100644 --- a/RAPIDpy/rapid.py +++ b/RAPIDpy/rapid.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- ## ## rapid.py ## RAPIDpy
added utf-8 coding comment at top of files
erdc_RAPIDpy
train
3a88003793d38cbb2cad61de634798e1d5d56832
diff --git a/src/Flex.php b/src/Flex.php index <HASH>..<HASH> 100644 --- a/src/Flex.php +++ b/src/Flex.php @@ -74,6 +74,7 @@ class Flex implements PluginInterface, EventSubscriberInterface 'remove' => false, 'unpack' => true, ]; + private $shouldUpdateComposerLock = false; public function activate(Composer $composer, IOInterface $io) { @@ -194,6 +195,8 @@ class Flex implements PluginInterface, EventSubscriberInterface // don't use $manipulator->removeProperty() for BC with Composer 1.0 $contents = preg_replace('{^\s*+"(?:name|description)":.*,$\n}m', '', $manipulator->getContents()); file_put_contents($json->getPath(), $contents); + + $this->updateComposerLock(); } public function record(PackageEvent $event) @@ -303,7 +306,7 @@ class Flex implements PluginInterface, EventSubscriberInterface $manipulator = new JsonManipulator(file_get_contents($json->getPath())); $manipulator->addSubNode('extra', 'symfony.allow-contrib', true); file_put_contents($json->getPath(), $manipulator->getContents()); - $this->updateComposerLock(); + $this->shouldUpdateComposerLock = true; } } @@ -338,6 +341,10 @@ class Flex implements PluginInterface, EventSubscriberInterface } $this->lock->write(); + + if ($this->shouldUpdateComposerLock) { + $this->updateComposerLock(); + } } public function enableThanksReminder() @@ -565,7 +572,7 @@ class Flex implements PluginInterface, EventSubscriberInterface $manipulator = new JsonManipulator(file_get_contents($json->getPath())); $manipulator->addSubNode('extra', 'symfony.id', $id); file_put_contents($json->getPath(), $manipulator->getContents()); - $this->updateComposerLock(); + $this->shouldUpdateComposerLock = true; return $id; } @@ -638,13 +645,11 @@ class Flex implements PluginInterface, EventSubscriberInterface private function updateComposerLock() { $lock = substr(Factory::getComposerFile(), 0, -4).'lock'; - if (!file_exists($lock)) { - // lock file does not exist yet, bypass - return; - } - $lockData = $this->composer->getLocker()->getLockData(); - $lockData['content-hash'] = Locker::getContentHash(file_get_contents(Factory::getComposerFile())); + $composerJson = file_get_contents(Factory::getComposerFile()); $lockFile = new JsonFile($lock, null, $this->io); + $locker = new Locker($this->io, $lockFile, $this->composer->getRepositoryManager(), $this->composer->getInstallationManager(), $composerJson); + $lockData = $locker->getLockData(); + $lockData['content-hash'] = Locker::getContentHash($composerJson); $lockFile->write($lockData); }
fixed wrong content hash in composer.lock (again)
symfony_flex
train
35091dea4762b59b9cafe42c722c348851999ec8
diff --git a/doc/DocumentationReader.js b/doc/DocumentationReader.js index <HASH>..<HASH> 100644 --- a/doc/DocumentationReader.js +++ b/doc/DocumentationReader.js @@ -47,7 +47,9 @@ var DocumentationReader = DocumentationController.extend({ }, panelOrder: ['toc'], containerId: 'body', - isEditable: false + isEditable: false, + skipAbstractClasses: true, + skipPrivateMethods: true } },
Hide private methods and abstract classes.
substance_substance
train
81ea091b88d9b24ae3ebab5fc1e5117d0836d1b3
diff --git a/lib/switch_point/model.rb b/lib/switch_point/model.rb index <HASH>..<HASH> 100644 --- a/lib/switch_point/model.rb +++ b/lib/switch_point/model.rb @@ -11,7 +11,7 @@ module SwitchPoint module ClassMethods def connection_with_switch_point - if @switch_point_name + if switch_point_proxy switch_point_proxy.connection else connection_without_switch_point
Ask to switch_point_proxy rather than @switch_point_name
eagletmt_switch_point
train
9e8ae39711143648158f555757296c613175c819
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ * Fix #3445: TokenRefreshInterceptor throws when running incluster config * Fix #3456: io.fabric8:crd-generator README should reference crd-generator-apt instead of now removed crd-generator artifact * Fix #3384: preventing NPE from being logged with pod execs. +* Fix #3484: Ensuring that the informer isWatching flag is correctly reported #### Improvements * Fix #3398: Added javadocs explaining the wait parameter diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManager.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManager.java index <HASH>..<HASH> 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManager.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManager.java @@ -87,10 +87,18 @@ public abstract class AbstractWatchManager<T extends HasMetadata> implements Wat // proactively close the request (it will be called again in close) // for reconnecting watchers, we may not complete onClose for a while closeRequest(); - if (!watcher.reconnecting() && forceClosed.getAndSet(true)) { + if (forceClosed.get()) { logger.debug("Ignoring duplicate firing of onClose event"); - } else { - watcher.onClose(cause); + } else { + boolean success = false; + try { + watcher.onClose(cause); + success = true; + } finally { + if (success || !watcher.reconnecting()) { + forceClosed.set(true); + } + } } close(); } diff --git a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/cache/Reflector.java b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/cache/Reflector.java index <HASH>..<HASH> 100644 --- a/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/cache/Reflector.java +++ b/kubernetes-client/src/main/java/io/fabric8/kubernetes/client/informers/cache/Reflector.java @@ -122,7 +122,7 @@ public class Reflector<T extends HasMetadata, L extends KubernetesResourceList<T throw new KubernetesClientException("Unrecognized resource"); } if (log.isDebugEnabled()) { - log.debug("Event received {} {}# resourceVersion {}", action.name(), resource.getKind(), resource.getMetadata().getResourceVersion()); + log.debug("Event received {} {} resourceVersion {}", action.name(), resource.getKind(), resource.getMetadata().getResourceVersion()); } switch (action) { case ERROR: diff --git a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManagerTest.java b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManagerTest.java index <HASH>..<HASH> 100644 --- a/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManagerTest.java +++ b/kubernetes-client/src/test/java/io/fabric8/kubernetes/client/dsl/internal/AbstractWatchManagerTest.java @@ -71,6 +71,24 @@ class AbstractWatchManagerTest { // Then assertThat(watcher.closeCount.get()).isEqualTo(1); } + + @Test + void closeEventWithExceptionIsIdempotentWithReconnecting() throws MalformedURLException { + // Given + final WatcherAdapter<HasMetadata> watcher = new WatcherAdapter<HasMetadata>() { + @Override + public boolean reconnecting() { + return true; + } + }; + final WatchManager<HasMetadata> awm = withDefaultWatchManager(watcher); + // When + for (int it = 0; it < 10; it++) { + awm.close(new WatcherException("Mock")); + } + // Then + assertThat(watcher.closeCount.get()).isEqualTo(1); + } @Test @DisplayName("closeWebSocket, closes web socket with 1000 code (Normal Closure)")
fix #<I>: ensuring that only one close method is called successfully
fabric8io_kubernetes-client
train
8b6c69a969dc07372d4b5d0abe6e06717d01a528
diff --git a/tryp/tc/base.py b/tryp/tc/base.py index <HASH>..<HASH> 100644 --- a/tryp/tc/base.py +++ b/tryp/tc/base.py @@ -3,6 +3,8 @@ import abc from typing import GenericMeta, Dict # type: ignore from functools import partial +from fn import _, F + from tryp.util.string import snake_case from tryp.lazy import lazy from tryp.tc.show import Show @@ -164,18 +166,27 @@ class AllInstances(object): def add(self, name, inst: ImplicitInstances): self._instances[name] = inst - def lookup(self, f, a): - for t in a.__mro__: - inst = self._lookup_type(f, t) - if inst is not None: - return inst - raise ImplicitNotFound(f, a) - - def _lookup_type(self, f, a): - if a.__name__ in self._instances: - inst = self._instances[a.__name__].instances.get(f) | None - if inst is not None: - return inst + def lookup(self, TC, G): + ''' Find an instance of the type class `TC` for type `G`. + Iterates `G`'s parent classes, looking up instances for each, + checking whether the instance is a subclass of the target type + class @`C`. + ''' + from tryp.lazy_list import LazyList + match = F(self._lookup_type, TC) + result = LazyList(map(match, G.__mro__))\ + .find(_.is_just)\ + .flatten\ + .get_or_raise(ImplicitNotFound(TC, G)) + return result[1] + + def _lookup_type(self, TC, G): + from tryp.maybe import Empty + if G.__name__ in self._instances: + match = lambda I: isinstance(I, TC) + return self._instances[G.__name__].instances.find(match) + else: + return Empty() Instances = AllInstances() # type: AllInstances
improve type class instance lookup test instances for inheritance of the target type class, so that when searching for a Functor, a Monad is treated as a match
tek_amino
train
29cdf39eb56944ffe8e45dd73ee77a87d66b0b9a
diff --git a/test/schema_object_base_test.rb b/test/schema_object_base_test.rb index <HASH>..<HASH> 100644 --- a/test/schema_object_base_test.rb +++ b/test/schema_object_base_test.rb @@ -80,6 +80,12 @@ describe Scorpio::SchemaObjectBase do end end describe 'initialization' do + describe 'on Base' do + it 'errors' do + err = assert_raises(TypeError) { Scorpio::SchemaObjectBase.new({}) } + assert_equal('cannot instantiate Scorpio::SchemaObjectBase which has no method #__schema__. please use Scorpio.class_for_schema', err.message) + end + end describe 'nil' do let(:object) { nil } it 'initializes with nil object' do
test initialization of SchemaObjectBase itself
notEthan_jsi
train
b4aa83da62a21144aa85c016448e28212de1596d
diff --git a/zzk/zkdao.go b/zzk/zkdao.go index <HASH>..<HASH> 100644 --- a/zzk/zkdao.go +++ b/zzk/zkdao.go @@ -83,23 +83,10 @@ func (zkdao *ZkDao) AddService(service *service.Service) error { return AddService(conn, service) } -type ServiceNode struct { - Service *service.Service - version interface{} -} - -func (s *ServiceNode) Version() interface{} { - return s.version -} - -func (s *ServiceNode) SetVersion(version interface{}) { - s.version = version -} - func AddService(conn coordclient.Connection, service *service.Service) error { glog.V(2).Infof("Creating new service %s", service.Id) - svcNode := &ServiceNode{ + svcNode := &zkservice.ServiceNode{ Service: service, } servicePath := ServicePath(service.Id) @@ -176,19 +163,7 @@ func (zkdao *ZkDao) UpdateService(service *service.Service) error { return err } defer conn.Close() - - servicePath := ServicePath(service.Id) - - sn := ServiceNode{} - if err := conn.Get(servicePath, &sn); err != nil { - glog.V(3).Infof("ZkDao.UpdateService unexpectedly could not retrieve %s error:%v", servicePath, err) - err = AddService(conn, service) - return err - } - sn.Service = service - glog.V(4).Infof("ZkDao.UpdateService %v, %v", servicePath, service) - - return conn.Set(servicePath, &sn) + return zkservice.UpdateService(conn, service) } func (zkdao *ZkDao) GetServiceState(serviceState *servicestate.ServiceState, serviceId string, serviceStateId string) error { @@ -415,7 +390,7 @@ func LoadHostServiceStateW(conn coordclient.Connection, hostId string, hssId str } func LoadService(conn coordclient.Connection, serviceId string, s *service.Service) error { - sn := ServiceNode{} + sn := zkservice.ServiceNode{} err := conn.Get(ServicePath(serviceId), &sn) if err != nil { glog.Errorf("Unable to retrieve service %s: %v", serviceId, err) @@ -426,7 +401,7 @@ func LoadService(conn coordclient.Connection, serviceId string, s *service.Servi } func LoadServiceW(conn coordclient.Connection, serviceId string, s *service.Service) (<-chan coordclient.Event, error) { - sn := ServiceNode{} + sn := zkservice.ServiceNode{} event, err := conn.GetW(ServicePath(serviceId), &sn) if err != nil { //glog.Errorf("Unable to retrieve service %s: %v", serviceId, err) @@ -494,7 +469,7 @@ func LoadAndUpdateServiceState(conn coordclient.Connection, serviceId string, ss func loadAndUpdateService(conn coordclient.Connection, serviceId string, mutator serviceMutator) error { servicePath := ServicePath(serviceId) - serviceNode := ServiceNode{} + serviceNode := zkservice.ServiceNode{} err := conn.Get(servicePath, &serviceNode) if err != nil { glog.Errorf("Unable to find data %s: %v", servicePath, err)
moved service node referenced to zzk/service
control-center_serviced
train
68b9cd4a38238a55bf0a446c140c4c13406788e3
diff --git a/src/Refinery29.php b/src/Refinery29.php index <HASH>..<HASH> 100644 --- a/src/Refinery29.php +++ b/src/Refinery29.php @@ -92,6 +92,7 @@ class Refinery29 extends Config 'single_array_no_trailing_comma' => true, 'single_blank_line_before_namespace' => true, 'single_quote' => true, + 'spaces_after_semicolon' => true, 'spaces_before_semicolon' => true, 'spaces_cast' => true, 'standardize_not_equal' => true, diff --git a/test/Refinery29Test.php b/test/Refinery29Test.php index <HASH>..<HASH> 100644 --- a/test/Refinery29Test.php +++ b/test/Refinery29Test.php @@ -194,6 +194,7 @@ class Refinery29Test extends \PHPUnit_Framework_TestCase 'single_array_no_trailing_comma' => true, 'single_blank_line_before_namespace' => true, 'single_quote' => true, + 'spaces_after_semicolon' => true, 'spaces_before_semicolon' => true, 'spaces_cast' => true, 'standardize_not_equal' => true,
Enhancement: Enable spaces_after_semicolon fixer
refinery29_php-cs-fixer-config
train
b94fb960b75983b878b192b9ee00e578145f09ac
diff --git a/src/Sulu/Bundle/WebsiteBundle/Analytics/AnalyticsManager.php b/src/Sulu/Bundle/WebsiteBundle/Analytics/AnalyticsManager.php index <HASH>..<HASH> 100644 --- a/src/Sulu/Bundle/WebsiteBundle/Analytics/AnalyticsManager.php +++ b/src/Sulu/Bundle/WebsiteBundle/Analytics/AnalyticsManager.php @@ -101,9 +101,13 @@ class AnalyticsManager implements AnalyticsManagerInterface public function remove($id) { $entity = $this->find($id); + + $webspaceKey = $entity->getWebspaceKey(); + $analyticsTitle = $entity->getTitle(); + $this->entityManager->remove($entity); - $this->domainEventCollector->collect(new AnalyticsRemovedEvent($id, $entity->getWebspaceKey())); + $this->domainEventCollector->collect(new AnalyticsRemovedEvent($id, $webspaceKey, $analyticsTitle)); } public function removeMultiple(array $ids) diff --git a/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsCreatedEvent.php b/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsCreatedEvent.php index <HASH>..<HASH> 100644 --- a/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsCreatedEvent.php +++ b/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsCreatedEvent.php @@ -65,6 +65,11 @@ class AnalyticsCreatedEvent extends DomainEvent return (string) $this->analytics->getId(); } + public function getResourceWebspaceKey(): string + { + return $this->analytics->getWebspaceKey(); + } + public function getResourceTitle(): ?string { return $this->analytics->getTitle(); diff --git a/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsModifiedEvent.php b/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsModifiedEvent.php index <HASH>..<HASH> 100644 --- a/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsModifiedEvent.php +++ b/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsModifiedEvent.php @@ -65,6 +65,11 @@ class AnalyticsModifiedEvent extends DomainEvent return (string) $this->analytics->getId(); } + public function getResourceWebspaceKey(): string + { + return $this->analytics->getWebspaceKey(); + } + public function getResourceTitle(): ?string { return $this->analytics->getTitle(); diff --git a/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsRemovedEvent.php b/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsRemovedEvent.php index <HASH>..<HASH> 100644 --- a/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsRemovedEvent.php +++ b/src/Sulu/Bundle/WebsiteBundle/Domain/Event/AnalyticsRemovedEvent.php @@ -27,12 +27,21 @@ class AnalyticsRemovedEvent extends DomainEvent */ private $webspaceKey; - public function __construct(int $id, string $webspaceKey) - { + /** + * @var string|null + */ + private $analyticsTitle; + + public function __construct( + int $id, + string $webspaceKey, + ?string $analyticsTitle + ) { parent::__construct(); $this->id = $id; $this->webspaceKey = $webspaceKey; + $this->analyticsTitle = $analyticsTitle; } public function getId(): int @@ -45,14 +54,24 @@ class AnalyticsRemovedEvent extends DomainEvent return 'removed'; } + public function getResourceKey(): string + { + return AnalyticsInterface::RESOURCE_KEY; + } + public function getResourceId(): string { return (string) $this->id; } - public function getResourceKey(): string + public function getResourceWebspaceKey(): string { - return AnalyticsInterface::RESOURCE_KEY; + return $this->webspaceKey; + } + + public function getResourceTitle(): ?string + { + return $this->analyticsTitle; } public function getResourceSecurityContext(): ?string
Enhance domain events for analytics (#<I>) * Fix domain events for analytics * Fix review
sulu_sulu
train
1e97f3e1f2862611055998d7e9d055084b09e677
diff --git a/src/helpers/DbConn.php b/src/helpers/DbConn.php index <HASH>..<HASH> 100644 --- a/src/helpers/DbConn.php +++ b/src/helpers/DbConn.php @@ -45,7 +45,7 @@ final class DbConn extends PDO implements DbConnInterface */ private static function loadDotenv() { - $dotenv = new \Dotenv\Dotenv(__DIR__ . '/../..'); + $dotenv = new \Dotenv\Dotenv($_SERVER['DOCUMENT_ROOT']); $dotenv->load(); } }
Make Dotenv to search for .env file in the document root always
kola-er_potato-orm
train
3a56a6653d651f5f2480ee19f931be2c2f8f5c88
diff --git a/lib/chewy/type/adapter/sequel.rb b/lib/chewy/type/adapter/sequel.rb index <HASH>..<HASH> 100644 --- a/lib/chewy/type/adapter/sequel.rb +++ b/lib/chewy/type/adapter/sequel.rb @@ -1,4 +1,4 @@ -require 'chewy/type/adapter/orm' +require 'chewy/type/adapter/base' module Chewy class Type @@ -77,7 +77,7 @@ module Chewy def import_dataset(dataset, batch_size) dataset = dataset.limit(batch_size) - DB.transaction(isolation: :committed) do + dataset.db.transaction(isolation: :committed) do 0.step(Float::INFINITY, batch_size).lazy .map { |offset| dataset.offset(offset).to_a } .take_while(&:any?)
Do not assume DB connection in the constant DB in sequel adapter
toptal_chewy
train
e0e668a268932a51825fdd0cccae33efdc03e74d
diff --git a/Slim/App.php b/Slim/App.php index <HASH>..<HASH> 100644 --- a/Slim/App.php +++ b/Slim/App.php @@ -1300,7 +1300,7 @@ class App extends \Pimple $message = $e->getMessage(); $file = $e->getFile(); $line = $e->getLine(); - $trace = $e->getTraceAsString(); + $trace = str_replace(array('#', '\n'), array('<div>#', '</div>'), $e->getTraceAsString()); $html = '<p>The application could not run because of the following error:</p>'; $html .= '<h2>Details</h2>';
Separate individual stack trace lines with div elements
slimphp_Slim
train
fdf1f4caa956e1ff76f83905928cfda84f5b0541
diff --git a/mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/MappingDataTypeCompletion.java b/mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/MappingDataTypeCompletion.java index <HASH>..<HASH> 100644 --- a/mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/MappingDataTypeCompletion.java +++ b/mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/MappingDataTypeCompletion.java @@ -34,6 +34,7 @@ import it.unibz.inf.ontop.model.type.RDFDatatype; import it.unibz.inf.ontop.model.type.TermType; import it.unibz.inf.ontop.model.type.TypeFactory; import it.unibz.inf.ontop.model.type.impl.TermTypeInferenceTools; +import it.unibz.inf.ontop.model.vocabulary.RDF; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -81,15 +82,32 @@ public class MappingDataTypeCompletion { public void insertDataTyping(CQIE rule) throws UnknownDatatypeException { Function atom = rule.getHead(); - Predicate predicate = atom.getFunctionSymbol(); - if (predicate.getArity() == 2) { // we check both for data and object property - Term term = atom.getTerm(1); // the second argument only + + //case of data and object property + if(!isURIRDFType(atom.getTerm(1))){ + Term object = atom.getTerm(2); // the object, third argument only Map<String, List<IndexedPosition>> termOccurenceIndex = createIndex(rule.getBody()); // Infer variable datatypes - insertVariableDataTyping(term, atom, 1, termOccurenceIndex); + insertVariableDataTyping(object, atom, 2, termOccurenceIndex); // Infer operation datatypes from variable datatypes - insertOperationDatatyping(term, atom, 1); + insertOperationDatatyping(object, atom, 2); + } + } + + /** + * check if the term is {@code URI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")} + */ + + private static boolean isURIRDFType(Term term) { + if (term instanceof Function) { + Function func = (Function) term; + if (func.getArity() == 1 && (func.getFunctionSymbol() instanceof URITemplatePredicate)) { + Term t0 = func.getTerm(0); + if (t0 instanceof ValueConstant) + return ((ValueConstant) t0).getValue().equals(RDF.TYPE.getIRIString()); + } } + return false; } /** @@ -99,7 +117,7 @@ public class MappingDataTypeCompletion { */ private void insertVariableDataTyping(Term term, Function atom, int position, Map<String, List<IndexedPosition>> termOccurenceIndex) throws UnknownDatatypeException { - Predicate predicate = atom.getFunctionSymbol(); + Term predicate = atom.getTerm(1); if (term instanceof Function) { Function function = (Function) term; @@ -121,7 +139,7 @@ public class MappingDataTypeCompletion { Term newTerm; RDFDatatype type = getDataType(termOccurenceIndex, variable); newTerm = termFactory.getTypedTerm(variable, type); - log.info("Datatype "+type+" for the value " + variable + " of the property " + predicate + " has been " + + log.info("Datatype "+type+" for the value " + variable + " of the property " + ((Function) predicate).getTerm(0) + " has been " + "inferred " + "from the database"); atom.setTerm(position, newTerm);
accept triples in MappingDatatypeCompletion
ontop_ontop
train
0401c7d7af7489b70a411707e8e6d2622538ca6b
diff --git a/src/__tests__/YouTube-test.js b/src/__tests__/YouTube-test.js index <HASH>..<HASH> 100644 --- a/src/__tests__/YouTube-test.js +++ b/src/__tests__/YouTube-test.js @@ -23,6 +23,7 @@ const playerMock = { destroy: jest.genMockFunction(), addEventListener: jest.genMockFunction(), removeEventListener: jest.genMockFunction(), + getIframe: jest.genMockFunction().mockImplementation(() => true), }; createPlayer.mockImplementation((id, props, cb) => cb(playerMock)); @@ -35,6 +36,7 @@ describe('YouTube Component', () => { playerMock.destroy.mockClear(); playerMock.addEventListener.mockClear(); playerMock.removeEventListener.mockClear(); + playerMock.getIframe.mockClear(); }); describe('rendering', () => {
Fix test broken by iframe check
troybetz_react-youtube
train
0f71ba3de1ad9d1e5ad50864722e57f7f74cf0c5
diff --git a/core/message.go b/core/message.go index <HASH>..<HASH> 100644 --- a/core/message.go +++ b/core/message.go @@ -88,6 +88,11 @@ func (msg *Message) GetStreamID() MessageStreamID { return msg.data.streamID } +// GetOrigStreamID returns the original/first streamID +func (msg *Message) GetOrigStreamID() MessageStreamID { + return msg.orig.streamID +} + // GetPrevStreamID returns the last "hop" of this message. func (msg *Message) GetPrevStreamID() MessageStreamID { return msg.prevStreamID
added Message.GetOrigStreamID()
trivago_gollum
train
1e6a7ca15d1084d29f36cb1c0c4b87a0d2946fe3
diff --git a/src/ProxyManager/ProxyGenerator/LazyLoadingGhost/MethodGenerator/MagicIsset.php b/src/ProxyManager/ProxyGenerator/LazyLoadingGhost/MethodGenerator/MagicIsset.php index <HASH>..<HASH> 100644 --- a/src/ProxyManager/ProxyGenerator/LazyLoadingGhost/MethodGenerator/MagicIsset.php +++ b/src/ProxyManager/ProxyGenerator/LazyLoadingGhost/MethodGenerator/MagicIsset.php @@ -40,6 +40,8 @@ class MagicIsset extends MagicMethodGenerator * @var string */ private $callParentTemplate = <<<'PHP' +%s + if (isset(self::$%s[$name])) { return isset($this->$name); } @@ -92,6 +94,7 @@ if (isset(self::$%s[$name])) { } } +%s PHP; /** @@ -112,33 +115,29 @@ PHP; ) { parent::__construct($originalClass, '__isset', [new ParameterGenerator('name')]); - $override = $originalClass->hasMethod('__isset'); + $override = $originalClass->hasMethod('__isset'); $this->setDocblock(($override ? "{@inheritDoc}\n" : '') . '@param string $name'); - $callParent = sprintf( - $this->callParentTemplate, - $publicProperties->getName(), - $protectedProperties->getName(), - $protectedProperties->getName(), - $privateProperties->getName(), - $privateProperties->getName(), - $privateProperties->getName() - ); + $parentAccess = 'return parent::__isset($name);'; - if ($override) { - $callParent .= 'return parent::__isset($name);'; - } else { - $callParent .= PublicScopeSimulator::getPublicAccessSimulationCode( + if (! $override) { + $parentAccess = PublicScopeSimulator::getPublicAccessSimulationCode( PublicScopeSimulator::OPERATION_ISSET, 'name' ); } - $this->setBody( + $this->setBody(sprintf( + $this->callParentTemplate, '$this->' . $initializerProperty->getName() . ' && $this->' . $callInitializer->getName() - . '(\'__isset\', array(\'name\' => $name));' - . "\n\n" . $callParent - ); + . '(\'__isset\', array(\'name\' => $name));', + $publicProperties->getName(), + $protectedProperties->getName(), + $protectedProperties->getName(), + $privateProperties->getName(), + $privateProperties->getName(), + $parentAccess + )); } }
Reducing code size, removing variables and mutability
Ocramius_ProxyManager
train
eb060742f54aa1c1b772470f53927eb9bf1755bb
diff --git a/actor/v7action/application.go b/actor/v7action/application.go index <HASH>..<HASH> 100644 --- a/actor/v7action/application.go +++ b/actor/v7action/application.go @@ -43,13 +43,17 @@ func (actor Actor) DeleteApplicationByNameAndSpace(name, spaceGUID string, delet } } - jobURL, deleteAppWarnings, err := actor.CloudControllerClient.DeleteApplication(app.GUID) + appDeleteJobURL, deleteAppWarnings, err := actor.CloudControllerClient.DeleteApplication(app.GUID) allWarnings = append(allWarnings, deleteAppWarnings...) if err != nil { return allWarnings, err } - jobQueue = append(jobQueue, jobURL) + pollWarnings, err := actor.CloudControllerClient.PollJob(appDeleteJobURL) + allWarnings = append(allWarnings, pollWarnings...) + if err != nil { + return allWarnings, err + } if deleteRoutes { for _, route := range routes { diff --git a/actor/v7action/application_test.go b/actor/v7action/application_test.go index <HASH>..<HASH> 100644 --- a/actor/v7action/application_test.go +++ b/actor/v7action/application_test.go @@ -57,9 +57,10 @@ var _ = Describe("Application Actions", func() { }) }) - When("looking up the app guid succeeds", func() { + When("looking up the app guid succeeds without routes", func() { BeforeEach(func() { fakeCloudControllerClient.GetApplicationsReturns([]resources.Application{{Name: "some-app", GUID: "abc123"}}, ccv3.Warnings{"some-get-app-warning"}, nil) + deleteMappedRoutes = false }) When("sending the delete fails", func() { @@ -102,7 +103,7 @@ var _ = Describe("Application Actions", func() { }) }) - When("attempting to delete mapped routes", func() { + When("looking up the app guid succeeds with routes", func() { BeforeEach(func() { deleteMappedRoutes = true fakeCloudControllerClient.GetApplicationsReturns([]resources.Application{{Name: "some-app", GUID: "abc123"}}, nil, nil)
Wait for app to finish deleting before starting deletion of routes - We saw a CATS failure in the new v7 CATS pipeline related to deletions happening out of order, it would cause weird failures, see <URL>
cloudfoundry_cli
train
9d607130ca2faae0e1db5c1824ea65b69afb0d04
diff --git a/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/wizards/common/corePageBuilder.js b/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/wizards/common/corePageBuilder.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/wizards/common/corePageBuilder.js +++ b/bundles/org.eclipse.orion.client.cf/web/cfui/plugins/wizards/common/corePageBuilder.js @@ -67,9 +67,9 @@ define(['i18n!cfui/nls/messages', 'orion/selection', 'orion/widgets/input/ComboT if(orgTargets[i].Space == self._spacesDropdown.value){ self._selection.setSelections(orgTargets[i]); self._defaultTarget.OrgId = null; - self._defaultTarget.OrgName = orgTargets[i].Org; + self._defaultTarget.Org = orgTargets[i].Org; self._defaultTarget.SpaceId = null; - self._defaultTarget.SpaceName = orgTargets[i].Space; + self._defaultTarget.Space = orgTargets[i].Space; return; } } @@ -89,9 +89,9 @@ define(['i18n!cfui/nls/messages', 'orion/selection', 'orion/widgets/input/ComboT option.org = org; if (self._defaultTarget && (self._defaultTarget.OrgId === org.Guid - || self._defaultTarget.OrgName === org.Name)){ + || self._defaultTarget.Org === org.Name)){ option.selected = "selected"; //$NON-NLS-0$ - self._defaultTarget.OrgName = org.Name; + self._defaultTarget.Org = org.Name; } self._orgsDropdown.appendChild(option); @@ -134,9 +134,9 @@ define(['i18n!cfui/nls/messages', 'orion/selection', 'orion/widgets/input/ComboT option.target = target; if (self._defaultTarget && (self._defaultTarget.SpaceId === target.SpaceId - || self._defaultTarget.SpaceName === target.Space)){ + || self._defaultTarget.Space === target.Space)){ option.selected = "selected"; //$NON-NLS-0$ - self._defaultTarget.SpaceName = target.Space; + self._defaultTarget.Space = target.Space; } self._spacesDropdown.appendChild(option);
Bug <I> - Launch conf wizard does not show the right org and space
eclipse_orion.client
train
2fa7abaad2a2b6ddbdb0949576d9cfb7fbb44e88
diff --git a/django_base64field/tests/models.py b/django_base64field/tests/models.py index <HASH>..<HASH> 100644 --- a/django_base64field/tests/models.py +++ b/django_base64field/tests/models.py @@ -38,3 +38,13 @@ class Helper(models.Model): return base64.encode(self.pk) return self.ek + + +class CustomReceiver(models.Model): + """ + Passing custom receiver to generate `youyouid` with a custom receiver. + """ + youyouid = Base64Field( + encode_receiver='django_base64field.tests.receivers:custom_receiver' + ) +
Add CustomReceiver model Passing custom receiver to generate `youyouid` with a custom receiver.
Alir3z4_django-base64field
train
d5ab0a256bbaaf0be3d05376d33a676d69e0a3a8
diff --git a/pyemma/coordinates/api.py b/pyemma/coordinates/api.py index <HASH>..<HASH> 100644 --- a/pyemma/coordinates/api.py +++ b/pyemma/coordinates/api.py @@ -8,7 +8,7 @@ __docformat__ = "restructuredtext en" from pyemma.util.annotators import deprecated from pyemma.util.log import getLogger -from pyemma.coordinates.pipelines import Discretizer as _Discretizer, Pipeline +from pyemma.coordinates.pipelines import Discretizer as _Discretizer from pyemma.coordinates.pipelines import Pipeline as _Pipeline # io from pyemma.coordinates.io.featurizer import MDFeaturizer as _MDFeaturizer
[coor/api] added data_in_memory to wrap numpy arrays and numpy- and csv readers.
markovmodel_PyEMMA
train
02a436159a57dd5dc0e323a126cfa7d39d8e3e6f
diff --git a/pysat/_files.py b/pysat/_files.py index <HASH>..<HASH> 100644 --- a/pysat/_files.py +++ b/pysat/_files.py @@ -282,13 +282,13 @@ class Files(object): # # Ensure files are in order # self.files = files_info.sort_index() + # Attach data + self.files = files_info + # Filter for empty files here (in addition to refresh) if self.ignore_empty_files: self._filter_empty_files(path=self.data_path) - # Attach data - self.files = files_info - # Extract date information from first and last files if not self.files.empty: self.start_date = filter_datetime_input(self.files.index[0]) @@ -366,6 +366,7 @@ class Files(object): loaded = pds.read_csv(fname, index_col=0, parse_dates=True, squeeze=True, header=0) self.data_path = loaded.name + loaded.name = None return loaded else: # grab files from memory @@ -396,7 +397,6 @@ class Files(object): # Check all potential directory locations for files. # Stop as soon as we find some. for path in self.data_paths: - # print('list_file ', self.list_files_rtn) info = self.list_files_rtn(tag=self.sat_info['tag'], inst_id=self.sat_info['inst_id'], data_path=path,
BUG: Removed name on Series aa part of _load
rstoneback_pysat
train
da6bc9c9e43e03997080364234dcc04f5f4245e0
diff --git a/angular-multi-select.js b/angular-multi-select.js index <HASH>..<HASH> 100644 --- a/angular-multi-select.js +++ b/angular-multi-select.js @@ -35,7 +35,7 @@ var angular_multi_select = angular.module( 'angular-multi-select', ['ng'] ); -angular_multi_select.directive( 'angularMultiSelect' , [ '$sce', '$timeout', '$templateCache', function ( $sce, $timeout ) { +angular_multi_select.directive( 'angularMultiSelect' , [ '$sce', '$timeout', function ( $sce, $timeout ) { return { restrict: 'AE',
Stop injecting things we won't use
alexandernst_angular-multi-select
train
15b2a2575d9f9940232e3fc656c3d2b264e520f0
diff --git a/pyerarchy/__init__.py b/pyerarchy/__init__.py index <HASH>..<HASH> 100644 --- a/pyerarchy/__init__.py +++ b/pyerarchy/__init__.py @@ -1,3 +1,6 @@ __author__ = 'bagrat' import core +import ex + +from core.node import Node
refac: Reorganized module import structure Node can be imported directly from pyerarchy.
bagrat_pyerarchy
train
ac7701fa0e3bcf305c3767f3a32be1db0324fa8c
diff --git a/errors.js b/errors.js index <HASH>..<HASH> 100644 --- a/errors.js +++ b/errors.js @@ -237,36 +237,36 @@ module.exports.SocketClosedError = TypedError({ reason: null }); -module.exports.TChannelDuplicateInitRequestError = TypedError({ - type: 'tchannel.init.duplicate-init-request', - message: 'tchannel: duplicate init request' -}); - -module.exports.TChannelDuplicateInitResponseError = TypedError({ - type: 'tchannel.init.duplicate-init-response', - message: 'tchannel: duplicate init response' -}); - module.exports.TChannelCallReqBeforeInitReqError = TypedError({ type: 'tchannel.init.call-request-before-init-request', message: 'call request before init request' }); -module.exports.TChannelCallResBeforeInitResError = TypedError({ - type: 'tchannel.init.call-response-before-init-response', - message: 'call response before init response' -}); - module.exports.TChannelCallReqContBeforeInitReqError = TypedError({ type: 'tchannel.init.call-request-cont-before-init-request', message: 'call request cont before init request' }); +module.exports.TChannelCallResBeforeInitResError = TypedError({ + type: 'tchannel.init.call-response-before-init-response', + message: 'call response before init response' +}); + module.exports.TChannelCallResContBeforeInitResError = TypedError({ type: 'tchannel.init.call-response-cont-before-init-response', message: 'call response cont before init response' }); +module.exports.TChannelDuplicateInitRequestError = TypedError({ + type: 'tchannel.init.duplicate-init-request', + message: 'tchannel: duplicate init request' +}); + +module.exports.TChannelDuplicateInitResponseError = TypedError({ + type: 'tchannel.init.duplicate-init-response', + message: 'tchannel: duplicate init response' +}); + module.exports.TChannelListenError = WrappedError({ type: 'tchannel.server.listen-failed', message: 'tchannel: {origMessage}',
alphabetical order to the erros
uber_tchannel-node
train
2d16374c1146a27e8e11ac2f4c2c94b185d327d0
diff --git a/charmhelpers/contrib/openstack/utils.py b/charmhelpers/contrib/openstack/utils.py index <HASH>..<HASH> 100644 --- a/charmhelpers/contrib/openstack/utils.py +++ b/charmhelpers/contrib/openstack/utils.py @@ -41,6 +41,7 @@ UBUNTU_OPENSTACK_RELEASE = OrderedDict([ ('quantal', 'folsom'), ('raring', 'grizzly'), ('saucy', 'havana'), + ('trusty', 'icehouse') ]) @@ -260,6 +261,9 @@ def configure_installation_source(rel): 'havana': 'precise-updates/havana', 'havana/updates': 'precise-updates/havana', 'havana/proposed': 'precise-proposed/havana', + 'icehouse': 'precise-updates/icehouse', + 'icehouse/updates': 'precise-updates/icehouse', + 'icehouse/proposed': 'precise-proposed/icehouse', } try: diff --git a/charmhelpers/fetch/__init__.py b/charmhelpers/fetch/__init__.py index <HASH>..<HASH> 100644 --- a/charmhelpers/fetch/__init__.py +++ b/charmhelpers/fetch/__init__.py @@ -44,8 +44,16 @@ CLOUD_ARCHIVE_POCKETS = { 'precise-havana/updates': 'precise-updates/havana', 'precise-updates/havana': 'precise-updates/havana', 'havana/proposed': 'precise-proposed/havana', - 'precies-havana/proposed': 'precise-proposed/havana', + 'precise-havana/proposed': 'precise-proposed/havana', 'precise-proposed/havana': 'precise-proposed/havana', + # Icehouse + 'icehouse': 'precise-updates/icehouse', + 'precise-icehouse': 'precise-updates/icehouse', + 'precise-icehouse/updates': 'precise-updates/icehouse', + 'precise-updates/icehouse': 'precise-updates/icehouse', + 'icehouse/proposed': 'precise-proposed/icehouse', + 'precise-icehouse/proposed': 'precise-proposed/icehouse', + 'precise-proposed/icehouse': 'precise-proposed/icehouse', } diff --git a/tests/contrib/openstack/test_openstack_utils.py b/tests/contrib/openstack/test_openstack_utils.py index <HASH>..<HASH> 100644 --- a/tests/contrib/openstack/test_openstack_utils.py +++ b/tests/contrib/openstack/test_openstack_utils.py @@ -76,6 +76,10 @@ UCA_SOURCES = [ ('cloud:precise-havana/proposed', url + ' precise-proposed/havana main'), ('cloud:precise-havana', url + ' precise-updates/havana main'), ('cloud:precise-havana/updates', url + ' precise-updates/havana main'), + ('cloud:precise-icehouse/proposed', + url + ' precise-proposed/icehouse main'), + ('cloud:precise-icehouse', url + ' precise-updates/icehouse main'), + ('cloud:precise-icehouse/updates', url + ' precise-updates/icehouse main'), ]
Add support for icehouse cloud archive pockets
juju_charm-helpers
train
1633206cc9d4b58b2f4cdaa8755f74d9561b6e7f
diff --git a/src/Illuminate/Database/Migrations/Migrator.php b/src/Illuminate/Database/Migrations/Migrator.php index <HASH>..<HASH> 100755 --- a/src/Illuminate/Database/Migrations/Migrator.php +++ b/src/Illuminate/Database/Migrations/Migrator.php @@ -192,14 +192,18 @@ class Migrator $this->note("<comment>Migrating:</comment> {$name}"); + $startTime = microtime(true); + $this->runMigration($migration, 'up'); + $runTime = round(microtime(true) - $startTime, 2); + // Once we have run a migrations class, we will log that it was run in this // repository so that we don't try to run it next time we do a migration // in the application. A migration repository keeps the migrate order. $this->repository->log($name, $batch); - $this->note("<info>Migrated:</info> {$name}"); + $this->note("<info>Migrated:</info> {$name} ({$runTime} seconds)"); } /** @@ -349,14 +353,18 @@ class Migrator return $this->pretendToRun($instance, 'down'); } + $startTime = microtime(true); + $this->runMigration($instance, 'down'); + $runTime = round(microtime(true) - $startTime, 2); + // Once we have successfully run the migration "down" we will remove it from // the migration repository so it will be considered to have not been run // by the application then will be able to fire by any later operation. $this->repository->delete($migration); - $this->note("<info>Rolled back:</info> {$name}"); + $this->note("<info>Rolled back:</info> {$name} ({$runTime} seconds)"); } /**
Add runtime for each migration to output
laravel_framework
train
b6f025049f2f9dd948bfe8506c953f97296d0d7f
diff --git a/src/bp/ui-admin/src/Pages/Users.js b/src/bp/ui-admin/src/Pages/Users.js index <HASH>..<HASH> 100644 --- a/src/bp/ui-admin/src/Pages/Users.js +++ b/src/bp/ui-admin/src/Pages/Users.js @@ -80,7 +80,7 @@ Password: ${payload.tempPassword}` if (window.confirm(`Are you sure you want to reset ${user.email}'s password?`)) { const { data: { payload } - } = await api.getSecured().get(`/admin/users/reset/${user.id}`) + } = await api.getSecured().get(`/admin/users/reset/${user.email}`) const message = `Your password has been reset.
replacing id for email in reset password form
botpress_botpress
train
0e6f030ffb6c65fa38b1f0b858d1b32ab24d5081
diff --git a/djangoratings/__init__.py b/djangoratings/__init__.py index <HASH>..<HASH> 100644 --- a/djangoratings/__init__.py +++ b/djangoratings/__init__.py @@ -45,27 +45,24 @@ class RatingManager(object): if is_anonymous and not self.field.allow_anonymous: raise TypeError("user must be a user, not '%r'" % (self.field.name, user)) + if is_anonymous: + user = None + defaults = dict( score = score, ip_address = ip_address, - user = is_anonymous and None or user, + user = user, ) + kwargs = dict( + content_type = self.get_content_type(), + object_id = self.instance.id, + key = self.field.key, + user = user, + ) if is_anonymous: - kwargs = dict( - content_type = self.get_content_type(), - object_id = self.instance.id, - key = self.field.key, - user = None, - ip_address = ip_address, - ) - else: - kwargs = dict( - content_type = self.get_content_type(), - object_id = self.instance.id, - key = self.field.key, - user = user, - ) + kwargs['ip_address'] = ip_address + try: rating, created = Vote.objects.get(**kwargs), False except Vote.DoesNotExist: @@ -88,18 +85,18 @@ class RatingManager(object): self.score += rating.score self.instance.save() #setattr(self.instance, self.field.name, Rating(score=self.score, votes=self.votes)) - + defaults = dict( score = self.score, votes = self.votes, ) - + kwargs = dict( content_type = self.get_content_type(), object_id = self.instance.id, key = self.field.key, ) - + try: score, created = Score.objects.get(**kwargs), False except Score.DoesNotExist:
refactored some code (DRY)
dcramer_django-ratings
train
56f4c704c542dffb29df1977d014da442b332eb4
diff --git a/spec/support/performance_helper.rb b/spec/support/performance_helper.rb index <HASH>..<HASH> 100644 --- a/spec/support/performance_helper.rb +++ b/spec/support/performance_helper.rb @@ -8,8 +8,8 @@ module PerformanceHelper def stop_profiling(profile_name = nil) result = RubyProf.stop + puts "#{profile_name} Time: #{format('%#.3g', total_time(result))}s" unless ENV.fetch('CI', false) - puts "Time: #{format('%#.3g', total_time(result))}s" if profile_name outdir = './profiles' Dir.mkdir(outdir) unless Dir.exist?(outdir)
Print time taken to the log in CI as well as locally.
envato_double_entry
train
5800ea0bf3bd719090bc8f062981b3ae3836fcec
diff --git a/lib/sprockets/sass_template.rb b/lib/sprockets/sass_template.rb index <HASH>..<HASH> 100644 --- a/lib/sprockets/sass_template.rb +++ b/lib/sprockets/sass_template.rb @@ -11,13 +11,15 @@ module Sprockets new.call(*args) end - def initialize + def initialize(options = {}) unless ::Sass::Script::Functions < Sprockets::SassFunctions # Install custom functions. It'd be great if this didn't need to # be installed globally, but could be passed into Engine as an # option. ::Sass::Script::Functions.send :include, Sprockets::SassFunctions end + + @cache_version = options[:cache_version] end def call(input) @@ -26,7 +28,7 @@ module Sprockets options = { filename: input[:filename], syntax: self.class.syntax, - cache_store: SassCacheStore.new(input[:cache]), + cache_store: SassCacheStore.new(input[:cache], @cache_version), load_paths: input[:environment].paths, sprockets: { context: context, @@ -56,16 +58,16 @@ module Sprockets class SassCacheStore < ::Sass::CacheStores::Base VERSION = '1' - def initialize(cache) - @cache = cache + def initialize(cache, version) + @cache, @version = cache, "#{VERSION}/#{version}" end def _store(key, version, sha, contents) - @cache._set("#{VERSION}/#{version}/#{key}/#{sha}", contents) + @cache._set("#{@version}/#{version}/#{key}/#{sha}", contents) end def _retrieve(key, version, sha) - @cache._get("#{VERSION}/#{version}/#{key}/#{sha}") + @cache._get("#{@version}/#{version}/#{key}/#{sha}") end def path_to(key)
Allow custom cache key version to be passed to sass template
rails_sprockets
train
28989568f3da32c3f3283d7b92b0912bc26b5c64
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,8 @@ # Changelog -#### 2.1.0-beta +#### 2.1.0 -* [Doctrine2][Symfony2] em_service config option moved to Symfony2 module *2015-06-03* +* [Doctrine2][Symfony2] `symfony_em_service` config option moved from Doctrine2 to Symfony2 module and renamed to `em_service` *2015-06-03* * [PhpBrowser][Frameworks] Fixed cloning form nodes Codeception\Lib\InnerBrowser::getFormFromCrawler(): ID XXX already defined *2015-05-13* * **PSR-4**: all support classes moved to `tests/_support` by default. Actors, Helpers, PageObjects, StepObjects, GroupObjects to follow PSR-4 naming style. Autoloader implemented by @splinter89. * **Dependency Injection**: support classes can be injected into tests. Support classes can be injected into each other too. This happens by implementing method `_inject` and explicitly specifying class names as parameters. Implemented by @splinter89. diff --git a/src/Codeception/Module/Doctrine2.php b/src/Codeception/Module/Doctrine2.php index <HASH>..<HASH> 100644 --- a/src/Codeception/Module/Doctrine2.php +++ b/src/Codeception/Module/Doctrine2.php @@ -30,7 +30,6 @@ use Codeception\Lib\Interfaces\DoctrineProvider; * * auto_connect: true - tries to get EntityManager through connected frameworks. If none found expects the $em values specified as described above. * * cleanup: true - all doctrine queries will be run in transaction, which will be rolled back at the end of test. * * connection_callback: - callable that will return an instance of EntityManager. This is a must if you run Doctrine without Zend2 or Symfony2 frameworks - * * symfony_em_service: 'doctrine.orm.entity_manager' - use the stated EntityManager (optional). * * ### Example (`functional.suite.yml`) * @@ -48,7 +47,7 @@ use Codeception\Lib\Interfaces\DoctrineProvider; class Doctrine2 extends \Codeception\Module implements DependsOnModule { - protected $config = ['cleanup' => true, 'connection_callback' => false, 'symfony_em_service' => 'doctrine.orm.entity_manager']; + protected $config = ['cleanup' => true, 'connection_callback' => false]; protected $dependencyMessage = <<<EOF Provide connection_callback function to establish database connection and get Entity Manager: diff --git a/src/Codeception/Module/Symfony2.php b/src/Codeception/Module/Symfony2.php index <HASH>..<HASH> 100644 --- a/src/Codeception/Module/Symfony2.php +++ b/src/Codeception/Module/Symfony2.php @@ -29,8 +29,8 @@ use Symfony\Component\HttpKernel\Exception\HttpException; * * app_path: 'app' - specify custom path to your app dir, where bootstrap cache and kernel interface is located. * * environment: 'local' - environment used for load kernel * * debug: true - turn on/off debug mode - * - * + * * em_service: 'doctrine.orm.entity_manager' - use the stated EntityManager to pair with Doctrine Module. + * * * ### Example (`functional.suite.yml`) - Symfony 2.x Directory Structure * * modules: @@ -45,6 +45,7 @@ use Symfony\Component\HttpKernel\Exception\HttpException; * * app_path: 'app' - specify custom path to your app dir, where the kernel interface is located. * * var_path: 'var' - specify custom path to your var dir, where bootstrap cache is located. * * environment: 'local' - environment used for load kernel + * * em_service: 'doctrine.orm.entity_manager' - use the stated EntityManager to pair with Doctrine Module. * * debug: true - turn on/off debug mode * * ### Example (`functional.suite.yml`) - Symfony 3 Directory Structure @@ -76,7 +77,13 @@ class Symfony2 extends \Codeception\Lib\Framework implements DoctrineProvider */ public $container; - public $config = ['app_path' => 'app', 'var_path' => 'app', 'environment' => 'test', 'debug' => true]; + public $config = [ + 'app_path' => 'app', + 'var_path' => 'app', + 'environment' => 'test', + 'debug' => true, + 'em_service' => 'doctrine.orm.entity_manager' + ]; /** * @var @@ -109,12 +116,12 @@ class Symfony2 extends \Codeception\Lib\Framework implements DoctrineProvider public function _getEntityManager() { $this->kernel->boot(); - if (!$this->kernel->getContainer()->has('doctrine')) { + if (!$this->kernel->getContainer()->has($this->config['em_service'])) { return null; } - $this->client->persistentServices[] = 'doctrine.orm.entity_manager'; + $this->client->persistentServices[] = $this->config['em_service']; $this->client->persistentServices[] = 'doctrine.orm.default_entity_manager'; - return $this->kernel->getContainer()->get('doctrine.orm.entity_manager'); + return $this->kernel->getContainer()->get($this->config['em_service']); } /**
moved em_service from Doctrine2 to Symfony2 module
Codeception_Codeception
train
ee39ceb65b89bc35cab5e01c454bc205d0892784
diff --git a/lib/upnp/control_point/device.rb b/lib/upnp/control_point/device.rb index <HASH>..<HASH> 100644 --- a/lib/upnp/control_point/device.rb +++ b/lib/upnp/control_point/device.rb @@ -232,6 +232,7 @@ module UPnP def extract_description(ddf) log "<#{self.class}> Extracting basic attributes from description..." + @device_type = ddf[:deviceType] || '' @friendly_name = ddf[:friendlyName] || '' @manufacturer = ddf[:manufacturer] || '' @manufacturer_url = ddf[:manufacturerURL] || '' @@ -239,12 +240,26 @@ module UPnP @model_name = ddf[:modelName] || '' @model_number = ddf[:modelNumber] || '' @model_url = ddf[:modelURL] || '' - @presentation_url = ddf[:presentationURL] || '' @serial_number = ddf[:serialNumber] || '' + @udn = ddf[:UDN] || '' + @upc = ddf[:UPC] || '' + @icon_list = extract_icons(ddf[:iconList]) + @presentation_url = ddf[:presentationURL] || '' log "<#{self.class}> Basic attributes extracted." end + # @return [Array<Hash>] + def extract_icons(ddf_icon_list) + ddf_icon_list.map do |icon, values| + values[:url] = unless URI(values[:url]).scheme + @url_base + values[:url] + end + puts "values url #{values[:url]}" + values + end || [] + end + def extract_devices(group_device_extractor) log "<#{self.class}> Extracting child devices for #{self.object_id} using #{group_device_extractor.object_id}"
Added extraction of missing basic description attribs
turboladen_playful
train
2965e285d8fd4aa9346157984b6812ece7f80175
diff --git a/errors.go b/errors.go index <HASH>..<HASH> 100644 --- a/errors.go +++ b/errors.go @@ -180,20 +180,28 @@ func Appendf(e error, format string, args ...interface{}) Error { } // Check whether e is equal to or wraps the original, at any depth -func Is(e error, original error) bool { - for { - if e == original { - return true - } - if e == nil || original == nil { - return false +func Is(e error, originals ...error) bool { + is := func(e, original error) bool { + for { + if e == original { + return true + } + if e == nil || original == nil { + return false + } + w, ok := e.(*merryErr) + if !ok { + return false + } + e = w.err } - w, ok := e.(*merryErr) - if !ok { - return false + } + for _, o := range originals { + if is(e, o) { + return true } - e = w.err } + return false } // Return the innermost underlying error.
Allow Is to test against a set of errors
ansel1_merry
train
ef2deddbc15bb33ca70a57504b7261a4d03642b6
diff --git a/isort/isort.py b/isort/isort.py index <HASH>..<HASH> 100644 --- a/isort/isort.py +++ b/isort/isort.py @@ -452,9 +452,18 @@ class SortImports(object): """ sort_ignore_case = self.config.get('force_alphabetical_sort', False) + sections = itertools.chain(self.sections, self.config['forced_separate']) + + sections = itertools.chain(self.sections, self.config['forced_separate']) + if self.config.get('no_sections', False): + self.imports['no_sections'] = {'straight': [], 'from': {}} + for section in sections: + self.imports['no_sections']['straight'].extend(self.imports[section].get('straight', [])) + self.imports['no_sections']['from'].update(self.imports[section].get('from', {})) + sections = ('no_sections', ) output = [] - for section in itertools.chain(self.sections, self.config['forced_separate']): + for section in sections: straight_modules = list(self.imports[section]['straight']) straight_modules = nsorted(straight_modules, key=lambda key: self._module_key(key, self.config)) from_modules = sorted(list(self.imports[section]['from'].keys())) @@ -463,9 +472,13 @@ class SortImports(object): section_output = [] if self.config.get('from_first', False): self._add_from_imports(from_modules, section, section_output, sort_ignore_case) + if self.config.get('lines_between_types', 0) and from_modules and straight_modules: + section_output.extend([''] * self.config['lines_between_types']) self._add_straight_imports(straight_modules, section, section_output) else: self._add_straight_imports(straight_modules, section, section_output) + if self.config.get('lines_between_types', 0) and from_modules and straight_modules: + section_output.extend([''] * self.config['lines_between_types']) self._add_from_imports(from_modules, section, section_output, sort_ignore_case) if self.config.get('force_sort_within_sections', False): diff --git a/test_isort.py b/test_isort.py index <HASH>..<HASH> 100644 --- a/test_isort.py +++ b/test_isort.py @@ -1766,3 +1766,22 @@ def test_function_with_docstring(): ' """ Single line triple quoted doctring """\n' ' pass\n') assert SortImports(file_contents=test_input, add_imports=add_imports).output == expected_output + + +def test_alphabetic_sorting(): + """Test to ensure isort correctly handles top of file comments""" + test_input = ("from django.contrib.gis.geos import GEOSException\n" + "from plone.app.testing import getRoles\n" + "from plone.app.testing import ManageRoles\n" + "from plone.app.testing import setRoles\n" + "from Products.CMFPlone import utils\n" + "\n" + "import ABC\n" + "import unittest\n" + "import Zope\n") + options = {'force_single_line': True, + 'force_alphabetical_sort': True, + 'no_sections': True, + 'lines_between_types': 1, + 'from_first': True} + assert SortImports(file_contents=test_input, **options).output == test_input
Add support for Plone style imports
timothycrosley_isort
train
b59e684c05bfc83573baf97f5f3bb73c41eb09b0
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -46,7 +46,7 @@ module.exports = function(grunt) { }, pkg: pkg, gitinfo: {}, - browserify: require('./grunt/tasks/browserify').task(), + browserify: require('./grunt/tasks/browserify').task(grunt), s3: require('./grunt/tasks/s3').task(grunt, config), prompt: require('./grunt/tasks/prompt').task(grunt, config), replace: require('./grunt/tasks/replace').task(grunt, config), diff --git a/grunt/tasks/browserify.js b/grunt/tasks/browserify.js index <HASH>..<HASH> 100644 --- a/grunt/tasks/browserify.js +++ b/grunt/tasks/browserify.js @@ -1,10 +1,4 @@ -var bannerStr = function(dest) { - return [ - "// cartodb.js version: <%= grunt.config.get('bump.version') %>", - "// uncompressed version: " + dest, - "// sha: <%= gitinfo.local.branch.current.SHA %>" - ].join("\n") -}; +var path = require('path'); var bundles = { @@ -27,9 +21,6 @@ var bundles = { }, cartodb: { - options: { - banner: bannerStr('cartodb.uncompressed.js') - }, src: 'src-browserify/cartodb.js', dest: '<%= config.dist %>/cartodb.uncompressed.js' }, @@ -43,7 +34,12 @@ var bundles = { }; module.exports = { - task: function() { + task: function(grunt) { + // from https://github.com/substack/browser-pack/blob/aadeabea66feac48193d27d233daf1c85209357e/index.js#L11 + var defaultPreludePath = grunt.file.read( + path.join('node_modules', 'browserify', 'node_modules', 'browser-pack', '_prelude.js') + ); + var cfg = {}; for (var name in bundles) { var bundle = cfg[name] = bundles[name]; @@ -55,8 +51,15 @@ module.exports = { transform: [], watch: '<%= config.doWatchify %>', browserifyOptions: { - debug: true // to generate source maps - } + debug: true, // to generate source maps + // Append the default prelude with the header, required for source-maps to match original code + prelude: [ + "// cartodb.js version: <%= grunt.config.get('bump.version') %>", + '// uncompressed version: cartodb.uncompressed.js', + "// sha: <%= grunt.config.get('gitinfo').local.branch.current.SHA %>", + defaultPreludePath + ].join("\n") + }, }; for (var key in defaultOptions) { var value = defaultOptions[key];
Fix banner source-maps being wrongly offset Prepend the default prelude which is used by browser-pack (<URL>) so source-maps matches real source code
CartoDB_carto.js
train
5c5c633beeb85d385ef3eddb32d61555902e1946
diff --git a/instaloader/instaloader.py b/instaloader/instaloader.py index <HASH>..<HASH> 100644 --- a/instaloader/instaloader.py +++ b/instaloader/instaloader.py @@ -701,6 +701,8 @@ class Instaloader: """ Download the Posts returned by given Post Iterator. + ..versionadded:: 4.4 + :param posts: Post Iterator to loop through. :param target: Target name :param fast_update: :option:`--fast-update` @@ -722,9 +724,14 @@ class Instaloader: end="", flush=True) else: self.context.log("[{:3d}] ".format(number + 1), end="", flush=True) - if post_filter is not None and not post_filter(post): - self.context.log("{} skipped".format(post)) - continue + if post_filter is not None: + try: + if not post_filter(post): + self.context.log("{} skipped".format(post)) + continue + except (InstaloaderException, KeyError, TypeError) as err: + self.context.error("{} skipped. Filter evaluation failed: {}".format(post, err)) + continue with self.context.error_catcher("Download {} of {}".format(post, target)): # The PostChangedException gets raised if the Post's id/shortcode changed while obtaining # additional metadata. This is most likely the case if a HTTP redirect takes place while
Catch Exceptions raised during filter evaluation Closes #<I>.
instaloader_instaloader
train
7050045dea34dc80d73f2870a9e2b36d28749cfa
diff --git a/test/test.js b/test/test.js index <HASH>..<HASH> 100644 --- a/test/test.js +++ b/test/test.js @@ -837,10 +837,12 @@ describe('struct', function () { return this.area() * this.l; }; - (func.is(Rectangle.prototype.area)); - (Nil.is(Rectangle.prototype.volume)); - (func.is(Cube.prototype.area)); - (func.is(Cube.prototype.volume)); + assert('function' === typeof Rectangle.prototype.area); + assert('function' === typeof Cube.prototype.area); + assert(undefined === Rectangle.prototype.volume); + assert('function' === typeof Cube.prototype.volume); + assert(Cube.prototype.constructor !== Rectangle.prototype.constructor); + var c = new Cube({w:2, h:2, l:2}); eq(c.volume(), 8);
test: fixed typo and added test for prototype.constructor
gcanti_tcomb
train
7f4f8b14093ce0259673c1e4bef7b6aad86a8b37
diff --git a/api/auth.go b/api/auth.go index <HASH>..<HASH> 100644 --- a/api/auth.go +++ b/api/auth.go @@ -344,7 +344,7 @@ func removeUser(w http.ResponseWriter, r *http.Request, t auth.Token) error { return err } email := r.URL.Query().Get("user") - if email != "" { + if email != "" && u.Email != email { if !permission.Check(t, permission.PermUserDelete) { return permission.ErrUnauthorized } diff --git a/api/auth_test.go b/api/auth_test.go index <HASH>..<HASH> 100644 --- a/api/auth_test.go +++ b/api/auth_test.go @@ -1092,6 +1092,31 @@ func (s *AuthSuite) TestRemoveUser(c *check.C) { c.Assert(users, check.DeepEquals, []string{s.user.Email}) } +func (s *AuthSuite) TestRemoveUserProvidingOwnEmail(c *check.C) { + conn, _ := db.Conn() + defer conn.Close() + u := auth.User{Email: "her-voices@painofsalvation.com", Password: "123456"} + _, err := nativeScheme.Create(&u) + c.Assert(err, check.IsNil) + defer conn.Users().Remove(bson.M{"email": u.Email}) + token, err := nativeScheme.Login(map[string]string{"email": u.Email, "password": "123456"}) + c.Assert(err, check.IsNil) + defer conn.Tokens().Remove(bson.M{"token": token.GetValue()}) + request, err := http.NewRequest("DELETE", "/users?user="+u.Email, nil) + c.Assert(err, check.IsNil) + recorder := httptest.NewRecorder() + err = removeUser(recorder, request, token) + c.Assert(err, check.IsNil) + n, err := conn.Users().Find(bson.M{"email": u.Email}).Count() + c.Assert(err, check.IsNil) + c.Assert(n, check.Equals, 0) + action := rectest.Action{Action: "remove-user", User: u.Email} + c.Assert(action, rectest.IsRecorded) + users := repositorytest.Users() + sort.Strings(users) + c.Assert(users, check.DeepEquals, []string{s.user.Email}) +} + func (s *AuthSuite) TestRemoveAnotherUser(c *check.C) { conn, _ := db.Conn() defer conn.Close()
api/auth: allow users to remove their own account providing the email Currently, tsuru-client always provides the email, even when the users are removing theirselves.
tsuru_tsuru
train
eeba128f8abae40d87465ed69ec3b9740d47fbb3
diff --git a/tasks/build_task.js b/tasks/build_task.js index <HASH>..<HASH> 100644 --- a/tasks/build_task.js +++ b/tasks/build_task.js @@ -44,6 +44,7 @@ module.exports = function(grunt) { grunt.config('copy.backend_files', { expand: true, src: ['conf/*', 'vendor/**/*', '!conf/grafana.dev.ini'], + options: { mode: true}, dest: '<%= tempDir %>' }); grunt.task.run('copy:dist_to_tmp');
Fixed release tar/zip keeping execution mode on phantomjs
grafana_grafana
train
afd4d6afca124571ca438f0236fe60e8006492e2
diff --git a/src/GitHub_Updater/Basic_Auth_Loader.php b/src/GitHub_Updater/Basic_Auth_Loader.php index <HASH>..<HASH> 100644 --- a/src/GitHub_Updater/Basic_Auth_Loader.php +++ b/src/GitHub_Updater/Basic_Auth_Loader.php @@ -244,8 +244,8 @@ class Basic_Auth_Loader { * @return array $args */ public function http_release_asset_auth( $args, $url ) { - $arrURL = parse_url( $url ); - if ( isset( $arrURL['host'] ) && 'bbuseruploads.s3.amazonaws.com' === $arrURL['host'] ) { + $arr_url = parse_url( $url ); + if ( isset( $arr_url['host'] ) && 'bbuseruploads.s3.amazonaws.com' === $arr_url['host'] ) { unset( $args['headers']['Authorization'] ); }
Adjusted variable name to comply with WP standards.
afragen_github-updater
train
708820e91c0c37d993efd50b5d395c9a07fbc42d
diff --git a/neutronclient/neutron/v2_0/__init__.py b/neutronclient/neutron/v2_0/__init__.py index <HASH>..<HASH> 100644 --- a/neutronclient/neutron/v2_0/__init__.py +++ b/neutronclient/neutron/v2_0/__init__.py @@ -91,7 +91,7 @@ def find_resourceid_by_name_or_id(client, resource, name_or_id): def add_show_list_common_argument(parser): parser.add_argument( '-D', '--show-details', - help=_('Show detailed info.'), + help=_('Show detailed information.'), action='store_true', default=False, ) parser.add_argument( @@ -356,7 +356,7 @@ class NeutronCommand(command.OpenStackCommand): parser = super(NeutronCommand, self).get_parser(prog_name) parser.add_argument( '--request-format', - help=_('The xml or json request format.'), + help=_('The XML or JSON request format.'), default='json', choices=['json', 'xml', ], ) parser.add_argument( diff --git a/neutronclient/neutron/v2_0/vpn/ipsec_site_connection.py b/neutronclient/neutron/v2_0/vpn/ipsec_site_connection.py index <HASH>..<HASH> 100644 --- a/neutronclient/neutron/v2_0/vpn/ipsec_site_connection.py +++ b/neutronclient/neutron/v2_0/vpn/ipsec_site_connection.py @@ -34,7 +34,7 @@ def _format_peer_cidrs(ipsec_site_connection): class ListIPsecSiteConnection(neutronv20.ListCommand): - """List IPsecSiteConnections that belong to a given tenant.""" + """List IPsec site connections that belong to a given tenant.""" resource = 'ipsec_site_connection' log = logging.getLogger(__name__ + '.ListIPsecSiteConnection') @@ -47,7 +47,7 @@ class ListIPsecSiteConnection(neutronv20.ListCommand): class ShowIPsecSiteConnection(neutronv20.ShowCommand): - """Show information of a given IPsecSiteConnection.""" + """Show information of a given IPsec site connection.""" resource = 'ipsec_site_connection' log = logging.getLogger(__name__ + '.ShowIPsecSiteConnection') @@ -162,7 +162,7 @@ class CreateIPsecSiteConnection(neutronv20.CreateCommand): class UpdateIPsecSiteConnection(neutronv20.UpdateCommand): - """Update a given IPsecSiteConnection.""" + """Update a given IPsec site connection.""" resource = 'ipsec_site_connection' log = logging.getLogger(__name__ + '.UpdateIPsecSiteConnection') @@ -173,7 +173,7 @@ class UpdateIPsecSiteConnection(neutronv20.UpdateCommand): '--dpd', metavar="action=ACTION,interval=INTERVAL,timeout=TIMEOUT", type=utils.str2dict, - help=vpn_utils.dpd_help("IPsec connection")) + help=vpn_utils.dpd_help("IPsec connection.")) def args2body(self, parsed_args): body = {'ipsec_site_connection': { @@ -186,7 +186,7 @@ class UpdateIPsecSiteConnection(neutronv20.UpdateCommand): class DeleteIPsecSiteConnection(neutronv20.DeleteCommand): - """Delete a given IPsecSiteConnection.""" + """Delete a given IPsec site connection.""" resource = 'ipsec_site_connection' log = logging.getLogger(__name__ + '.DeleteIPsecSiteConnection')
Some edits for help strings Some edits for neutron help strings as noticed by Lana during review of this patch: <URL>
rackerlabs_rackspace-python-neutronclient
train
c5541ba049e8377bfad5b61e4f841df76f0c19ea
diff --git a/dscan/plugins/internal/base_plugin_internal.py b/dscan/plugins/internal/base_plugin_internal.py index <HASH>..<HASH> 100644 --- a/dscan/plugins/internal/base_plugin_internal.py +++ b/dscan/plugins/internal/base_plugin_internal.py @@ -23,6 +23,12 @@ def handle_interrupt(signal, stack): signal.signal(signal.SIGINT, handle_interrupt) +# https://github.com/kennethreitz/requests/issues/2214 +try: + requests.packages.urllib3.disable_warnings() +except: + pass + class BasePluginInternal(controller.CementBaseController): requests = None out = None
Remove super annoying warning by urllib3.
droope_droopescan
train
4a20aea828abf06e334d47eb7caab1e1a5e59693
diff --git a/test/errors-component-spec.js b/test/errors-component-spec.js index <HASH>..<HASH> 100644 --- a/test/errors-component-spec.js +++ b/test/errors-component-spec.js @@ -105,11 +105,7 @@ describe('<Errors />', () => { </Provider> ); - const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); - const errors = TestUtils.scryRenderedDOMComponentsWithTag(form, 'span'); - it('should display all errors', () => { - const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); const errors = TestUtils.scryRenderedDOMComponentsWithTag(form, 'span'); assert.lengthOf(errors, 2); assert.equal(errors[0].innerHTML, 'This field is required'); @@ -117,6 +113,52 @@ describe('<Errors />', () => { }); }); + describe('displaying errors from form .errors', () => { + const store = applyMiddleware(thunk)(createStore)(combineReducers({ + testForm: formReducer('test', {}), + test: modelReducer('test'), + })); + + let formValid = false; + + const form = TestUtils.renderIntoDocument( + <Provider store={store}> + <Form model="test" + validators={{ + '': { foo: ({ foo }) => foo && foo.length }, + }} + > + <Errors model="test" + messages={{ + foo: 'This form is invalid', + }} + /> + <Field model="test.foo"> + <input type="text" /> + </Field> + </Form> + </Provider> + ); + + const errors = TestUtils.scryRenderedDOMComponentsWithTag(form, 'span'); + const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input'); + + it('should display all form errors', () => { + const errors = TestUtils.scryRenderedDOMComponentsWithTag(form, 'span'); + assert.lengthOf(errors, 1); + assert.equal(errors[0].innerHTML, 'This form is invalid'); + }); + + it('should not display form errors if form is valid', () => { + input.value = 'testing'; + + TestUtils.Simulate.change(input); + + const errors = TestUtils.scryRenderedDOMComponentsWithTag(form, 'span'); + assert.lengthOf(errors, 0); + }); + }); + describe('displaying custom messages', () => { const store = applyMiddleware(thunk)(createStore)(combineReducers({ testForm: formReducer('test', {}),
Adding unit tests for supporting form errors in <Errors>
davidkpiano_react-redux-form
train
8145fe18e361b94459da3aa63180e1e385a775e3
diff --git a/cas-server-support-saml/src/main/java/org/jasig/cas/support/saml/util/Saml10ObjectBuilder.java b/cas-server-support-saml/src/main/java/org/jasig/cas/support/saml/util/Saml10ObjectBuilder.java index <HASH>..<HASH> 100644 --- a/cas-server-support-saml/src/main/java/org/jasig/cas/support/saml/util/Saml10ObjectBuilder.java +++ b/cas-server-support-saml/src/main/java/org/jasig/cas/support/saml/util/Saml10ObjectBuilder.java @@ -62,6 +62,11 @@ public final class Saml10ObjectBuilder extends AbstractSamlObjectBuilder { private static final String CONFIRMATION_METHOD = "urn:oasis:names:tc:SAML:1.0:cm:artifact"; /** + * Encoder to wrap the saml response in a SOAP envelope. + */ + private final HTTPSOAP11Encoder encoder = new CasHTTPSOAP11Encoder(); + + /** * Create a new SAML response object. * @param id the id * @param issueInstant the issue instant @@ -169,15 +174,27 @@ public final class Saml10ObjectBuilder extends AbstractSamlObjectBuilder { } /** - * New subject element. + * New subject element that uses the confirmation method + * {@link #CONFIRMATION_METHOD}. * * @param identifier the identifier * @return the subject */ public Subject newSubject(final String identifier) { + return newSubject(identifier, CONFIRMATION_METHOD); + } + + /** + * New subject element with given confirmation method. + * + * @param identifier the identifier + * @param confirmationMethod the confirmation method + * @return the subject + */ + public Subject newSubject(final String identifier, final String confirmationMethod) { final SubjectConfirmation confirmation = newSamlObject(SubjectConfirmation.class); final ConfirmationMethod method = newSamlObject(ConfirmationMethod.class); - method.setConfirmationMethod(CONFIRMATION_METHOD); + method.setConfirmationMethod(confirmationMethod); confirmation.getConfirmationMethods().add(method); final NameIdentifier nameIdentifier = newSamlObject(NameIdentifier.class); nameIdentifier.setNameIdentifier(identifier); @@ -240,8 +257,6 @@ public final class Saml10ObjectBuilder extends AbstractSamlObjectBuilder { messageContext.setOutboundMessageTransport( new HttpServletResponseAdapter(httpResponse, httpRequest.isSecure())); messageContext.setOutboundSAMLMessage(samlMessage); - - final HTTPSOAP11Encoder encoder = new CasHTTPSOAP11Encoder(); - encoder.encode(messageContext); + this.encoder.encode(messageContext); } }
moved encoder up; added overloaded method for confirmation method
apereo_cas
train
f54265e9a57f1a3ca4acd334008ab1a0276c2ebf
diff --git a/packages/button/src/react/index.js b/packages/button/src/react/index.js index <HASH>..<HASH> 100644 --- a/packages/button/src/react/index.js +++ b/packages/button/src/react/index.js @@ -104,9 +104,10 @@ renderIcon.propTypes = { icon: PropTypes.element } -const Button = React.forwardRef((props, ref) => { +const Button = React.forwardRef((props, forwardedRef) => { const themeName = useTheme() - if (!ref) ref = React.useRef() + const ref = React.useRef() + React.useImperativeHandle(forwardedRef, () => ref.current) const nonLoadingWidth = React.useMemo(() => { if (props.loading && ref && ref.current) { return ref.current.offsetWidth diff --git a/packages/link/src/react/index.js b/packages/link/src/react/index.js index <HASH>..<HASH> 100644 --- a/packages/link/src/react/index.js +++ b/packages/link/src/react/index.js @@ -19,7 +19,8 @@ const style = ({ appearance, themeName }) => ) const Link = React.forwardRef((props, forwardedRef) => { - const ref = forwardedRef || React.useRef() + const ref = React.useRef() + React.useImperativeHandle(forwardedRef, () => ref.current) const themeName = useTheme() let tagName = 'a' diff --git a/packages/viewtoggle/src/react/index.js b/packages/viewtoggle/src/react/index.js index <HASH>..<HASH> 100644 --- a/packages/viewtoggle/src/react/index.js +++ b/packages/viewtoggle/src/react/index.js @@ -30,7 +30,8 @@ const styles = { } const ViewToggle = React.forwardRef(({ onSelect, ...props }, forwardedRef) => { - const ref = forwardedRef || React.useRef() + const ref = React.useRef() + React.useImperativeHandle(forwardedRef, () => ref.current) const themeName = useTheme() const hasRenderedOnce = useHasRenderedOnce()
fix: removes conditional uses of useRef
pluralsight_design-system
train
12a82237d5764bc0be21d6df0c4f442a2a0646fc
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -136,8 +136,7 @@ export default class InputNumber extends React.Component { if (selectionRange && typeof selectionRange === 'function' && this.start !== undefined && - this.end !== undefined && - this.start !== this.end) { + this.end !== undefined) { this.input.setSelectionRange(this.start, this.end); } else { this.focus();
Keep cursor position when focus input-number close ant-design/ant-design#<I> the code removed in this commit was added at <URL>
react-component_input-number
train
fc66283175a5512d56e50a63f62dfbdf129e44f1
diff --git a/app/transitions/fly-to.js b/app/transitions/fly-to.js index <HASH>..<HASH> 100644 --- a/app/transitions/fly-to.js +++ b/app/transitions/fly-to.js @@ -11,15 +11,26 @@ export default function flyTo(opts={}) { var oldOffset = this.oldElement.offset(); var newOffset = this.newElement.offset(); - var motion = { - translateX: newOffset.left - oldOffset.left, - translateY: newOffset.top - oldOffset.top, - outerWidth: this.newElement.outerWidth(), - outerHeight: this.newElement.outerHeight() - }; - this.newElement.css({ visibility: 'hidden' }); - return animate(this.oldElement, motion, opts).then(() => { - this.newElement.css({ visibility: ''}); - }); + if (opts.movingSide === 'new') { + let motion = { + translateX: [0, oldOffset.left - newOffset.left], + translateY: [0, oldOffset.top - newOffset.top], + outerWidth: [this.newElement.outerWidth(), this.oldElement.outerWidth()], + outerHeight: [this.newElement.outerHeight(), this.oldElement.outerHeight()] + }; + this.oldElement.css({ visibility: 'hidden' }); + return animate(this.newElement, motion, opts); + } else { + let motion = { + translateX: newOffset.left - oldOffset.left, + translateY: newOffset.top - oldOffset.top, + outerWidth: this.newElement.outerWidth(), + outerHeight: this.newElement.outerHeight() + }; + this.newElement.css({ visibility: 'hidden' }); + return animate(this.oldElement, motion, opts).then(() => { + this.newElement.css({ visibility: ''}); + }); + } }
new `movingSide` option on the fly-to transition This lets you pick whether the old or new element will be the one that animates. The motion is the same either way (always from the position & size of the old element to the position and size of the new element). But the content of the moving element will vary.
ember-animation_liquid-fire
train
1285f01be63e5bddd1cc6dc821d040b57058a4ee
diff --git a/lib/slimmer/tag_mover.rb b/lib/slimmer/tag_mover.rb index <HASH>..<HASH> 100644 --- a/lib/slimmer/tag_mover.rb +++ b/lib/slimmer/tag_mover.rb @@ -16,9 +16,11 @@ module Slimmer end.compact.sort end - def wrap_node(node) - wrap = node.delete('slimmer-wrap-with') - "<!--[if #{wrap}]>-->#{node.to_s}<!--<![endif]-->" + def wrap_node(src, node) + if node.previous_sibling.to_s =~ /<!--\[if[^\]]+\]>-->/ and node.next_sibling.to_s == '<!--<![endif]-->' + node = Nokogiri::XML::NodeSet.new(src, [node.previous_sibling, node, node.next_sibling]) + end + node end def move_tags(src, dest, type, opts) @@ -30,10 +32,8 @@ module Slimmer src.css(type).each do |node| if include_tag?(node, min_attrs) && !already_there.include?(tag_fingerprint(node, comparison_attrs)) + node = wrap_node(src, node) node.remove - if node['slimmer-wrap-with'] - node = wrap_node(node) - end dest.at_xpath('/html/head') << node end end diff --git a/test/typical_usage_test.rb b/test/typical_usage_test.rb index <HASH>..<HASH> 100644 --- a/test/typical_usage_test.rb +++ b/test/typical_usage_test.rb @@ -134,7 +134,7 @@ module TypicalUsage given_response 200, %{ <html> <head> - <!--[if gt IE 8]>--><link href="app.css" rel="stylesheet" type="text/css" slimmer-wrap-with="gt IE 8"><!--<![endif]--> + <!--[if gt IE 8]>--><link href="app.css" rel="stylesheet" type="text/css"><!--<![endif]--> </head> </html> }
Work out if tag is wrapped by comment dynamically Using a propriatory attribute was fragile and crufty. Now looks at the previous and next node in the tree and copies the whole block over to the template if they match a conditional comment.
alphagov_slimmer
train
5b2326a93c1c926ee0c302f57e46edabf8638fc7
diff --git a/spec/unit/provider/user_spec.rb b/spec/unit/provider/user_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/provider/user_spec.rb +++ b/spec/unit/provider/user_spec.rb @@ -452,11 +452,20 @@ describe Chef::Provider::User do it "should raise an error if we can't translate the group name during resource assertions" do expect(Etc).to receive(:getgrnam).and_raise(ArgumentError) + @provider.action = :create @provider.define_resource_requirements @provider.convert_group_name expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::User) end + it "does not raise an error if we can't translate the group name during resource assertions if we are removing the user" do + expect(Etc).to receive(:getgrnam).and_raise(ArgumentError) + @provider.action = :remove + @provider.define_resource_requirements + @provider.convert_group_name + expect { @provider.process_resource_requirements }.not_to raise_error + end + it "should set the new resources gid to the integerized version if available" do expect(Etc).to receive(:getgrnam).with("999").and_return(@group) @provider.convert_group_name
Add recommended test from btm
chef_chef
train
2267236970abae693e470e1a006e6049518c9c7b
diff --git a/demo/index.html b/demo/index.html index <HASH>..<HASH> 100644 --- a/demo/index.html +++ b/demo/index.html @@ -11,6 +11,7 @@ <title>Demo</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> + <link href='https://fonts.googleapis.com/css?family=Poppins' rel='stylesheet' type='text/css'> </head> <body> <!--[if lt IE 8]> diff --git a/src/components/helper-methods.js b/src/components/helper-methods.js index <HASH>..<HASH> 100644 --- a/src/components/helper-methods.js +++ b/src/components/helper-methods.js @@ -12,9 +12,9 @@ export default { } }, - getBaseProps(props, defaultStyles) { - defaultStyles = props.theme && props.theme.pie ? props.theme.pie : defaultStyles; - const calculatedValues = this.getCalculatedValues(props, defaultStyles); + getBaseProps(props, defaultStyles, defaultColorScale) { + defaultStyles = props.theme && props.theme.pie ? props.theme.pie.style : defaultStyles; + const calculatedValues = this.getCalculatedValues(props, defaultStyles, defaultColorScale); const { slices, style, pathFunction, colors, labelPosition } = calculatedValues; return slices.reduce((memo, slice, index) => { const datum = slice.data; @@ -57,10 +57,12 @@ export default { }, {}); }, - getCalculatedValues(props, defaultStyles) { + getCalculatedValues(props, defaultStyles, defaultColorScale) { const style = Helpers.getStyles(props.style, defaultStyles, "auto", "100%"); - const colorScale = props.theme && props.theme.pie ? props.theme.pie.colorScale - : props.colorScale; + const colorScale = props.theme && props.theme.pie ? + props.colorScale || props.theme.pie.props.colorScale || defaultColorScale + : props.colorScale || defaultColorScale; + console.log(colorScale); const colors = Array.isArray(colorScale) ? colorScale : Style.getColorScale(colorScale); const padding = Helpers.getPadding(props); diff --git a/src/components/victory-pie.js b/src/components/victory-pie.js index <HASH>..<HASH> 100644 --- a/src/components/victory-pie.js +++ b/src/components/victory-pie.js @@ -27,6 +27,16 @@ const defaultStyles = { } }; +const defaultColorScale = [ + "#75C776", + "#39B6C5", + "#78CCC4", + "#62C3A4", + "#64A8D1", + "#8C95C8", + "#3BAF74" +]; + export default class VictoryPie extends React.Component { static defaultTransitions = { onExit: { @@ -312,15 +322,6 @@ export default class VictoryPie extends React.Component { cornerRadius: 0, padAngle: 0, padding: 30, - colorScale: [ - "#75C776", - "#39B6C5", - "#78CCC4", - "#62C3A4", - "#64A8D1", - "#8C95C8", - "#3BAF74" - ], startAngle: 0, standalone: true, width: 400, @@ -331,7 +332,8 @@ export default class VictoryPie extends React.Component { containerComponent: <VictoryContainer/> }; - static getBaseProps = partialRight(PieHelpers.getBaseProps.bind(PieHelpers), defaultStyles); + static getBaseProps = partialRight(PieHelpers.getBaseProps.bind(PieHelpers), + defaultStyles, defaultColorScale); constructor() { super(); @@ -342,11 +344,13 @@ export default class VictoryPie extends React.Component { } componentWillMount() { - this.baseProps = PieHelpers.getBaseProps(this.props, defaultStyles); + this.baseProps = PieHelpers.getBaseProps(this.props, + defaultStyles, defaultColorScale); } componentWillReceiveProps(newProps) { - this.baseProps = PieHelpers.getBaseProps(newProps, defaultStyles); + this.baseProps = PieHelpers.getBaseProps(newProps, + defaultStyles, defaultColorScale); } renderData(props) { @@ -404,7 +408,7 @@ export default class VictoryPie extends React.Component { ); } - const styleObject = this.props.theme && this.props.theme.pie ? this.props.theme.pie + const styleObject = this.props.theme && this.props.theme.pie ? this.props.theme.pie.style : defaultStyles; const calculatedProps = PieHelpers.getCalculatedValues(this.props, styleObject); const { style, padding, radius } = calculatedProps;
modify to accept props from a theme object for colorscheme
FormidableLabs_victory
train
6aabed2c26e6490efdeeefaea3586a0272f391b9
diff --git a/gcolor/dsatur/__init__.py b/gcolor/dsatur/__init__.py index <HASH>..<HASH> 100755 --- a/gcolor/dsatur/__init__.py +++ b/gcolor/dsatur/__init__.py @@ -98,13 +98,4 @@ def get_amount_color(node_indexes, coloring, color_number): def get_neighbors(node_index, data): - return [ index for index in range(len(data[node_index])) if data[node_index][index] != 0 ]; - - -# from support import draw_graph, read_graph; -# -# graph = read_graph(GRAPH_SIMPLE_SAMPLES.GRAPH_FULL1); -# coloring = dsatur(graph.data); -# draw_graph(graph, coloring); -# print(graph); -# print(coloring); \ No newline at end of file + return [ index for index in range(len(data[node_index])) if data[node_index][index] != 0 ]; \ No newline at end of file diff --git a/nnet/hysteresis/__init__.py b/nnet/hysteresis/__init__.py index <HASH>..<HASH> 100644 --- a/nnet/hysteresis/__init__.py +++ b/nnet/hysteresis/__init__.py @@ -174,14 +174,4 @@ class hysteresis_network(network, network_interface): if (cluster_allocated == False): clusters.append([i]); - return clusters; - - -# network = net(2, -3, -1); -# network.states[0] = 1; -# network.outputs[0] = 1; -# network.states[1] = 0; -# network.outputs[1] = 1; -# -# (t, x) = network.simulate(1000, 10); -# draw_dynamics(t, x, x_title = "Time", y_title = "x(t)"); \ No newline at end of file + return clusters; \ No newline at end of file diff --git a/nnet/som/__init__.py b/nnet/som/__init__.py index <HASH>..<HASH> 100644 --- a/nnet/som/__init__.py +++ b/nnet/som/__init__.py @@ -386,6 +386,22 @@ class som: return winner_number; + def get_density_matrix(self): + maximum_value = max(self._award); + minimum_value = min(self._award); + + difference = maximum_value - minimum_value; + if (difference == 0): difference = 1; + + density_matrix = [ [0] * self._cols for i in range(self._rows) ]; + for i in range(self._rows): + for j in range(self._cols): + neuron_index = i * self._cols + j; + density_matrix[i][j] = (self._award[neuron_index] - minimum_value) / difference; + + return density_matrix; + + def show_award(self): awards = list(); @@ -444,19 +460,18 @@ class som: if ( (self._conn_type != type_conn.func_neighbor) and (coupling != False) ): for neighbor in self._neighbors[index]: - axes.plot([self._weights[index][0], self._weights[neighbor][0]], [self._weights[index][1], self._weights[neighbor][1]], 'g', linewidth = 0.5); + if (neighbor > index): + axes.plot([self._weights[index][0], self._weights[neighbor][0]], [self._weights[index][1], self._weights[neighbor][1]], 'g', linewidth = 0.5); elif (dimension == 3): axes.scatter(self._weights[index][0], self._weights[index][1], self._weights[index][2], c = color, marker = 'o'); + if ( (self._conn_type != type_conn.func_neighbor) and (coupling != False) ): + for neighbor in self._neighbors[index]: + if (neighbor > index): + axes.plot([self._weights[index][0], self._weights[neighbor][0]], [self._weights[index][1], self._weights[neighbor][1]], [self._weights[index][2], self._weights[neighbor][2]], 'g-', linewidth = 0.5); + + plt.grid(); - plt.show(); - - -# sample = read_sample('../../samples/SampleTwoDiamonds.txt'); -# network = som(5, 5, sample, 100, type_conn.grid_four); -# network.show_network(); -# -# network.train(); -# network.show_network(); \ No newline at end of file + plt.show(); \ No newline at end of file diff --git a/nnet/som/examples.py b/nnet/som/examples.py index <HASH>..<HASH> 100644 --- a/nnet/som/examples.py +++ b/nnet/som/examples.py @@ -7,10 +7,14 @@ from samples.definitions import FCPS_SAMPLES; from support import read_sample; +import matplotlib.pyplot as plt; +from matplotlib import cm; +from pylab import *; + def template_self_organization(file, rows, cols, time, structure, init_type = type_init.uniform_grid): sample = read_sample(file); network = som(rows, cols, sample, time, structure, init_type); - network.train(); + network.train(); network.show_network(False, dataset = False); def som_sample1():
3-D representation of connections have been support for 'nnet.som'; Added method for obtaining P-matrix; Cosmetic changes
annoviko_pyclustering
train
4a83e6f453c8bf838abe00d7d6fc9b3ea2569b90
diff --git a/cmd/prometheus/main.go b/cmd/prometheus/main.go index <HASH>..<HASH> 100644 --- a/cmd/prometheus/main.go +++ b/cmd/prometheus/main.go @@ -1145,25 +1145,6 @@ func reloadConfig(filename string, expandExternalLabels, enableExemplarStorage b } } - // Perform validation for Agent-compatible configs and remove anything that's unsupported. - if agentMode { - // Perform validation for Agent-compatible configs and remove anything that's - // unsupported. - if len(conf.AlertingConfig.AlertRelabelConfigs) > 0 || len(conf.AlertingConfig.AlertmanagerConfigs) > 0 { - level.Warn(logger).Log("msg", "alerting configs not supported in agent mode") - conf.AlertingConfig.AlertRelabelConfigs = []*relabel.Config{} - conf.AlertingConfig.AlertmanagerConfigs = config.AlertmanagerConfigs{} - } - if len(conf.RuleFiles) > 0 { - level.Warn(logger).Log("msg", "recording rules not supported in agent mode") - conf.RuleFiles = []string{} - } - if len(conf.RemoteReadConfigs) > 0 { - level.Warn(logger).Log("msg", "remote_read configs not supported in agent mode") - conf.RemoteReadConfigs = []*config.RemoteReadConfig{} - } - } - failed := false for _, rl := range rls { rstart := time.Now()
Remove agent mode warnings when loading configs (#<I>) PR #<I> introduced failing to load the config file when agent mode is configured to run with unspported settings. This made the block that logs a warning on their configuration no-op, which is now removed.
prometheus_prometheus
train
07e3d90b3aea1b07110b0d8cff4e72c270cc9b6d
diff --git a/concrete/src/Page/Single.php b/concrete/src/Page/Single.php index <HASH>..<HASH> 100644 --- a/concrete/src/Page/Single.php +++ b/concrete/src/Page/Single.php @@ -135,7 +135,7 @@ class Single { $pathToFile = static::getPathToNode($cPath, $pkg); $txt = Loader::helper('text'); - $c = CorePage::getByPath("/" . $cPath); + $c = CorePage::getByPath($cPath); if ($c->isError() && $c->getError() == COLLECTION_NOT_FOUND) { // create the page at that point in the tree
Fix checking the global single page is already exists
concrete5_concrete5
train
ac5a2cf1e1267ef5be5b95b5158565a4bd885f13
diff --git a/hpcbench/api.py b/hpcbench/api.py index <HASH>..<HASH> 100644 --- a/hpcbench/api.py +++ b/hpcbench/api.py @@ -18,6 +18,19 @@ __all__ = [ Metric = namedtuple("Metric", "unit type") +class UnexpectedMetricsException(Exception): + def __init__(self, unset_metrics, metrics): + self.unset_metrics = unset_metrics + self.metrics = metrics + + def __str__(self): + error = \ + 'Could not extract some metrics: %s\n' \ + 'metrics set: %s' + return error % (', '.join(self.unset_metrics), + ', '.join(set(self.metrics))) + + class Metrics(object): # pragma pylint: disable=too-few-public-methods """List of common metrics """ @@ -80,11 +93,7 @@ class MetricsExtractor(with_metaclass(ABCMeta, object)): def _check_metrics(self, metrics): unset_metrics = set(self.metrics) - set(metrics) if any(unset_metrics): - error = \ - 'Could not extract some metrics: %s\n' \ - 'metrics set: %s' - raise Exception(error % (' ,'.join(unset_metrics), - ' ,'.join(set(metrics)))) + raise UnexpectedMetricsException(unset_metrics, metrics) @classmethod def stdout(cls, outdir):
API change: raise a dedicated exception when metric are unexpected
BlueBrain_hpcbench
train
42ccd0764b7beb801fadd7055f247be7cda0d7de
diff --git a/lib/types.js b/lib/types.js index <HASH>..<HASH> 100644 --- a/lib/types.js +++ b/lib/types.js @@ -56,6 +56,9 @@ var _types = { }, 'DATE': { format: function(value) { + if(!(value instanceof Date)) + value = new Date(value); + return value.getFullYear() +pad(value.getMonth()+1) +pad(value.getDate()); @@ -71,6 +74,9 @@ var _types = { // YYYYMMDDTHHMMSS // TODO: Support UTC and TZ values format: function(value) { + if(!(value instanceof Date)) + value = new Date(value); + return format_value('DATE', value)+'T'+format_value('TIME', value); }, parse: function(value, parameters, calendar) { @@ -157,6 +163,9 @@ var _types = { }, 'TIME': { format: function(value) { + if(!(value instanceof Date)) + value = new Date(value); + // TODO: Right now we always use pure local time // That means the timezone is ignored and times are always local return pad(value.getHours())
Date formatters will attempt to coerce data into a date object
tritech_node-icalendar
train
46f2c582493011413e58cd43c8ae59c2a067d1af
diff --git a/lib/datasource/maven/index.js b/lib/datasource/maven/index.js index <HASH>..<HASH> 100644 --- a/lib/datasource/maven/index.js +++ b/lib/datasource/maven/index.js @@ -137,6 +137,9 @@ async function downloadHttpProtocol(pkgUrl) { } catch (err) { if (isNotFoundError(err)) { logger.debug(`Url not found ${pkgUrl}`); + } else if (isHostError(err)) { + // istanbul ignore next + logger.warn({ pkgUrl }, 'Cannot connect to maven host'); } else if (isPermissionsIssue(err)) { logger.warn( { pkgUrl }, @@ -165,6 +168,10 @@ function isTemporalError(err) { ); } +function isHostError(err) { + return err.code === 'ETIMEDOUT'; +} + function isNotFoundError(err) { return err.code === 'ENOTFOUND' || err.statusCode === 404; }
refactor(maven): log host error separately
renovatebot_renovate
train
d346ccb1511e4251304889a1aeeba21005ca3f5b
diff --git a/src/bernard/platforms/facebook/web.py b/src/bernard/platforms/facebook/web.py index <HASH>..<HASH> 100644 --- a/src/bernard/platforms/facebook/web.py +++ b/src/bernard/platforms/facebook/web.py @@ -63,7 +63,7 @@ async def receive_events(request: Request): """ Here Facebook might send us a bunch of events/messages that we need to handle. - + The JSON's body is checked using the signature provided in the headers then different message objects are created and forwarded to the FSM. """ @@ -172,7 +172,7 @@ async def unload_js(request: Request): You need to sign the webview using the `sign_webview` parameter of an UrlButton. - + If you want to close/change your page without triggering the page close event, you can call in JS `bernard.unloadNotifier.inhibit()`. """ @@ -182,14 +182,37 @@ async def unload_js(request: Request): script = """ (function () { + var STORAGE_KEY = '_bnd_user'; + function UnloadNotifier() { var self = this, intervalId, ws; + + function getSearch() { + if (window.location.search.indexOf('_bnd_user=') >= 0) { + sessionStorage.setItem( + STORAGE_KEY, + window.location.search + ); + + return window.location.search; + } + + var q = sessionStorage.getItem(STORAGE_KEY); + + if (q) { + return q; + } + } function connect() { - ws = new WebSocket(WS_URL + window.location.search); - ws.onopen = onConnect; + search = getSearch(); + + if (search) { + ws = new WebSocket(WS_URL + search); + ws.onopen = onConnect; + } } function onConnect() { @@ -242,9 +265,9 @@ async def unload_js(request: Request): async def unload_sock(request: Request): """ WebSocket view to detect when Messenger closes the WebView. - + There is a dual mechanism: - + - If "unload" is received over the socket, then close instantly - If no heartbeat is received for some time, them close
Improve the unload notifier Store Bernard user in session to allow page changes
BernardFW_bernard
train
6c4018b73aedbac5c0d011c55ae2cc9a0deb8dfc
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ with open(os.path.join(here, "CHANGES.rst")) as changes: CHANGES = changes.read() with open(os.path.join(here, name, "__init__.py")) as v_file: - version = re.compile(r".*__version__ = '(.*?)'", re.S).match(v_file.read()).group(1) + version = re.compile(r'.*__version__ = "(.*?)"', re.S).match(v_file.read()).group(1) requires = ["pyramid", "redis >= 3.0", "python3-memcached"]
Fix setup.py after black run
Gandi_pyramid_kvs
train
e8588b1cc45e531e5c99d94bdb6e430a6ac81c6b
diff --git a/test/component-view-test.js b/test/component-view-test.js index <HASH>..<HASH> 100644 --- a/test/component-view-test.js +++ b/test/component-view-test.js @@ -14,7 +14,6 @@ var queues = require("can-queues"); var getFragment = require("can-fragment"); var viewCallbacks = require("can-view-callbacks"); var Scope = require("can-view-scope"); -var observe = require("can-observe"); var innerHTML = function(el){ return el && el.innerHTML;
removing can-observe from test that doesn't use it
canjs_can-component
train
8c661be201b7d5a4faf16a9267d5f384a9dd88df
diff --git a/src/BootstrapForm.php b/src/BootstrapForm.php index <HASH>..<HASH> 100644 --- a/src/BootstrapForm.php +++ b/src/BootstrapForm.php @@ -446,7 +446,7 @@ class BootstrapForm { $label = $label === false ? null : $this->getLabelTitle($label, $name); - $value = !$value && $value != 0 ? $label : $value; + $value = is_null($value) ? $label : $value; $labelOptions = $inline ? ['class' => 'radio-inline'] : [];
Refactor Add suggested refactor to work for any false value and not just zero
dwightwatson_bootstrap-form
train
9032ebb45a28deb57fef2928acd72fca25aabbef
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -42,7 +42,7 @@ function parsePath(url) { output.protocols = protocols(parsed) output.protocol = output.protocols[0] output.port = parsed.port - output.resource = parsed.host + output.resource = parsed.hostname output.user = parsed.username || "" output.password = parsed.password || "" output.pathname = parsed.pathname
fix: use hostname instead of host
IonicaBizau_parse-path
train
e0b613e488f30762222bb3d48c8df273a4f8282c
diff --git a/emirdrp/processing/info.py b/emirdrp/processing/info.py index <HASH>..<HASH> 100644 --- a/emirdrp/processing/info.py +++ b/emirdrp/processing/info.py @@ -63,9 +63,9 @@ def gather_info(recipeinput): val = getattr(recipeinput, key) if isinstance(val, DataFrame): metadata[key] = gather_info_dframe(val) - elif isinstance(val, ObservationResult): + elif hasattr(val, 'frames'): metas = [] - for f in val.images: + for f in val.frames: metas.append(gather_info_dframe(f)) metadata[key] = metas else: diff --git a/emirdrp/recipes/image/join.py b/emirdrp/recipes/image/join.py index <HASH>..<HASH> 100644 --- a/emirdrp/recipes/image/join.py +++ b/emirdrp/recipes/image/join.py @@ -743,8 +743,8 @@ from emirdrp.products import SourcesCatalog, CoordinateList2DType class FullDitheredImagesRecipe(JoinDitheredImagesRecipe): obresult = ObservationResultRequirement(query_opts=Result('frame', node='children')) master_bpm = MasterBadPixelMaskRequirement() - extinction = Extinction_Requirement() - sources = Catalog_Requirement() + # extinction = Extinction_Requirement() + # sources = Catalog_Requirement() # offsets = Offsets_Requirement() offsets = Requirement( CoordinateList2DType, @@ -774,9 +774,15 @@ class FullDitheredImagesRecipe(JoinDitheredImagesRecipe): obresult = rinput.obresult + # just in case images are in result, instead of frames + if not obresult.frames: + frames = obresult.results + else: + frames = obresult.frames + img_info = [] data_hdul = [] - for f in rinput.obresult.frames: + for f in frames: img = f.open() data_hdul.append(img) info = {}
Support passing a DB ObservationResult
guaix-ucm_pyemir
train
c6c8b765064c3ed19e5d2acc5452523f9ee930b5
diff --git a/samples/booking/app/controllers/hotels.go b/samples/booking/app/controllers/hotels.go index <HASH>..<HASH> 100644 --- a/samples/booking/app/controllers/hotels.go +++ b/samples/booking/app/controllers/hotels.go @@ -1,6 +1,7 @@ package controllers import ( + "code.google.com/p/go.crypto/bcrypt" "database/sql" "fmt" "github.com/robfig/revel" @@ -124,17 +125,21 @@ func (c Hotels) Settings() rev.Result { } func (c Hotels) SaveSettings(password, verifyPassword string) rev.Result { - user := connected(c.Controller) - user.Password = password - user.Validate(c.Validation) - c.Validation.Required(verifyPassword).Message("VerifyPassword is required") - c.Validation.Required(password == verifyPassword).Message("Your password doesn't match") + models.ValidatePassword(c.Validation, password).Key("password") + c.Validation.Required(verifyPassword). + Key("verifyPassword"). + Message("Please verify your password") + c.Validation.Required(password == verifyPassword). + Key("verifyPassword"). + Message("Your password doesn't match") if c.Validation.HasErrors() { c.Validation.Keep() return c.Redirect(Hotels.Settings) } - _, err := c.Txn.Exec("update User set Password = ? where UserId = ?", - password, user.UserId) + + bcryptPassword, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + _, err := c.Txn.Exec("update User set HashedPassword = ? where UserId = ?", + bcryptPassword, connected(c.Controller).UserId) if err != nil { panic(err) } diff --git a/samples/booking/app/models/user.go b/samples/booking/app/models/user.go index <HASH>..<HASH> 100644 --- a/samples/booking/app/models/user.go +++ b/samples/booking/app/models/user.go @@ -26,14 +26,18 @@ func (u *User) Validate(v *rev.Validation) { rev.Match{userRegex}, ).Key("user.Username") - v.Check(u.Password, - rev.Required{}, - rev.MaxSize{15}, - rev.MinSize{5}, - ).Key("user.Password") + ValidatePassword(v, u.Password).Key("user.Password") v.Check(u.Name, rev.Required{}, rev.MaxSize{100}, ).Key("user.Name") } + +func ValidatePassword(v *rev.Validation, password string) *rev.ValidationResult { + return v.Check(password, + rev.Required{}, + rev.MaxSize{15}, + rev.MinSize{5}, + ) +} diff --git a/samples/booking/app/views/Hotels/Settings.html b/samples/booking/app/views/Hotels/Settings.html index <HASH>..<HASH> 100644 --- a/samples/booking/app/views/Hotels/Settings.html +++ b/samples/booking/app/views/Hotels/Settings.html @@ -4,17 +4,17 @@ <h1>Change your password</h1> <form method="POST" action="{{url "Hotels.SaveSettings"}}"> - {{with $field := field "connected.Password" .}} + {{with $field := field "password" .}} <p class="{{$field.ErrorClass}}"> <strong>Password:</strong> - <input type="password" name="Password" size="16" value="{{.connected.Password}}"> * + <input type="password" name="{{$field.Name}}" size="16"> * <span class="error">{{$field.Error}}</span> </p> {{end}} {{with $field := field "verifyPassword" .}} <p class="{{$field.ErrorClass}}"> <strong>Verify password:</strong> - <input type="password" name="{{$field.Name}}" size="16" value="{{.verifyPassword}}"> * + <input type="password" name="{{$field.Name}}" size="16"> * <span class="error">{{$field.Error}}</span> </p> {{end}}
Update bookings SaveSettings page to bcrypt
revel_revel
train
1748f7fa973dd66e2fab2baee48678610a4c6c94
diff --git a/lib/adhearsion/initializer/asterisk.rb b/lib/adhearsion/initializer/asterisk.rb index <HASH>..<HASH> 100644 --- a/lib/adhearsion/initializer/asterisk.rb +++ b/lib/adhearsion/initializer/asterisk.rb @@ -50,7 +50,7 @@ module Adhearsion end def ami_options - %w(host port username password events).inject({}) do |options, property| + %w(host port username password events auto_reconnect).inject({}) do |options, property| options[property.to_sym] = config.ami.send property options end diff --git a/lib/adhearsion/initializer/configuration.rb b/lib/adhearsion/initializer/configuration.rb index <HASH>..<HASH> 100644 --- a/lib/adhearsion/initializer/configuration.rb +++ b/lib/adhearsion/initializer/configuration.rb @@ -129,8 +129,8 @@ module Adhearsion end def initialize(overrides = {}) - @listening_port = overrides.has_key?(:port) ? overrides.delete(:port) : self.class.default_listening_port @listening_host = overrides.has_key?(:host) ? overrides.delete(:host) : self.class.default_listening_host + @listening_port = overrides.has_key?(:port) ? overrides.delete(:port) : self.class.default_listening_port super end end @@ -158,7 +158,7 @@ module Adhearsion end class AMIConfiguration < AbstractConfiguration - attr_accessor :port, :username, :password, :events, :host + attr_accessor :port, :username, :password, :events, :host, :auto_reconnect class << self def default_port @@ -172,12 +172,17 @@ module Adhearsion def default_host 'localhost' end + + def default_auto_reconnect + true + end end def initialize(overrides = {}) - self.host = self.class.default_host - self.port = self.class.default_port - self.events = self.class.default_events + self.host = self.class.default_host + self.port = self.class.default_port + self.events = self.class.default_events + self.auto_reconnect = self.class.default_auto_reconnect super end end diff --git a/lib/adhearsion/voip/asterisk/manager_interface.rb b/lib/adhearsion/voip/asterisk/manager_interface.rb index <HASH>..<HASH> 100644 --- a/lib/adhearsion/voip/asterisk/manager_interface.rb +++ b/lib/adhearsion/voip/asterisk/manager_interface.rb @@ -108,8 +108,9 @@ module Adhearsion # @param [Hash] options Available options are :host, :port, :username, :password, and :events # def initialize(options={}) +puts options.inspect options = parse_options options - +puts options.inspect @host = options[:host] @username = options[:username] @password = options[:password]
Respect the :auto_reconnect setting for AMI
adhearsion_adhearsion
train
645e4007476d20244304dcb5d96874a54a4f6f9c
diff --git a/sdk/framework/backend_test.go b/sdk/framework/backend_test.go index <HASH>..<HASH> 100644 --- a/sdk/framework/backend_test.go +++ b/sdk/framework/backend_test.go @@ -2,8 +2,6 @@ package framework import ( "context" - "github.com/hashicorp/go-secure-stdlib/strutil" - "github.com/stretchr/testify/require" "net/http" "reflect" "strings" @@ -11,6 +9,9 @@ import ( "testing" "time" + "github.com/hashicorp/go-secure-stdlib/strutil" + "github.com/stretchr/testify/require" + "github.com/hashicorp/vault/sdk/helper/consts" "github.com/hashicorp/vault/sdk/logical" )
Run `make fmt` (#<I>)
hashicorp_vault
train